code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
class Dog extends object
begin
function __init__ self name dtype
begin
comment 定义类的属性
comment self.name = name 公有属性
comment self.__name = name 私有属性
set name = name
set dtype = dtype
end function
comment 定义类的方法
function shout self
begin
print string I'm %s, type: %s % tuple name dtype
end function
end class
comment clas... | class Dog(object):
def __init__(self, name, dtype):
# 定义类的属性
# self.name = name 公有属性
# self.__name = name 私有属性
self.name = name
self.dtype = dtype
# 定义类的方法
def shout(self):
print('I\'m %s, type: %s' % (self.name, self.dtype))
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
string Created on Fri Apr 7 14:56:22 2017 @author: a
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
close plt string all
set xkW = list 0.002 30
set yCost = list 0.022 20
set pkWCost = call polyfit call log10 xkW call... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 7 14:56:22 2017
@author: a
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
plt.close('all')
xkW=[0.002,30]
yCost=[0.022,20]
pkWCost=np.polyfit(np.log10(xkW),np.log10(yCost),1)
numPoint=10000
xkWArra... | Python | zaydzuhri_stack_edu_python |
function merge_sort array left_index right_index
begin
if left_index > right_index
begin
return
end
set middle = left_index + right_index // 2
call merge_sort array left_index middle
call merge_sort array middle + 1 right_index
merge array left_index right_index middle
end function
string We use the // operator to be e... | def merge_sort(array, left_index, right_index):
if left_index > right_index:
return
middle = (left_index + right_index)//2
merge_sort(array, left_index, middle)
merge_sort(array, middle + 1, right_index)
merge(array, left_index, right_index, middle)
"""
We use the // operator to b... | Python | zaydzuhri_stack_edu_python |
function _runGenTarget self
begin
return exists path join path distutilTargetPackagePath string gen.py
end function | def _runGenTarget(self):
return os.path.exists(os.path.join(self.__buildConfiguration.distutilTargetPackagePath,
"gen.py")) | Python | nomic_cornstack_python_v1 |
import boto3
string medium blog post code to do basic boto3 commands to access s3, view buckets, view objects, upload files from local, download files to local, delete objects, and delete buckets
comment connect to client / credentials
set s3_client = call resource string s3
print s3_client
comment s3.ServiceResource()... | import boto3
"""
medium blog post code to do basic boto3 commands to access s3, view buckets, view objects,
upload files from local, download files to local, delete objects, and delete buckets
"""
# connect to client / credentials
s3_client = boto3.resource('s3')
print(s3_client)
# s3.ServiceResource()
# create buc... | Python | zaydzuhri_stack_edu_python |
function count_substrings string k
begin
comment Remove special characters and numbers from the string
set cleaned_string = join string generator expression char for char in string if is alpha char
comment Initialize a counter to keep track of the number of substrings
set count = 0
comment Loop through all possible su... | def count_substrings(string, k):
# Remove special characters and numbers from the string
cleaned_string = ''.join(char for char in string if char.isalpha())
# Initialize a counter to keep track of the number of substrings
count = 0
# Loop through all possible substrings
for i in range(... | Python | jtatman_500k |
from unittest import TestCase
from A4 import crud
from A4 import student
class TestFileWrite extends TestCase
begin
function test_file_write_normal_case self
begin
set new_student = call Student string Kylo string Purcell string A01088857 true list 80 90 70
set filename = string testfile1.txt
call file_write new_studen... | from unittest import TestCase
from A4 import crud
from A4 import student
class TestFileWrite(TestCase):
def test_file_write_normal_case(self):
new_student = student.Student('Kylo', 'Purcell', 'A01088857', True, [80, 90, 70])
filename = 'testfile1.txt'
crud.file_write(new_student, filename)... | Python | zaydzuhri_stack_edu_python |
function reveal_next_dot canvas dot_list index
begin
call itemconfig dot_list at index state=string normal
return dot_list at index
end function | def reveal_next_dot(canvas, dot_list, index):
canvas.itemconfig(dot_list[index], state='normal')
return dot_list[index] | Python | nomic_cornstack_python_v1 |
function pdktimestamp tt
begin
set x = call fromtimestamp tt
set ans = string %s.%03d % tuple string format time x string %Y-%m-%d %H:%M:%S microsecond / 1000
return ans
end function | def pdktimestamp(tt):
x = datetime.datetime.fromtimestamp(tt)
ans = "%s.%03d" % (x.strftime("%Y-%m-%d %H:%M:%S"),
(x.microsecond / 1000))
return ans | Python | nomic_cornstack_python_v1 |
import sys
import os
import copy
import random
import numpy as np
import math
from tqdm import tqdm
from collections import defaultdict
from datetime import datetime , timezone , timedelta
import seaborn as sns
import matplotlib.pyplot as plt
set dayDict = dict string Monday 1 ; string Tuesday 2 ; string Wednesday 3 ; ... | import sys
import os
import copy
import random
import numpy as np
import math
from tqdm import tqdm
from collections import defaultdict
from datetime import datetime, timezone, timedelta
import seaborn as sns
import matplotlib.pyplot as plt
dayDict = {
"Monday":1,
"Tuesday":2,
"Wednesday":3,
"Thursday":4,
"Frida... | Python | zaydzuhri_stack_edu_python |
class Node extends object
begin
function __init__ self
begin
set in_degree = 0
set cur_inputs = 0
set dest = list
end function
function __str__ self
begin
return format string in_degree:{}, cur_inputs:{}, dests:{} in_degree cur_inputs dest
end function
end class
function bfs edges N used
begin
from collections import ... | class Node(object):
def __init__(self):
self.in_degree = 0
self.cur_inputs = 0
self.dest = []
def __str__(self):
return "in_degree:{}, cur_inputs:{}, dests:{}".format(self.in_degree, self.cur_inputs, self.dest)
def bfs(edges, N, used):
from collections import dequ... | Python | zaydzuhri_stack_edu_python |
comment operator##
comment a='5'
comment b='6'
comment print (a+b)
comment print(str.__add__(a,b))
comment operator
class Student
begin
function __init__ self m1 m2
begin
set m1 = m1
set m2 = m2
end function
function __add__ self other
begin
set m1 = m1 + m1
set m2 = m2 + m2
set s3 = call Student m1 m2
return s3
end fu... | ###operator##
#a='5'
#b='6'
#print (a+b)
#print(str.__add__(a,b))
###operator
class Student:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def __add__(self, other):
m1 = self.m1 + other.m1
m2 = self.m2 + other.m2
s3 = Student(m1,m2)
return s3
def __gt__... | Python | zaydzuhri_stack_edu_python |
comment 9.Define a function max_of_three() that takes three numbers as arguments and returns the largest of them.
function max_of_three a b c
begin
comment DocString
string Function to find out the maximum of three numbers
if a > b
begin
if a > c
begin
return a
end
else
begin
return c
end
end
else
if b > c
begin
return... | #9.Define a function max_of_three() that takes three numbers as arguments and returns the largest of them.
def max_of_three(a,b,c):
#DocString
""" Function to find out the maximum of three numbers """
if a > b:
if a > c:
return a
else:
return c
else:
... | Python | zaydzuhri_stack_edu_python |
import sys
import pygame
import random
import math
comment Moves the rectangle back onto the screen.
comment Input: PyGame rect. Number. Number.
comment Output: PyGame rect.
function clampRect rect width height
begin
set new = rect
if left < 0
begin
set new = move list - left 0
end
if right > width
begin
set new = move... | import sys
import pygame
import random
import math
# Moves the rectangle back onto the screen.
# Input: PyGame rect. Number. Number.
# Output: PyGame rect.
def clampRect(rect, width, height):
new = rect
if new.left < 0:
new = new.move([-new.left, 0])
if new.right > width:
new = new.move([width - new.right, 0])
... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
import numpy as np
import pylab
comment %%
set size = 100
set inputs = call placeholder float32 list none size size 1 name=string image
set lifegame = call placeholder int8 list 1 size size 1 name=string lifegame
with call name_scope string count
begin
set flt = call constant array list list 1 1... | import tensorflow as tf
import numpy as np
import pylab
#%%
size = 100
inputs = tf.placeholder(tf.float32, [None, size, size, 1], name="image")
lifegame = tf.placeholder(tf.int8, [1, size, size, 1], name="lifegame")
with tf.name_scope("count"):
flt = tf.initializers.constant(np.array([
[1, 1, 1],
[1, 0, ... | Python | zaydzuhri_stack_edu_python |
comment Cell 1
from abc import ABC , abstractmethod
from scipy.io import wavfile
import math , pyaudio
import numpy as np
class Oscillator extends ABC
begin
string The property ._freq represents the fundamental frequency of the oscillator, this doesn’t change, and the property ._f represents the altered frequency which... | # Cell 1
from abc import ABC, abstractmethod
from scipy.io import wavfile
import math, pyaudio
import numpy as np
class Oscillator(ABC):
"""
The property ._freq represents the fundamental frequency
of the oscillator, this doesn’t change, and the property ._f
represents the altered frequency which is th... | Python | zaydzuhri_stack_edu_python |
function _add gvar
begin
comment Check for mandatory arguments.
set _missing = list
if string target-user not in gvar at string user_settings
begin
append _missing string -U|--target-user
end
if string target-password not in gvar at string user_settings
begin
append _missing string -P|--target-password
end
if string t... | def _add(gvar):
# Check for mandatory arguments.
_missing = []
if 'target-user' not in gvar['user_settings']:
_missing.append('-U|--target-user')
if 'target-password' not in gvar['user_settings']:
_missing.append('-P|--target-password')
if 'target-common-name' not in gvar['user_se... | Python | nomic_cornstack_python_v1 |
function test_post authenticated_client
begin
set observable_json = dict string value string asd.com ; string type string domain-name
set rv = post string /api/observables/ data=dumps observable_json content_type=string application/json
set response = loads data
assert is instance response at string id int
end function | def test_post(authenticated_client):
observable_json = {'value': 'asd.com', 'type': 'domain-name'}
rv = authenticated_client.post('/api/observables/',
data=json.dumps(observable_json),
content_type='application/json')
response = json.load... | Python | nomic_cornstack_python_v1 |
function getEquispaceGrid n_dim rng subdivisions
begin
return array list comprehension array range subdivisions + 1 * rng * 1.0 / subdivisions for i in range n_dim
end function | def getEquispaceGrid(n_dim, rng, subdivisions):
return np.array(
[
np.array(range(subdivisions + 1)) * rng * 1.0 / subdivisions
for i in range(n_dim)
]
) | Python | nomic_cornstack_python_v1 |
function create_attr_dict filename check
begin
set xl_workbook = call open_workbook filename
set specificAttributeString = string {
set specificAttributeDict = dict
set xl_sheet = call sheet_by_name check
for row in range nrows
begin
if row > 0
begin
set cell = call cell row 8
set specificAttributeString = specificAtt... | def create_attr_dict(filename, check):
xl_workbook = xlrd.open_workbook(filename)
specificAttributeString = '{'
specificAttributeDict = {}
xl_sheet = xl_workbook.sheet_by_name(check)
for row in range(xl_sheet.nrows):
if row>0:
cell = xl_sheet.cell(row,8)
specificAttri... | Python | nomic_cornstack_python_v1 |
comment 用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb
comment name = ['oldboy','alex','wusir']
comment ret = map(lambda name: name + "_sb", name)
comment print(list(ret))
comment 用map来处理下述l,然后用list得到一个新的列表,列表中每个人的名字都是sb结尾
comment l = [{'name': 'alex'}, {'name': 'y'}]
comment ret = map(lambda nam: nam['name']+'sb', l)
comment pri... | # 用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb
# name = ['oldboy','alex','wusir']
# ret = map(lambda name: name + "_sb", name)
# print(list(ret))
# 用map来处理下述l,然后用list得到一个新的列表,列表中每个人的名字都是sb结尾
# l = [{'name': 'alex'}, {'name': 'y'}]
# ret = map(lambda nam: nam['name']+'sb', l)
# print(list(ret))
# 用filter来处理,得到股票价格大于20的股票名字
#
# s... | Python | zaydzuhri_stack_edu_python |
function get_sides self combatant
begin
comment get all entities involved in combat by looking up their combathandlers
set combatants = list comprehension comb for comb in contents if has attribute comb string scripts and call has key
set location = location
if has attribute location string allow_pvp and allow_pvp
begi... | def get_sides(self, combatant):
# get all entities involved in combat by looking up their combathandlers
combatants = [
comb
for comb in self.obj.location.contents
if hasattr(comb, "scripts") and comb.scripts.has(self.key)
]
location = self.obj.locatio... | Python | nomic_cornstack_python_v1 |
function printIntro
begin
print string Greetings there
end function | def printIntro():
print('Greetings there') | Python | nomic_cornstack_python_v1 |
comment requirements.txt: requests termcolor
string Investments distribution calculator
import argparse
import logging
import math
import operator
from decimal import Decimal
from typing import List
import requests
from termcolor import colored
import pcli.log
set log = call getLogger
class Actions
begin
set SHOW = str... | # requirements.txt: requests termcolor
"""Investments distribution calculator"""
import argparse
import logging
import math
import operator
from decimal import Decimal
from typing import List
import requests
from termcolor import colored
import pcli.log
log = logging.getLogger()
class Actions:
SHOW = "show... | Python | zaydzuhri_stack_edu_python |
function update_Atoms self Theta=none update_jacobian=false
begin
if Theta is not none
begin
comment If necessary, update Theta
set Theta = Theta
end
if update_jacobian
begin
set tuple Atoms Jacobians = call compute_Atoms_matrix return_jacobian=true
end
else
begin
set Atoms = call compute_Atoms_matrix return_jacobian=f... | def update_Atoms(self,Theta=None,update_jacobian=False):
if Theta is not None:
self.Theta = Theta # If necessary, update Theta
if update_jacobian:
self.Atoms, self.Jacobians = self.compute_Atoms_matrix(return_jacobian=True)
else:
self.Atoms = self.compute_Atom... | Python | nomic_cornstack_python_v1 |
from numpy import *
set x = array eval input string vetor:
set i = 0
set n = 0
set p = 0
set w = 0
while i < size x
begin
if x at i > 0
begin
set p = p + 1
end
set i = i + 1
end
set k = zeros p dtype=int
while n < size x
begin
if x at n >= 0
begin
set k at w = x at n
set w = w + 1
end
set n = n + 1
end
print k | from numpy import*
x = array(eval(input("vetor: ")))
i =0
n=0
p =0
w=0
while(i<size(x)):
if(x[i]>0):
p= p+1
i = i+1
k = zeros(p, dtype=int)
while(n<size(x)):
if(x[n]>=0):
k[w]=x[n]
w = w +1
n = n+1
print(k) | Python | zaydzuhri_stack_edu_python |
while response not in list string CO string EN string BF
begin
set response = upper call raw_input string
end
set stri = list comprehension i for i in call raw_input string Phrase:
set phrase = list
set num = string
if response != string BF
begin
while type num != int
begin
try
begin
set num = integer call raw_input ... | while response not in ["CO", "EN", "BF"]:
response = raw_input("").upper()
stri = [i for i in raw_input("Phrase: ")]
phrase = []
num = ""
if response != "BF":
while type(num) != int:
try: num = int(raw_input("Number: "))
except ValueError: num=""
if not 0 <= num <= 26: num = ""
if res... | Python | zaydzuhri_stack_edu_python |
function has_food text
begin
return any generator expression food in lower text for food in FOOD_PATTERNS
end function | def has_food(text):
return any(food in text.lower() for food in FOOD_PATTERNS) | Python | nomic_cornstack_python_v1 |
function main
begin
set num = 3
if 1 < num and num < 5
begin
print true
end
else
begin
print false
end
end function
call main | def main():
num = 3
if 1 < num and num < 5:
print(True)
else:
print(False)
main()
| Python | zaydzuhri_stack_edu_python |
function save self **kwargs
begin
if pk
begin
set topic_modification_date = now
end
save keyword kwargs
end function | def save(self, **kwargs):
if self.pk:
self.topic_modification_date = datetime.now()
super(Topic, self).save(**kwargs) | Python | nomic_cornstack_python_v1 |
function Yinghui_method self ponteiro
begin
set K = K at tuple slice : : ponteiro
set x = x at tuple slice : : ponteiro
set z = z at tuple slice : : ponteiro
set K1 = max K axis=0
set KNc = min K axis=0
set z1 = T
set aux = ones shape dtype=bool
set aux at K == K1 at tuple newaxis slice : : = false
set aux ... | def Yinghui_method(self, ponteiro):
K = self.K[:,ponteiro]
x = self.x[:,ponteiro]
z = self.z[:,ponteiro]
K1 = np.max(K, axis = 0); KNc = np.min(K, axis = 0)
z1 = z.T[(K == K1[np.newaxis,:]).T].T
aux = np.ones(K.shape, dtype = bool)
aux[K == K1[np.newaxis,:]] = Fa... | Python | nomic_cornstack_python_v1 |
import binascii
import re
import md5
set INPUT_FILE = string input.txt
function md5Hash x
begin
set m = call new
update m string x
return call hexlify call digest
end function
class Program
begin
function __init__ self name connectedPrograms
begin
set name = name
set connectedPrograms = connectedPrograms
end function
f... | import binascii
import re
import md5
INPUT_FILE = "input.txt"
def md5Hash(x):
m = md5.new()
m.update(str(x))
return binascii.hexlify(m.digest())
class Program():
def __init__(self, name, connectedPrograms):
self.name = name
self.connectedPrograms = connectedPrograms
def __str__(self):
return "{} connected... | Python | zaydzuhri_stack_edu_python |
string Calulates the order parameter for all the given atoms in the lipid chains (using the Ci-1 - Ci - Ci+1 vector). It prints the XY coordinate of the phosphate headgroup followed by all the order parameters belonging to that lipid. Useful for building bidimensional maps of the lipid order.
set XTC = string NP61-POPC... | """
Calulates the order parameter for all the given atoms in the lipid chains (using the Ci-1 - Ci - Ci+1 vector).
It prints the XY coordinate of the phosphate headgroup followed by all the order parameters belonging to that lipid.
Useful for building bidimensional maps of the lipid order.
"""
XTC = "NP61-POPC6-46_PRO1... | Python | zaydzuhri_stack_edu_python |
function reddit_auth self
begin
set Reddit = call oauth
end function | def reddit_auth(self):
self.Reddit = self.oauth() | Python | nomic_cornstack_python_v1 |
function get_daily_historic_data self ticker start_date end_date
begin
set av_url = call _construct_alpha_vantage_symbol_call ticker
try
begin
set av_data_js = get requests av_url
set data = loads text at string Time Series (Daily)
end
except Exception as e
begin
print string Could not download AlphaVantage data for %s... | def get_daily_historic_data(self, ticker, start_date, end_date):
av_url = self._construct_alpha_vantage_symbol_call(ticker)
try:
av_data_js = requests.get(av_url)
data = json.loads(av_data_js.text)['Time Series (Daily)']
except Exception as e:
print(
... | Python | nomic_cornstack_python_v1 |
function pref_password
begin
set form = call UserNewPassword
comment print current_user
if method == string POST
begin
print
info string updating user password
comment for debugging purposes
for f_field in form
begin
info string form name : %s / form data : %s name data
end
if call validate_on_submit
begin
set existing... | def pref_password():
form = UserNewPassword()
# print current_user
if request.method == 'POST' :
print
log_cis.info("updating user password \n")
# for debugging purposes
for f_field in form :
log_cis.info( "form name : %s / form data : %s ", f_field.name, f_field.data )
if form.validate_on_sub... | Python | nomic_cornstack_python_v1 |
import string
import random
function generate_password length
begin
set password_chars = ascii_letters + digits + punctuation
return join string generator expression random choice password_chars for i in range length
end function
print call generate_password 20 | import string
import random
def generate_password(length):
password_chars = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(password_chars) for i in range(length))
print(generate_password(20)) | Python | jtatman_500k |
function old_province self old_province
begin
set _old_province = old_province
end function | def old_province(self, old_province):
self._old_province = old_province | Python | nomic_cornstack_python_v1 |
import sys
function LI
begin
return list map int split right strip read line stdin
end function
set tuple a b c = call LI
if c % 2 == 0
begin
set c = 2
end
else
begin
set c = 3
end
set a_ = power a c
set b_ = power b c
set ans = string
if a_ < b_
begin
set ans = string <
end
else
if a_ > b_
begin
set ans = string >
en... | import sys
def LI(): return list(map(int, sys.stdin.readline().rstrip().split()))
a, b, c = LI()
if c%2==0:
c = 2
else:
c = 3
a_ = pow(a, c)
b_ = pow(b, c)
ans = ''
if a_ < b_:
ans = '<'
elif a_ > b_:
ans = '>'
else:
ans = '='
print(ans) | Python | zaydzuhri_stack_edu_python |
function get_auth_token fullname _days _seconds=0
begin
try
begin
set payload = call getPayLoad fullname _days _seconds
return tuple true call encode_auth_token_HS256 payload
end
except Exception as e
begin
return tuple false e
end
end function | def get_auth_token(fullname, _days, _seconds = 0):
try:
payload = getPayLoad(fullname, _days, _seconds)
return True, encode_auth_token_HS256(payload)
except Exception as e:
return False, e | Python | nomic_cornstack_python_v1 |
function getMaxBirthProb self
begin
return maxBirthProb
end function | def getMaxBirthProb(self):
return self.maxBirthProb | Python | nomic_cornstack_python_v1 |
for firstNum in firstList
begin
for secondNum in secondList
begin
if firstNum == secondNum
begin
append sameNum firstNum
end
end
end
set cleanList = list
for x in sameNum
begin
if x not in cleanList
begin
append cleanList x
end
end
print cleanList
set numsList = firstList + secondList
print string Suurim number on: + ... | for firstNum in firstList:
for secondNum in secondList:
if firstNum == secondNum:
sameNum.append(firstNum)
cleanList = []
for x in sameNum:
if x not in cleanList:
cleanList.append(x)
print(cleanList)
numsList = firstList + secondList
print("Suurim number on: " + format(max(numsList)... | Python | zaydzuhri_stack_edu_python |
function fuel mass
begin
return mass // 3 - 2
end function
function theRocketEq mass
begin
set neededFuel = call fuel mass
set totalFuel = neededFuel
while neededFuel > 0
begin
set neededFuel = call fuel neededFuel
if neededFuel < 0
begin
break
end
set totalFuel = totalFuel + neededFuel
end
return totalFuel
end functio... | def fuel(mass: int):
return mass // 3 - 2
def theRocketEq(mass: int):
neededFuel = fuel(mass)
totalFuel = neededFuel
while neededFuel > 0:
neededFuel = fuel(neededFuel)
if neededFuel < 0:
break
totalFuel += neededFuel
return totalFuel
print(theRocketEq(100756)... | Python | zaydzuhri_stack_edu_python |
function apply_boundary_conditions self t value_vector dx
begin
set value_vector at 0 = call left_constant t - left_neumann_parameter * value_vector at 1 / dx / left_dirichlet_parameter - left_neumann_parameter / dx
set value_vector at - 1 = call right_constant t + right_neumann_parameter * value_vector at - 2 / dx / r... | def apply_boundary_conditions(self, t, value_vector, dx):
value_vector[0] = (self.left_constant(t) - self.left_neumann_parameter*value_vector[1]/dx) \
/ (self.left_dirichlet_parameter - self.left_neumann_parameter/dx)
value_vector[-1] = (self.right_constant(t) + self.right_neumann_paramet... | Python | nomic_cornstack_python_v1 |
function make_summary_table train_result val_result plot=true save_dir=none prepend=string save=false
begin
string Makes a matplotlib table object with relevant data. Thanks to Lucas Manuelli for the contribution. Parameters ---------- train_result: ClassificationResult result on train split val_result: Classification... | def make_summary_table(train_result, val_result, plot=True, save_dir=None, prepend="", save=False):
"""
Makes a matplotlib table object with relevant data.
Thanks to Lucas Manuelli for the contribution.
Parameters
----------
train_result: ClassificationResult
... | Python | jtatman_500k |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
import time
string selenium 是一套完整的web应用程序测试系统,包含了测试的录制(selenium IDE),编写及运行(Selenium Remote Control)和测试的并行处理(Selenium Grid) executable_path 驱动路径 geckodriv... | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
import time
"""
selenium 是一套完整的web应用程序测试系统,包含了测试的录制(selenium IDE),编写及运行(Selenium Remote Control)和测试的并行处理(Selenium Grid)
executable_path 驱动路径
geckodriver.... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Sep 14 14:38:44 2021 @author: Velez
class Card
begin
function __init__ self Name CardType
begin
set name = Name
set cardtype = CardType
end function
function Info self
begin
print name cardtype
end function
end class
class CityCard extends Card
begin
function __init__... | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 14 14:38:44 2021
@author: Velez
"""
class Card():
def __init__(self,Name,CardType):
self.name=Name
self.cardtype=CardType
def Info(self):
print(self.name,self.cardtype)
class CityCard(Card):
def __init__(self,Na... | Python | zaydzuhri_stack_edu_python |
import socket , os , json
import sys , time
set base_dir = directory name path directory name path absolute path path __file__
set file_dir = string %s/%s % tuple base_dir string ftp_server
append path file_dir
print base_dir
from conf import settings
import optparse
import getpass
import hashlib
set STATUS_CODE = dict... | import socket,os,json
import sys,time
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
file_dir = '%s/%s'%(base_dir,'ftp_server')
sys.path.append(file_dir)
print(base_dir)
from conf import settings
import optparse
import getpass
import hashlib
STATUS_CODE = {
250:"invalid cmd fo... | Python | zaydzuhri_stack_edu_python |
function add_alarm title content news weather from_log=false
begin
comment working on time format
set alarm_time = replace content string T string
set delay = call date_difference alarm_time
set alarm_time = call readable_date alarm_time
if delay >= 0 or from_log
begin
comment call function / logging / assign alarm val... | def add_alarm(title, content, news, weather, from_log=False):
# working on time format
alarm_time = content.replace('T', ' ')
delay = date_difference(alarm_time)
alarm_time = readable_date(alarm_time)
if delay >= 0 or from_log:
# call function / logging / assign alarm values / refresh
... | Python | nomic_cornstack_python_v1 |
function test_disable_hidden_api_low_sdk self
begin
call _make_client_with_extra_adb_properties dict string ro.build.version.codename string O ; string ro.build.version.sdk string 26
set is_rootable = true
call _disable_hidden_api_blocklist
call assert_not_called
end function | def test_disable_hidden_api_low_sdk(self):
self._make_client_with_extra_adb_properties({
'ro.build.version.codename': 'O',
'ro.build.version.sdk': '26',
})
self.device.is_rootable = True
self.client._disable_hidden_api_blocklist()
self.adb.mock_shell_func.assert_not_called() | Python | nomic_cornstack_python_v1 |
from kütüphane import *
print string **************************************** Kütüphane Programına Hoşgeldiniz Yapmak İsteğeceğiniz İşlem Numaraları ve Açıklamaları: 1. Kitapları Göster 2. Kitap Sorgulama 3. Kitap Ekle 4. Kitap Sil 5. Baskı Yükselt İşlemi sonlandırmak için 'q' ya basını ********************************... | from kütüphane import *
print("""
****************************************
Kütüphane Programına Hoşgeldiniz
Yapmak İsteğeceğiniz İşlem Numaraları ve Açıklamaları:
1. Kitapları Göster
2. Kitap Sorgulama
3. Kitap Ekle
4. Kitap Sil
5. Baskı Yükselt
İşlemi sonlandırmak için 'q' ya basını
**************************... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string Generates 'example_layout.yaml' from 'example_layout.yaml.templ' and the default values in 'layout.py'
import layout
import os
from string import Template
set EXAMPLE_LAYOUT = string example_layout.yaml
set EXAMPLE_LAYOUT_TEMPL = string example_layout.yaml.templ
if __name__ == string... | #!/usr/bin/env python
"""Generates 'example_layout.yaml' from 'example_layout.yaml.templ' and
the default values in 'layout.py'"""
import layout
import os
from string import Template
EXAMPLE_LAYOUT = "example_layout.yaml"
EXAMPLE_LAYOUT_TEMPL = "example_layout.yaml.templ"
if __name__ == '__main__':
if not os.pat... | Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
return string Car with the maximum speed of + string max_speed + string + speed_unit
end function | def __str__(self):
return "Car with the maximum speed of " + str(self.max_speed) + \
" " + self.speed_unit | Python | nomic_cornstack_python_v1 |
function audit_latitude_longitude value start end tolerance
begin
set r = false
if call is_float value
begin
set value = decimal value
if call almost_within value start end tolerance
begin
set r = true
end
end
return r
end function | def audit_latitude_longitude(value, start, end, tolerance):
r = False
if is_float(value):
value = float(value)
if almost_within(value, start, end, tolerance):
r = True
return r | Python | nomic_cornstack_python_v1 |
function _append_word_to_file file_path word
begin
with open string file_path string a+ encoding=string utf-8 as fp
begin
write fp word + string
end
end function | def _append_word_to_file(file_path: Path, word: str):
with open(str(file_path), 'a+', encoding='utf-8') as fp:
fp.write(word + '\n') | Python | nomic_cornstack_python_v1 |
function create self **kwargs
begin
set kwargs = dict none defaults ; none kwargs
set kwargs = call run_subfactories kwargs
return call create_instance keyword kwargs
end function | def create(self, **kwargs):
kwargs = {**self.defaults, **kwargs}
kwargs = self.run_subfactories(kwargs)
return self.create_instance(**kwargs) | Python | nomic_cornstack_python_v1 |
import struct
import time
import usb.core
class Sample extends object
begin
set FORMAT = string <BBBHHHhhhhhhhhh
set NBYTES = call calcsize FORMAT
function __init__ self buf offset
begin
set tpl = call unpack_from FORMAT buf offset
set node_id = tpl at 0
set last_sequence_no = tpl at 1
set status = tpl at 2
set gyro_ti... | import struct
import time
import usb.core
class Sample(object):
FORMAT = "<BBBHHHhhhhhhhhh"
NBYTES = struct.calcsize(FORMAT)
def __init__(self, buf, offset):
tpl = struct.unpack_from(Sample.FORMAT, buf, offset)
self.node_id = tpl[0]
self.last_sequence_no = tpl[1]
self.stat... | Python | zaydzuhri_stack_edu_python |
function horizontalMatrix
begin
set a = list list string a string b string c string d list string f string g string h string i list string k string l string m string n list string p string q string r string s
set row = length a
set col = length a at 0
for i in range row
begin
for j in range col
begin
print a at i at j ... | def horizontalMatrix():
a = [['a','b','c','d'],['f','g','h','i'],['k','l','m','n'],['p','q','r','s']]
row = len(a)
col = len(a[0])
for i in range(row):
for j in range(col):
print(a[i][j], end=" ")
print("\n")
horizontalMatrix()
print("========")
def verticalMatrix():
a = [['a','b'... | Python | zaydzuhri_stack_edu_python |
function _get_advertisement_interval self
begin
return __advertisement_interval
end function | def _get_advertisement_interval(self):
return self.__advertisement_interval | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python3
import concurrent.futures
import time
import logging
from readerwriterlock import rwlock
from logdecorator import log_on_start , log_on_end , log_on_error
set DEBUG = DEBUG
set logging_format = string %(asctime)s: %(message)s
call basicConfig format=logging_format level=INFO datefmt=string %H... | #! /usr/bin/python3
import concurrent.futures
import time
import logging
from readerwriterlock import rwlock
from logdecorator import log_on_start, log_on_end, log_on_error
DEBUG = logging.DEBUG
logging_format = "%(asctime)s: %(message)s"
logging.basicConfig(format=logging_format, level=logging.INFO,
... | Python | zaydzuhri_stack_edu_python |
from astropy.io import fits
from astropy.utils.exceptions import AstropyUserWarning
import warnings
from pathlib import Path
import argparse
set parser = call ArgumentParser description=string Simple tool to check for corrupted fits file images. epilog=string Please email hsouchereau@outlook.com for help inquiries or b... | from astropy.io import fits
from astropy.utils.exceptions import AstropyUserWarning
import warnings
from pathlib import Path
import argparse
parser = argparse.ArgumentParser(description="Simple tool to check for corrupted fits file images.",
epilog="Please email hsouchereau@outl... | Python | zaydzuhri_stack_edu_python |
import abc
import copy
class Node
begin
string Abstract data type for tree node
decorator abstractmethod
function __init__ self
begin
return
end function
decorator abstractmethod
function isEmpty self
begin
return
end function
decorator abstractmethod
function insert self val
begin
return
end function
decorator abstrac... | import abc
import copy
class Node:
"""Abstract data type for tree node"""
@abc.abstractmethod
def __init__(self):
return
@abc.abstractmethod
def isEmpty(self):
return
@abc.abstractmethod
def insert(self,val):
return
@abc.abstractmethod
def member(self,... | Python | zaydzuhri_stack_edu_python |
function get_key_value self
begin
return get attribute self name
end function | def get_key_value(self):
return getattr(self, self.__class__._meta.primary_key.name) | Python | nomic_cornstack_python_v1 |
function add_friends_to_dB follower_id friends_list
begin
set xmatrix = db at string xmatrix
update xmatrix dict string _id follower_id dict string $addToSet dict string follows dict string $each friends_list
end function | def add_friends_to_dB(follower_id,friends_list):
xmatrix = db['xmatrix']
xmatrix.update({'_id':follower_id},
{'$addToSet':{
'follows':{
'$each':friends_list
}
... | Python | nomic_cornstack_python_v1 |
function set_module_args args
begin
set args = dumps dict string ANSIBLE_MODULE_ARGS args
comment pylint: disable=protected-access
set _ANSIBLE_ARGS = call to_bytes args
end function | def set_module_args(args):
args = json.dumps({'ANSIBLE_MODULE_ARGS': args})
basic._ANSIBLE_ARGS = to_bytes(args) # pylint: disable=protected-access | Python | nomic_cornstack_python_v1 |
import feedparser
set URLS = list string https://www.dailytelegraph.com.au/news/breaking-news/rss string https://www.dailytelegraph.com.au/newslocal/parramatta/rss string https://www.dailytelegraph.com.au/news/nsw/rss string https://www.dailytelegraph.com.au/news/national/rss string https://www.dailytelegraph.com.au/ne... | import feedparser
URLS = ["https://www.dailytelegraph.com.au/news/breaking-news/rss",
"https://www.dailytelegraph.com.au/newslocal/parramatta/rss",
"https://www.dailytelegraph.com.au/news/nsw/rss",
"https://www.dailytelegraph.com.au/news/national/rss",
"https://www.dailytelegraph.com.au... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import enum
set SPECIAL_KEY = b'\xe0'
set RAW_KEY_UP = b'H'
set RAW_KEY_DOWN = b'P'
set RAW_KEY_ESCAPE = b'\x1b'
set RAW_KEY_ENTER = b'\r'
class KEY extends Enum
begin
set UP = 0
set DOWN = 1
set ESCAPE = 2
set ENTER = 3
end class | # -*- coding: utf-8 -*-
import enum
SPECIAL_KEY = b'\xe0'
RAW_KEY_UP = b'H'
RAW_KEY_DOWN = b'P'
RAW_KEY_ESCAPE = b'\x1b'
RAW_KEY_ENTER = b'\r'
class KEY(enum.Enum):
UP = 0
DOWN = 1
ESCAPE = 2
ENTER = 3 | Python | zaydzuhri_stack_edu_python |
function collatz startNum
begin
set n = startNum
set collatzSeq = list
while n != 1
begin
append collatzSeq n
if n % 2 == 0
begin
set n = n / 2
end
else
begin
set n = 3 * n + 1
end
end
append collatzSeq n
comment print "Collatz Sequence = "+str(collatzSeq)
return length collatzSeq
end function
function maxColSeqLen nu... | def collatz(startNum):
n = startNum
collatzSeq = []
while(n!=1):
collatzSeq.append(n)
if (n%2 == 0 ):
n = n/2
else:
n = 3*n + 1
collatzSeq.append(n)
#print "Collatz Sequence = "+str(collatzSeq)
return len(collatzSeq)
def maxColSeqLen(num):
sta... | Python | zaydzuhri_stack_edu_python |
import random
function str_to_int g_str
begin
set g_str = split g_str string ,
set g_str = list map int g_str
set row = g_str at 0 - 1
set column = g_str at 1 - 1
return list row column
end function
function win_or_not r_list
begin
if r_list at 0 == r_list at 1 == r_list at 2 != 0
begin
if r_list at 1 == 1
begin
return... | import random
def str_to_int(g_str):
g_str = g_str.split(',')
g_str = list(map(int, g_str))
row = g_str[0] - 1
column = g_str[1] - 1
return [row, column]
def win_or_not(r_list):
if r_list[0] == r_list[1] == r_list[2] != 0:
if r_list[1] == 1:
return 1
return 2
... | Python | zaydzuhri_stack_edu_python |
function get_bundle_files bundle_uuid use_draft=none
begin
comment lint-amnesty, pylint: disable=dict-values-not-iterating
return values call get_bundle_files_dict bundle_uuid use_draft
end function | def get_bundle_files(bundle_uuid, use_draft=None):
return get_bundle_files_dict(bundle_uuid, use_draft).values() # lint-amnesty, pylint: disable=dict-values-not-iterating | Python | nomic_cornstack_python_v1 |
string PCA exercise 10/27/19.
comment : import common modules
comment the Python array package
import numpy as np
comment the Python plotting package
import matplotlib.pyplot as plt
comment Display array values to 6 digits of precision
call set_printoptions precision=4 suppress=true
comment : import numpy.linalg with a... | """ PCA exercise
10/27/19.
"""
#: import common modules
import numpy as np # the Python array package
import matplotlib.pyplot as plt # the Python plotting package
# Display array values to 6 digits of precision
np.set_printoptions(precision=4, suppress=True)
#: import numpy.linalg with a shorter name
import nu... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import random
from shape_zoo import *
import itertools
function standard_initializer n_blocks shapes sizes rot_size random_holes
begin
set block_selections = call multinomial n_blocks list 1.0 / length shapes * length shapes
set hDisp = list none * length shapes
set bPers = list none * length shapes
... | import numpy as np
import random
from shape_zoo import *
import itertools
def standard_initializer(n_blocks, shapes, sizes, rot_size, random_holes):
block_selections= np.random.multinomial(n_blocks, [1./len(shapes)]*len(shapes))
hDisp = [None]*len(shapes)
bPers = [None]*len(shapes)
hPers = [None]*len... | Python | zaydzuhri_stack_edu_python |
function print_first_and_last_sorted sentence
begin
comment 调用sort_sentence函数,进行分词排序
set words = call sort_sentence sentence
comment 打印排序后的第一个词
call print_first_word words
comment 打印排序后的最后一个词
call print_last_word words
end function | def print_first_and_last_sorted(sentence):
words = sort_sentence(sentence)#调用sort_sentence函数,进行分词排序
print_first_word(words)#打印排序后的第一个词
print_last_word(words)#打印排序后的最后一个词 | Python | nomic_cornstack_python_v1 |
import helpers
function compute_Indu_relations scene
begin
comment Takes as input a scene object from the Scene class and computes INDU relations between every pairwise object
comment within that scene. RETURNS: a dictionary of object pair as key and corresponding INDU relation in x direction
comment and y direction. C... | import helpers
def compute_Indu_relations(scene):
# Takes as input a scene object from the Scene class and computes INDU relations between every pairwise object
# within that scene. RETURNS: a dictionary of object pair as key and corresponding INDU relation in x direction
# and y direction. CURRENTLY ONLY C... | Python | zaydzuhri_stack_edu_python |
import os , bisect , codecs
import datetime
from File import File
from config import config
from WordCache import WordCacheInstance
from btree import btreeInstance , btreeReverseInstance
class FileController
begin
function __init__ self stemming=false
begin
set filesList = list
set stemming = stemming
set storekey = i... | import os, bisect, codecs
import datetime
from File import File
from config import config
from WordCache import WordCacheInstance
from btree import btreeInstance, btreeReverseInstance
class FileController:
def __init__(self, stemming=False):
self.filesList = []
self.stemming = stemming
self.storekey = 'stemmi... | Python | zaydzuhri_stack_edu_python |
comment Author : Anantharaman Chandar #
comment CWID : A20403439 #
comment Course : ITMD 513 Open Source Programming Final Project #
comment Instructor : James Papademas #
comment Description: This script gives you a best team report based on the #
comment selected formation #
comment #
comment #
comment Import Librari... | #############################################################################
# Author : Anantharaman Chandar #
# CWID : A20403439 #
# Course : ITMD 513 Open Source Programming Final Project #
# Instru... | Python | zaydzuhri_stack_edu_python |
import json
import boto3
import datetime
import sys
import os
append path string lib
import validators
set sqs = call client string sqs string us-west-2
set cloudwatch = call client string cloudwatch string us-west-2
set function_name = __name__
function handler event context
begin
string Main method for processing dat... | import json
import boto3
import datetime
import sys
import os
sys.path.append("lib")
import validators
sqs = boto3.client('sqs', "us-west-2")
cloudwatch = boto3.client("cloudwatch", "us-west-2")
function_name = __name__
def handler(event, context):
"""Main method for processing data.
Checks URL for a URL,... | Python | zaydzuhri_stack_edu_python |
comment This program is free software; you can redistribute it and/or modify
comment it under the terms of the GNU General Public License as published by
comment the Free Software Foundation; version 2 of the License.
comment This program is distributed in the hope that it will be useful,
comment but WITHOUT ANY WARRAN... | # This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied... | Python | zaydzuhri_stack_edu_python |
class Stack extends object
begin
function __init__ self
begin
set container = list
end function
function __len__ self
begin
string dunder method implementation of size()
return length container
end function
function __str__ self
begin
string Return stack as string, delimited by "-"
return join string - list comprehens... | class Stack(object):
def __init__(self):
self.container = []
def __len__(self):
"""
dunder method implementation of size()
"""
return len(self.container)
def __str__(self):
"""
Return stack as string, delimited by "-"
"""
return "-".j... | Python | zaydzuhri_stack_edu_python |
from flask import Flask
from flask import request
import requests
from influxdb import InfluxDBClient
comment Коннект к БД
comment Датчики кладут данные раз в секунду
set clientdb = call InfluxDBClient host=string pmelikov.ru port=string 46086
call switch_database string test
set app = call Flask __name__
comment Тариф... | from flask import Flask
from flask import request
import requests
from influxdb import InfluxDBClient
# Коннект к БД
# Датчики кладут данные раз в секунду
clientdb = InfluxDBClient(host='pmelikov.ru', port='46086')
clientdb.switch_database('test')
app = Flask(__name__)
# Тариф за электроэнергию (задается в приложен... | Python | zaydzuhri_stack_edu_python |
comment program to find a triple (a,b,c) such that 1<a+b+c<2 from a given array
import itertools
set a = integer input string enter size of array:-
set b = list
for i in range a
begin
set c = decimal input string elements of the array :-
try
begin
append b c
end
except any
begin
break
end
end
set d = permutations b 3
... | # program to find a triple (a,b,c) such that 1<a+b+c<2 from a given array
import itertools
a = int(input("enter size of array:-"))
b = []
for i in range(a):
c = float(input("elements of the array :-"))
try:
b.append(c)
except:
break
d = itertools.permutations(b , 3)
for j in list(d):
c =... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
class CondicionDeVenta
begin
set CONTADO = string CON
set CREDITO = string CRE
set CONDICIONES = tuple tuple CONTADO string Contado tuple CREDITO string Crédito
end class
class Iva
begin
set DIEZ = string 10
set CINCO = string 05
set EXENTA = string 00
set PORCENTAJES = tuple tuple DIEZ st... | # -*- coding: utf-8 -*-
class CondicionDeVenta:
CONTADO = 'CON'
CREDITO = 'CRE'
CONDICIONES = (
(CONTADO, 'Contado'),
(CREDITO, 'Crédito'),
)
class Iva:
DIEZ = '10'
CINCO = '05'
EXENTA = '00'
PORCENTAJES = (
(DIEZ, '10 %'),
(CINCO, '5 %'),
(EXEN... | Python | zaydzuhri_stack_edu_python |
function load_kmer_data k
begin
set hg38 = call load_kmer_file format string hg38_{}k.pkl k
set hiv1 = call load_kmer_file format string HIV-1_{}k.pkl k
return tuple hg38 hiv1
end function | def load_kmer_data(k):
hg38 = load_kmer_file("hg38_{}k.pkl".format(k))
hiv1 = load_kmer_file("HIV-1_{}k.pkl".format(k))
return (hg38, hiv1) | Python | nomic_cornstack_python_v1 |
function getFrameSize self
begin
return frame_size
end function | def getFrameSize(self):
return self.frame_size | Python | nomic_cornstack_python_v1 |
function contains L element
begin
set a = 0
set b = length L - 1
set m = a + b // 2
while a < b
begin
if L at m == element or L at a == element or L at b == element
begin
return true
end
else
if L at m > element
begin
set b = m - 1
end
else
begin
set a = m + 1
end
set m = a + b // 2
end
return false
end function | def contains(L,element):
a = 0
b = len(L)-1
m = (a+b)//2
while a < b :
if L[m] == element or L[a]==element or L[b]==element:
return True
elif L[m] > element :
b = m-1
else :
a = m+1
m = (a+b)//2
return False | Python | nomic_cornstack_python_v1 |
function flatten self
begin
return list comprehension e for es in array for e in es
end function | def flatten(self):
return [e for es in self.array for e in es] | Python | nomic_cornstack_python_v1 |
from unittest import TestCase
from hep_ipython_tools.calculation_queue import CalculationQueue , CalculationQueueItem
from hep_ipython_tools.tests.fixtures import MockQueue
class A
begin
pass
end class
class TestCalculationQueue extends TestCase
begin
function setUp self
begin
set calculation_queue = call CalculationQu... | from unittest import TestCase
from hep_ipython_tools.calculation_queue import CalculationQueue, CalculationQueueItem
from hep_ipython_tools.tests.fixtures import MockQueue
class A:
pass
class TestCalculationQueue(TestCase):
def setUp(self):
self.calculation_queue = CalculationQueue()
self.... | Python | zaydzuhri_stack_edu_python |
function get_target self
begin
return config
end function | def get_target(self):
return self.config | Python | nomic_cornstack_python_v1 |
set lista = list
append lista input string Introduce el nombre:
append lista input string Introduce la direccion:
append lista input string Introduce el telefono:
print string Los datos personales son: lista | lista = []
lista.append(input("Introduce el nombre: "))
lista.append(input("Introduce la direccion: "))
lista.append(input("Introduce el telefono: "))
print("Los datos personales son: ", lista) | Python | zaydzuhri_stack_edu_python |
comment Author: Bharath Kumar Bommana
comment Main.py is the file that has all the function calls and ensure the sequential flow of data through the system,
from XMLParser import XMLParser
from SenseCluster import SenseCluster
from ExampleGenerator import ExampleGenerator
from DefinitionGeneration import DefinitionGene... | #Author: Bharath Kumar Bommana
#Main.py is the file that has all the function calls and ensure the sequential flow of data through the system,
from XMLParser import XMLParser
from SenseCluster import SenseCluster
from ExampleGenerator import ExampleGenerator
from DefinitionGeneration import DefinitionGeneration
from t... | Python | zaydzuhri_stack_edu_python |
function is_showcase_change_download_policy self
begin
return _tag == string showcase_change_download_policy
end function | def is_showcase_change_download_policy(self):
return self._tag == 'showcase_change_download_policy' | Python | nomic_cornstack_python_v1 |
function connect self
begin
set _connection = call BlockingConnection parameters=_conn_params on_open_callback=_on_connection_open
call add_on_close_callback _on_connection_closed
end function | def connect( self ):
self._connection = pika.BlockingConnection( parameters = self._conn_params,
on_open_callback=self._on_connection_open )
self._connection.add_on_close_callback( self._on_connection_closed ) | Python | nomic_cornstack_python_v1 |
function ListDevices self
begin
string List all known devices
set devices = list
for obj in keys objects
begin
if starts with obj string /org/bluez/ and string dev_ in obj
begin
append devices call ObjectPath obj variant_level=1
end
end
return array devices variant_level=1
end function | def ListDevices(self):
'''List all known devices
'''
devices = []
for obj in mockobject.objects.keys():
if obj.startswith('/org/bluez/') and 'dev_' in obj:
devices.append(dbus.ObjectPath(obj, variant_level=1))
return dbus.Array(devices, variant_level=1) | Python | jtatman_500k |
class Solution extends object
begin
function findUnsortedSubarray self nums
begin
set newVals = sorted nums
set start = 0
set end = length nums
for tuple i val in enumerate nums
begin
if newVals at i != nums at i
begin
if start == 0
begin
set start = i + 1
end
set end = i + 1
end
end
if start == 0
begin
return 0
end
re... | class Solution(object):
def findUnsortedSubarray(self, nums):
newVals = sorted(nums)
start = 0
end = len(nums)
for (i, val) in enumerate(nums):
if (newVals[i] != nums[i]):
if (start == 0):
start = (i + 1)
end = (i + 1)
... | Python | zaydzuhri_stack_edu_python |
function set_subject self value lang=none
begin
string Set the DC Subject literal value :param value: Value of the subject node :param lang: Language in which the value is
return add metadata key=subject value=value lang=lang
end function | def set_subject(self, value: Union[Literal, Identifier, str], lang: str= None):
""" Set the DC Subject literal value
:param value: Value of the subject node
:param lang: Language in which the value is
"""
return self.metadata.add(key=DC.subject, value=value, lang=lang) | Python | jtatman_500k |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
function save self *args **kwargs
begin
save
if call requires_restart and not call isImportingData
begin
call set_setting string SERVER_RESTART_REQUIRED true none
end
end function | def save(self, *args, **kwargs):
super().save()
if self.requires_restart() and not InvenTree.ready.isImportingData():
InvenTreeSetting.set_setting('SERVER_RESTART_REQUIRED', True, None) | Python | nomic_cornstack_python_v1 |
function execute self
begin
if string tumblr.com in lower url
begin
set img_urls = call get_tumblr_imgs url
for img_url in img_urls
begin
set current = call Download title subreddit img_url
end
end
end function | def execute(self):
if 'tumblr.com' in self.candidate.url.lower():
img_urls = self.get_tumblr_imgs(self.candidate.url)
for img_url in img_urls:
self.current = Download(self.candidate.title,
self.candidate.subreddit,
... | Python | nomic_cornstack_python_v1 |
string Something in the Box? Create a function that returns True if an asterisk * is inside a box. Examples in_box([ "###", "#*#", "###" ]) ➞ True in_box([ "####", "#* #", "# #", "####" ]) ➞ True in_box([ "*####", "# #", "# #*", "####" ]) ➞ false in_box([ "#####", "# #", "# #", "# #", "#####" ]) ➞ False Notes The aster... | """
Something in the Box?
Create a function that returns True if an asterisk * is inside a box.
Examples
in_box([
"###",
"#*#",
"###"
]) ➞ True
in_box([
"####",
"#* #",
"# #",
"####"
]) ➞ True
in_box([
"*####",
"# #",
"# #*",
"####"
]) ➞ false
in_box([
"#####",
"# #",
"# #",
"# ... | Python | zaydzuhri_stack_edu_python |
function _generate_matrix self trues preds
begin
set mask = trues >= 0 ? trues < num_classes
set conf_mat = reshape call bincount num_classes * as type trues at mask int + preds at mask minlength=num_classes ^ 2 num_classes num_classes
return conf_mat
end function | def _generate_matrix(self, trues, preds):
mask = (trues >= 0) & (trues < self.num_classes)
conf_mat = np.bincount(self.num_classes * trues[mask].astype(int) + preds[mask],
minlength=self.num_classes ** 2).reshape(self.num_classes, self.num_classes)
return conf_mat | 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.