code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
for i in range N - 1
begin
set S1 = sum W at slice : i + 1 :
set S2 = sum W at slice i + 1 : :
append ans absolute S1 - S2
end
print min ans | for i in range(N-1):
S1 = sum(W[:i+1])
S2 = sum(W[i+1:])
ans.append(abs(S1-S2))
print(min(ans)) | Python | zaydzuhri_stack_edu_python |
function create_jsonable_history self
begin
string Creates a JSON-able representation of this object. Returns: A dictionary mapping key to EventTrackerDescription (which can be used to create event trackers).
return dictionary comprehension value_category_key : call get_description for tuple value_category_key tracker ... | def create_jsonable_history(self):
"""Creates a JSON-able representation of this object.
Returns:
A dictionary mapping key to EventTrackerDescription (which can be used to
create event trackers).
"""
return {value_category_key: tracker.get_description()
for (value_category_key, ... | Python | jtatman_500k |
string создайте алхимичный engine добавьте declarative base (свяжите с engine) создайте объект Session добавьте модели User и Post, объявите поля: для модели User обязательными являются name, username, email для модели Post обязательными являются user_id, title, body создайте связи relationship между моделями: User.pos... | """
создайте алхимичный engine
добавьте declarative base (свяжите с engine)
создайте объект Session
добавьте модели User и Post, объявите поля:
для модели User обязательными являются name, username, email
для модели Post обязательными являются user_id, title, body
создайте связи relationship между моделями: User.posts ... | Python | zaydzuhri_stack_edu_python |
for i in range 12
begin
set n = input
if string r in n
begin
set cnt = cnt + 1
end
end
print cnt | for i in range(12):
n = input()
if "r" in n:
cnt += 1
print(cnt) | Python | zaydzuhri_stack_edu_python |
for i in range n
begin
set tuple e l r = list comprehension integer x for x in split input
append arr e
set cnt = 0
end | for i in range(n):
e,l,r=[int(x) for x in input().split()]
arr.append(e)
cnt = 0 | Python | zaydzuhri_stack_edu_python |
function sleep_until self time
begin
raise call NotImplementedError
end function | def sleep_until(self, time):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function type self
begin
comment type: ignore
return config at CONF_TYPE
end function | def type(self) -> str:
return self.config[CONF_TYPE] # type: ignore | Python | nomic_cornstack_python_v1 |
function solar_declination J
begin
return 0.409 * sin 2 * pi / 365.0 * J - 1.39
end function | def solar_declination(J):
return 0.409*sin(((2*pi)/365.0)*J - 1.39) | Python | nomic_cornstack_python_v1 |
function test_if_generator self
begin
assert true is instance call pierwsze_iterator 20 list
end function | def test_if_generator(self):
self.assertTrue(isinstance(pierwsze_iterator(20), list)) | Python | nomic_cornstack_python_v1 |
set list = list 10 20 30 40 50
comment reversing the list
reverse list
comment printing the reversed list
print string The reversed list is : + string list | list = [10, 20, 30, 40, 50]
# reversing the list
list.reverse()
# printing the reversed list
print ("The reversed list is : " + str(list))
| Python | flytech_python_25k |
function eval_input input_pairs value_from
begin
comment Match any of the following patterns: self.path, inputs.foo, or "foo"
comment in an expression of the form $(A + B) in the valueFrom field
set expr_pattern = string \$\((self\.path|inputs\.\w+|".+") \+ (self\.path|inputs\.\w+|".+")\)
set match = call fullmatch exp... | def eval_input(input_pairs, value_from):
# Match any of the following patterns: self.path, inputs.foo, or "foo"
# in an expression of the form $(A + B) in the valueFrom field
expr_pattern = r'\$\((self\.path|inputs\.\w+|".+") \+ (self\.path|inputs\.\w+|".+")\)'
match = re.fullmatch(expr_pattern, value_f... | Python | nomic_cornstack_python_v1 |
function ReadUntilClose self
begin
while true
begin
set tuple cmd data = call ReadUntil b'CLSE' b'WRTE'
if cmd == b'CLSE'
begin
call _Send b'CLSE' arg0=local_id arg1=remote_id
break
end
if cmd != b'WRTE'
begin
if cmd == b'FAIL'
begin
raise call AdbCommandFailureException string Command failed. data
end
raise call Inval... | def ReadUntilClose(self):
while True:
cmd, data = self.ReadUntil(b'CLSE', b'WRTE')
if cmd == b'CLSE':
self._Send(b'CLSE', arg0=self.local_id, arg1=self.remote_id)
break
if cmd != b'WRTE':
if cmd == b'FAIL':
... | Python | nomic_cornstack_python_v1 |
comment For timestamp
import datetime
import requests
comment Calculating the hash
comment in order to add digital
comment fingerprints to the blocks
import hashlib
comment To store data
comment in our blockchain
import json
comment Flask is for creating the web
comment app and jsonify is for
comment displaying the blo... | # For timestamp
import datetime
import requests
# Calculating the hash
# in order to add digital
# fingerprints to the blocks
import hashlib
# To store data
# in our blockchain
import json
# Flask is for creating the web
# app and jsonify is for
# displaying the blockchain
from flask import Flask, js... | Python | zaydzuhri_stack_edu_python |
function cache_parameters module cache_gradients=false
begin
set param_cache = ordered dictionary
set grad_cache = ordered dictionary
for tuple name param in named parameters module
begin
set param_cache at name = clone detach param
if cache_gradients and grad is not none
begin
set grad_cache at name = clone detach gra... | def cache_parameters(module: nn.Module, cache_gradients=False):
param_cache = OrderedDict()
grad_cache = OrderedDict()
for name, param in module.named_parameters():
param_cache[name] = param.detach().clone()
if cache_gradients and param.grad is not None:
grad_cache[name] = param... | Python | nomic_cornstack_python_v1 |
function create_superuser self username email password
begin
set user = call create_user username=username email=call normalize_email email password=password
set is_admin = true
save using=_db
return user
end function | def create_superuser(self, username, email, password):
user = self.create_user(
username=username,
email=self.normalize_email(email),
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user | Python | nomic_cornstack_python_v1 |
function plot_ccd_individual ccd_data plot_origin=true mask=none extract_array_from_mask=false zoom_around_mask=false positions=none should_plot_image=false should_plot_noise_map=false should_plot_psf=false should_plot_signal_to_noise_map=false should_plot_absolute_signal_to_noise_map=false should_plot_potential_chi_sq... | def plot_ccd_individual(
ccd_data, plot_origin=True, mask=None, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
should_plot_image=False,
should_plot_noise_map=False,
should_plot_psf=False,
should_plot_signal_to_noise_map=False,
should_plot_absolute_... | Python | jtatman_500k |
function encipher self string keep_punct=false
begin
if not keep_punct
begin
set string = call remove_punctuation string
end
return join string call buildfence string key
end function | def encipher(self,string,keep_punct=False):
if not keep_punct: string = self.remove_punctuation(string)
return ''.join(self.buildfence(string, self.key)) | Python | nomic_cornstack_python_v1 |
class Stack
begin
function __init__ self
begin
set items = list
end function
function push self item
begin
append items item
end function
function getSize self
begin
return length items
end function
function multiPop self times=1
begin
set i = min times get size self
while times != 0
begin
return pop items
set times =... | class Stack :
def __init__(self):
self.items = []
def push(self,item):
self.items.append(item)
def getSize(self):
return len(self.items)
def multiPop(self , times=1):
i = min(times,self.getSize())
while (times != 0):
return self.items.pop()
... | Python | zaydzuhri_stack_edu_python |
if number % 10 == 0
begin
print string { number } is divisible by 10
end
else
begin
print string your number sucks
end | if number % 10 == 0:
print(f"{number} is divisible by 10")
else:
print(f"your number sucks") | Python | zaydzuhri_stack_edu_python |
function update_default_values self **updates
begin
string Replace the default values of specified fields. Parameters ---------- Parameters are taken as keyword-arguments of `field=new_value`. Raises ------ KeyError If a field doesn't exist in the struct.
for tuple field value in call iteritems updates
begin
set fname ... | def update_default_values(self, **updates):
"""Replace the default values of specified fields.
Parameters
----------
Parameters are taken as keyword-arguments of `field=new_value`.
Raises
------
KeyError
If a field doesn't exist in the struct.
... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
comment @Author: AlvinPy
comment @github: https://github.com/AlvinPy/PythonTutorials.git
comment @码云:https://gitee.com/alvinfeng/PythonTutorials.git
comment 导入需要使用的模块,pprint模块是为了格式化打印-
comment 结果,一般情况下可不用
import csv
comment 创建一个列表保存列名
set title = list string input string output
comment 创建一... | # -*- coding: utf-8 -*-
# @Author: AlvinPy
# @github: https://github.com/AlvinPy/PythonTutorials.git
# @码云:https://gitee.com/alvinfeng/PythonTutorials.git
# 导入需要使用的模块,pprint模块是为了格式化打印-
# 结果,一般情况下可不用
import csv
# 创建一个列表保存列名
title = ['input', 'output']
dataList = [] # 创建一个列表保存数据
# 读取所有文件
for i in range(5... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
import os
function check_dir dir_name
begin
set is_exist = false
set self_cwd = get current directory
comment print os.listdir(self_cwd)
for line in list directory self_cwd
begin
set file_path = join path self_cwd line
if is directory path file_path
begin
if line == dir_name
begin
set is_exist = t... | # coding: utf-8
import os
def check_dir(dir_name):
is_exist = False
self_cwd = os.getcwd()
# print os.listdir(self_cwd)
for line in os.listdir(self_cwd):
file_path = os.path.join(self_cwd, line)
if os.path.isdir(file_path):
if line == dir_name:
is_exist = Tr... | Python | zaydzuhri_stack_edu_python |
function setNodeCount self numNodes preemptable=false force=false
begin
for attempt in call retry predicate=retryPredicate
begin
with attempt
begin
set workerInstances = call getNodes preemptable=preemptable
set numCurrentNodes = length workerInstances
set delta = numNodes - numCurrentNodes
if delta > 0
begin
info stri... | def setNodeCount(self, numNodes, preemptable=False, force=False):
for attempt in retry(predicate=self.scaler.provisioner.retryPredicate):
with attempt:
workerInstances = self.getNodes(preemptable=preemptable)
numCurrentNodes = len(workerInstances)
delt... | Python | nomic_cornstack_python_v1 |
import numpy as np
from vispy.util import transforms as tr
from mesh import Mesh
from vispy import app , gloo
call set_printoptions suppress=true precision=2
comment all of this is only to define gl_Position
set VERT_SHADER = string attribute vec3 vertex; uniform mat4 model_matrix; uniform mat4 projection_matrix; void ... | import numpy as np
from vispy.util import transforms as tr
from mesh import Mesh
from vispy import app, gloo
np.set_printoptions(suppress=True, precision=2)
#all of this is only to define gl_Position
VERT_SHADER = """
attribute vec3 vertex;
uniform mat4 model_matrix;
uniform mat4 projection_matrix;
void main(){
gl_P... | Python | zaydzuhri_stack_edu_python |
comment 99 Bottles of Beer on the Wall
comment bottles = 100
comment while bottles >= 3:
comment bottles = bottles - 1
comment print(str(bottles) + " bottles of beer on the wall, " + str(bottles) + " bottles of beer, we take one down, pass it around, " + str(bottles - 1) + " bottles of beer on the wall!")
comment conti... | #99 Bottles of Beer on the Wall
# bottles = 100
# while bottles >= 3:
# bottles = bottles - 1
# print(str(bottles) + " bottles of beer on the wall, " + str(bottles) + " bottles of beer, we take one down, pass it around, " + str(bottles - 1) + " bottles of beer on the wall!")
# continue
# break
# bottles = 1
... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function minNumberOfFrogs self croakOfFrogs
begin
set cnt = list 0 * 5
set res = 0
set frogs = 0
for c in croakOfFrogs
begin
set i = find string croak c
set cnt at i = cnt at i + 1
if i == 0
begin
set frogs = frogs + 1
set res = max res frogs
end
else
if i == 4
begin
set frogs = frogs - 1
end
else
... | class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
cnt = [0] * 5
res = frogs = 0
for c in croakOfFrogs:
i = "croak".find(c)
cnt[i] += 1
if i == 0:
frogs += 1
res = max(res, frogs)
elif i == 4:
... | Python | zaydzuhri_stack_edu_python |
comment is unique
comment tests to show that a string only contains uniqe data structors
comment frist crack at it
function unique1 testString
begin
set dic = dict
for letter in testString
begin
if letter in dic
begin
return false
end
else
begin
set dic at letter = letter
end
end
return true
end function
comment secou... | ##is unique
## tests to show that a string only contains uniqe data structors
##frist crack at it
def unique1(testString):
dic = {}
for letter in testString:
if letter in dic:
return False
else:
dic[letter] = letter
return True
##secound crack at it
def unique2(test... | Python | zaydzuhri_stack_edu_python |
function writeOrganismTaxonomies self
begin
info string writeOrganismTaxonomies: START
set organisms = call getAllOrganisms
set taxonomies = dict
info string writeOrganismTaxonomies: insert file will be organismTaxonomiesInsert.psql
set taxonomyFile = call openInsertFile string organismTaxonomiesInsert.psql
for tuple ... | def writeOrganismTaxonomies( self ):
self.logger.info( 'writeOrganismTaxonomies: START' )
organisms = self.reader.getAllOrganisms()
taxonomies = {}
self.logger.info( 'writeOrganismTaxonomies: insert file will be organismTaxonomiesInsert.psql' )
taxonomyFile = self.openInser... | Python | nomic_cornstack_python_v1 |
function _parse_args self args
begin
set parser = call OptionParserExtended option_class=SosOption
set parser = call OptionParserExtended option_class=SosOption
call add_option string -l string --list-plugins action=string store_true dest=string list_plugins default=false help=string list plugins and available plugin o... | def _parse_args(self, args):
self.parser = parser = OptionParserExtended(option_class=SosOption)
parser.add_option("-l", "--list-plugins", action="store_true",
dest="list_plugins", default=False,
help="list plugins and available plugin opti... | Python | nomic_cornstack_python_v1 |
function usage_similarity resource_list_one resource_list_two
begin
comment Convert list of tuples to set of tuples
set resource_set_one = set
set resource_set_two = set
for resource in resource_list_one
begin
add resource_set_one tuple resource at 0 resource at 1
end
for resource in resource_list_two
begin
add resourc... | def usage_similarity(resource_list_one, resource_list_two):
# Convert list of tuples to set of tuples
resource_set_one = set()
resource_set_two = set()
for resource in resource_list_one:
resource_set_one.add((resource[0], resource[1]))
for resource in resource_list_two:
resource_set_... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function minRemoveToMakeValid self s
begin
string :type s: str :rtype: str
set stk = list
set remove = set
set res = string
for tuple i ch in enumerate s
begin
if ch not in string ()
begin
continue
end
if ch == string (
begin
append stk i
end
else
if not stk
begin
add remove i
end
... | class Solution(object):
def minRemoveToMakeValid(self, s):
"""
:type s: str
:rtype: str
"""
stk = []
remove = set()
res = ""
for i, ch in enumerate(s):
if ch not in "()":
continue
if ch == '(':
st... | Python | zaydzuhri_stack_edu_python |
function __init__ self databaseFile
begin
set databaseFile = databaseFile
set expectingDataBlock = none
try
begin
set loop = call get_running_loop
set timeout_handle = call call_later TIMEOUT _timeout
end
except RuntimeError
begin
print __name__ string is being instantiated without a running event loop
end
end function | def __init__(self, databaseFile):
self.databaseFile = databaseFile
self.expectingDataBlock = None
try:
loop = asyncio.get_running_loop()
self.timeout_handle = loop.call_later(self.TIMEOUT, self._timeout)
except RuntimeError:
print(self.__class__.__name... | Python | nomic_cornstack_python_v1 |
function display cls agent agent_surface sim_surface=none
begin
if is instance agent AbstractDQNAgent
begin
call display agent agent_surface sim_surface
end
end function | def display(cls, agent, agent_surface, sim_surface=None):
if isinstance(agent, AbstractDQNAgent):
DQNGraphics.display(agent, agent_surface, sim_surface) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Wed Dec 11 14:52:45 2019 @author: soldierside
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sn
import math
call runfile string /Users/soldierside/Documents/Bootcamp/Projec... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 11 14:52:45 2019
@author: soldierside
"""
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sn
import math
runfile('/Users/soldierside/Documents/Bootcamp/Projecte final/nyc-taxi-... | Python | zaydzuhri_stack_edu_python |
function report_accurarcy model svc loader device=device string cpu
begin
set tuple embeddings labels = call get_embeddings model dataset device
set predictions = list comprehension predict svc e for e in embeddings
set ground_truths = list comprehension argument maximum l axis=- 1 for l in labels
set cm = call confusi... | def report_accurarcy(model, svc, loader, device=torch.device('cpu')):
embeddings, labels = get_embeddings(model, loader.dataset, device)
predictions = [svc.predict(e) for e in embeddings]
ground_truths = [np.argmax(l, axis=-1) for l in labels]
cm = confusion_matrix(ground_truths, predictions)
acc ... | Python | nomic_cornstack_python_v1 |
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
function test_delete_test_product driver
begin
call click
set old_products = list
set new_products = list
set i = 0
while i < length call find_elements_by_xpath string //tr[@class]/td[3]/a
begin
... | from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def test_delete_test_product(driver):
driver.find_element_by_xpath("//li[2]/a").click()
old_products = []
new_products = []
i = 0
while i < len(driver.find_elements_by_xpath("/... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment encoding=UTF-8
import select
import socket
import errno
import collections
from ioloop import IOLoop
class EchoStream extends object
begin
function __init__ self socket *args **kwargs
begin
set io_loop = call instance
set socket = socket
call setblocking 0
set _read_callback = none
... | #!/usr/bin/env python
# encoding=UTF-8
import select
import socket
import errno
import collections
from ioloop import IOLoop
class EchoStream(object):
def __init__(self, socket, *args, **kwargs):
self.io_loop = IOLoop.instance()
self.socket = socket
self.socket.setblocking(0)
se... | Python | zaydzuhri_stack_edu_python |
comment the printout becomes more informative#
print areas
comment exercise 3#
comment we can put lists within lists-#
set house = list list string hallway hall list string kitchen kitchen list string living_room living_room list string bedroom bedroom list string bathroom bathroom
print house
comment this prints out t... | #the printout becomes more informative#
print(areas)
#exercise 3#
#we can put lists within lists-#
house=[['hallway',hall],['kitchen',kitchen],['living_room',living_room],['bedroom',bedroom],['bathroom',bathroom]]
print(house)
print(type(house))#this prints out the type of the list
#exercise 4
print(are... | Python | zaydzuhri_stack_edu_python |
function _find_time_command line
begin
set match = match line
if match
begin
return call group 0
end
else
begin
return none
end
end function | def _find_time_command(line):
match = TIME_COMMAND_RE.match(line)
if match:
return match.group(0)
else:
return None | Python | nomic_cornstack_python_v1 |
set bin_str = binary num
set rev_bin_str = string 0b + bin_str at slice : 1 : - 1
set rev_num = integer rev_bin_str 2
print format string The binary reversed version of {} is {} num rev_num | bin_str = bin(num)
rev_bin_str = '0b' + bin_str[:1:-1]
rev_num = int(rev_bin_str,2)
print("The binary reversed version of {} is {}".format(num, rev_num))
| Python | flytech_python_25k |
function _tempfile content=none
begin
set tf = named temporary file delete=false
if content is not none
begin
write tf encode string content string ascii
end
close tf
return name
end function | def _tempfile(content=None):
tf = tempfile.NamedTemporaryFile(delete=False)
if content is not None:
tf.write(str(content).encode('ascii'))
tf.close()
return tf.name | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
print string *****Option*****
set x_data = list 1 2 3
set y_data = list 1 2 3
set W = call Variable 5.0
set hypothesis = x_data * W
comment 직접 계산한 함수
set gradient = call reduce_mean W * x_data - y_data * x_data * 2
set cost = call reduce_mean call square hypothesis - y_data
comment 러닝레이트를 더 줄였음
... | import tensorflow as tf
print("\n*****Option*****\n")
x_data = [1,2,3]
y_data = [1,2,3]
W = tf.Variable(5.0)
hypothesis = x_data * W
gradient = tf.reduce_mean((W * x_data - y_data) * x_data) * 2#직접 계산한 함수
cost = tf.reduce_mean(tf.square(hypothesis - y_data))
optimizer = tf.train.GradientDescentOptimizer(learning_r... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
set M = dict string A set literal string B string D ; string B set literal string A string F string G string H ; string C set literal string E string F ; string D set literal string A string E ; string E set literal string C string D string F string H ; string F se... | #!/usr/bin/python
# -*- coding: utf-8 -*-
M={"A":{"B","D"},"B":{"A","F","G","H"},"C":{"E","F"},"D":{"A","E"},
"E":{"C","D","F","H"},"F":{"B","C","E","H"},"G":{"B","H"},"H":{"B","E","F","G"}}
afaire={"G"}
fait=set()
while afaire:
temp=set()
for s in afaire:
temp|=M[s]
temp-=fait
temp-=afaire... | Python | zaydzuhri_stack_edu_python |
import collections
import math
set prefix = string
set suffix = string
function processPrefix s
begin
global prefix
if length s > 0
begin
if s not in prefix
begin
if prefix in s
begin
set prefix = s
return 0
end
else
begin
return - 1
end
end
else
if prefix at slice : length s : != s
begin
return - 1
end
end
return ... | import collections
import math
prefix = ""
suffix = ""
def processPrefix(s):
global prefix
if len(s) > 0:
if s not in prefix:
if prefix in s:
prefix = s
return 0
else:
return -1
else:
if prefix[:len(s)] != s:
return -1
return 0
def processSuffix(s):
global suffix
if len(s) > 0:
if... | Python | zaydzuhri_stack_edu_python |
function zpi_service_discovery_test zpi device_list
begin
comment request Simple Descriptor for each active endpoint on specified device
comment save the result as following format:
comment device_list[] -> device#n['endpoints'] ->endpoint#m->'simple_desc':
comment global device_list
info string Service discovery...
fo... | def zpi_service_discovery_test(zpi, device_list):
#request Simple Descriptor for each active endpoint on specified device
#save the result as following format:
#device_list[] -> device#n['endpoints'] ->endpoint#m->'simple_desc':
#global device_list
log.info('Service discovery...')
for devi... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn , optim
from torch.autograd import Variable
import torch.nn.functional as F
import torchvision
from torchvision import datasets , transforms , models
from PIL import Image
comment Tells the machine what folder contains the image data.
... | import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn, optim
from torch.autograd import Variable
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms, models
from PIL import Image
# Tells the machine what folder contains the im... | Python | zaydzuhri_stack_edu_python |
import math
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
comment adding some comments for new commit
function calc x
begin
return string log absolute 12 * sin integer x
end function
try
begin
set link = string http://suninjuly.github.io/get_attribute.html
set browser = call Chr... | import math
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
#adding some comments for new commit
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
try:
link = "http://suninjuly.github.io/get_attribute.html"
browser = webdriver.Chrome()
browser.get(lin... | Python | zaydzuhri_stack_edu_python |
from math import exp
function f x
begin
return x - 12 * exp x / 2 - 8 * x - 2 ^ 2
end function
function g x
begin
return - x - 2 * x ^ 2 - 5 * x ^ 3 + 6 * x ^ 4
end function
print f dist 0
print call g 1 | from math import exp
def f(x):
return (x-12)*exp(x/2)-8*(x-2)**2
def g(x):
return -x-2*x**2-5*x**3+6*x**4
print(f(0))
print(g(1)) | Python | zaydzuhri_stack_edu_python |
set x = string string Read
set y = string 5
set r = string string 3
print x + string + y + string + r | x = str("Read")
y = str(5)
r = str("3")
print(x + " " + y + " "+ r ) | Python | zaydzuhri_stack_edu_python |
comment data in string format and you have to parse into dictionary
set data = data
set dataDict = loads data | # data in string format and you have to parse into dictionary
data = request.data
dataDict = json.loads(data)
| Python | jtatman_500k |
function while_demo
begin
set i = 1
while i <= 10
begin
print i end=string
set i = i + 1
end
print string While Loop Completed
end function
function for_demo
begin
for letter in string Kumar
begin
print letter end=string
end
print string
for num in range 10
begin
print num end=string
end
print string
end function | def while_demo():
i = 1
while i <= 10:
print(i, end="\t")
i += 1
print("\nWhile Loop Completed")
def for_demo():
for letter in "Kumar":
print(letter, end="\t")
print("\n")
for num in range(10):
print(num, end="\t")
print("\n")
| Python | zaydzuhri_stack_edu_python |
import boto3
import time
import json
with open string config.json as s
begin
set settings = load json s
end
set kinesis = call client string kinesis aws_access_key_id=settings at string aws_access_key_id aws_secret_access_key=settings at string aws_secret_access_key region_name=settings at string region_name
function l... | import boto3
import time
import json
with open('config.json') as s:
settings = json.load(s)
kinesis = boto3.client('kinesis', aws_access_key_id = settings["aws_access_key_id"], aws_secret_access_key = settings["aws_secret_access_key"] , region_name = settings["region_name"])
def list_streams():
print("\n> Cu... | Python | zaydzuhri_stack_edu_python |
function batch_size self
begin
raise call NotImplementedError string batch_size has not been implemented
end function | def batch_size(self):
raise NotImplementedError("batch_size has not been implemented") | Python | nomic_cornstack_python_v1 |
function iter_page_links self
begin
set r = get requests starting_url
set soup = call BeautifulSoup content features=string html.parser
comment get target column of list items
set resources = find find all soup string ul attrs=dict string class string dropdown-menu at 3 string ul
for resource in find all resources stri... | def iter_page_links(self) -> Iterable[str]:
r = requests.get(self.starting_url)
soup = bs4.BeautifulSoup(r.content, features="html.parser")
# get target column of list items
resources = soup.find_all("ul", attrs={'class': 'dropdown-menu'})[3].find('ul')
for resource in resourc... | Python | nomic_cornstack_python_v1 |
from os import listdir
from os.path import isfile , join
import json
import os
comment returns each topic from the given syllabus path
function parse_syllabus self path
begin
set files = list comprehension f for f in list directory path if is file join path f
for file in files
begin
set tuple filename file_extension = ... | from os import listdir
from os.path import isfile, join
import json
import os
#returns each topic from the given syllabus path
def parse_syllabus(self, path):
files = [f for f in listdir(path) if isfile(join(path, f))]
for file in files:
filename, file_extension = os.path.splitext(file)
... | Python | zaydzuhri_stack_edu_python |
function recipe_batches recipe ingredients
begin
comment recipe is what is need
comment ingredients is what we have
set total_batches = list
comment could have used len() instead. Wasn't aware that would work on dictionaries
if set ingredients >= set recipe
begin
for x in recipe
begin
comment if we don't have enough o... | def recipe_batches(recipe, ingredients):
# recipe is what is need
# ingredients is what we have
total_batches = []
if set(ingredients) >= set(recipe): # could have used len() instead. Wasn't aware that would work on dictionaries
for x in recipe:
# if we don't have enough of an ingredient, add 0 to l... | Python | zaydzuhri_stack_edu_python |
string Test garageband files against chater 4 rubric
import sys
append path string ../api
append path string ../appleloops
import bandFile
import appleLoops
from errors import TestError , TestCode
from utilities import grab_section , are_equal
import pprint
set TICKS_PER_MEASURE = 4 * 960
function hasCorrectInstruments... | """
Test garageband files against chater 4 rubric
"""
import sys
sys.path.append("../api")
sys.path.append("../appleloops")
import bandFile
import appleLoops
from errors import TestError, TestCode
from utilities import grab_section, are_equal
import pprint
TICKS_PER_MEASURE = 4 * 960
def hasCorrectInstruments(bf):... | Python | zaydzuhri_stack_edu_python |
comment Write a function that accepts two numbers as arguments and return the remainder
function name_dob name dob
begin
print string { name } was born on { dob }
end function
call name_dob string Gurkirpal string Jan 1, 1990 | # Write a function that accepts two numbers as arguments and return the remainder
def name_dob(name, dob):
print(f'{name} was born on {dob}')
name_dob('Gurkirpal', 'Jan 1, 1990')
| Python | zaydzuhri_stack_edu_python |
function segment self img
begin
if is instance img list
begin
pass
end
else
begin
set return_one = true
set img = list img
end
set mrcnn_mask = call _get_mrcnn_mask img
set segs = list
for tuple mask image in zip mrcnn_mask img
begin
set processed_image = call _apply_soft_mask image mask
append segs call sobel_watersh... | def segment(self, img):
if isinstance(img, list):
pass
else:
return_one = True
img = [img]
mrcnn_mask = self._get_mrcnn_mask(img)
segs = []
for mask, image in zip(mrcnn_mask, img):
processed_image = self._apply_soft_mask(image, mas... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sat Sep 26 09:47:10 2020 @author: diluisi
import os
import urllib
comment import pandas as pd
comment gerador de datas
comment x = pd.date_range("01-01-2017","31-12-2017")
comment with open('dates.txt', 'w') as f:
comment for item in x:
comme... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 26 09:47:10 2020
@author: diluisi
"""
import os
import urllib
#import pandas as pd
#gerador de datas
#x = pd.date_range("01-01-2017","31-12-2017")
#with open('dates.txt', 'w') as f:
# for item in x:
# f.write("%s\n" % item)
csvfile = '... | Python | zaydzuhri_stack_edu_python |
from base_page import BasePage
from locators import ProductPageLocators
class ProductPage extends BasePage
begin
set product_name = none
set product_price = none
function should_be_product_page self
begin
call should_be_product_card
call should_be_add_to_basket_form
call get_product_info
end function
function should_be... | from .base_page import BasePage
from .locators import ProductPageLocators
class ProductPage(BasePage):
product_name = None
product_price = None
def should_be_product_page(self):
self.should_be_product_card()
self.should_be_add_to_basket_form()
self.get_product_info()
def shou... | Python | zaydzuhri_stack_edu_python |
function wrap_functions cls
begin
function create_function function
begin
function wrap_function self *args **kwargs
begin
string Call the function on the wrapped variable.
return call get attribute wrapped function *args keyword kwargs
end function
return wrap_function
end function
for function in functions
begin
set ... | def wrap_functions(cls):
def create_function(function: str):
def wrap_function(self, *args, **kwargs):
"""Call the function on the wrapped variable."""
return getattr(self.wrapped, function)(*args, **kwargs)
return wrap_function
for function in functions:
setat... | Python | nomic_cornstack_python_v1 |
function sndData self dat
begin
comment comando da inviare
set strCmd = string
for byt in dat
begin
set strCmd = strCmd + string %c % byt
end
comment Non uso sndByte per evitare il ritardo self.dlTx
write ser strCmd
end function | def sndData(self, dat):
# comando da inviare
strCmd=""
for byt in dat:
strCmd+=("%c" %byt)
# Non uso sndByte per evitare il ritardo self.dlTx
self.ser.write(strCmd) | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
set data = call PositionalList
end function | def __init__(self):
self.data = PositionalList() | Python | nomic_cornstack_python_v1 |
class AdjacencyList
begin
decorator staticmethod
function getOriList
begin
set adjacencyList = dict string SEO list ; string NY list string SEO ; string TKY list string BER string NY ; string LDN list string SEO ; string BER list string LDN
return adjacencyList
end function
function __init__ self
begin
set adjacencyLi... | class AdjacencyList:
@staticmethod
def getOriList():
adjacencyList = {
'SEO': [],
'NY': ['SEO'],
'TKY': ['BER', 'NY'],
'LDN': ['SEO'],
'BER': ['LDN'],
}
return adjacencyList
def __init__(self):
self... | Python | zaydzuhri_stack_edu_python |
function _retrieve_value variable data=none
begin
if is instance variable tuple Series DataFrame
begin
return variable
end
if is instance variable str or is instance variable Iterable and all generator expression is instance i str for i in variable
begin
assert data is not none msg string `data` must be provided
return... | def _retrieve_value(variable, data=None):
if isinstance(variable, (pd.Series, pd.DataFrame)):
return variable
if isinstance(variable, str) or (
isinstance(variable, Iterable) and all(isinstance(i, str) for i in variable)
):
assert data is not None, "`data` must be provided"
... | Python | nomic_cornstack_python_v1 |
comment Take any list data type with numbers. Print Sum of all the numbers in the list.
set t = 0
set list = list 11 5 17 18 23
for i in range 0 length list
begin
set t = t + list at i
end
print string Sum of all elements in given list: t | #Take any list data type with numbers. Print Sum of all the numbers in the list.
t = 0
list = [11, 5, 17, 18, 23]
for i in range(0, len(list)):
t = t + list[i]
print("Sum of all elements in given list: ", t) | Python | zaydzuhri_stack_edu_python |
function extract path
begin
comment --------------------------------------------------------------------
set body = list
set func = string
set brief = string
set seenfunction = false
set seenpercent = false
for l in open path
begin
set line = left strip strip l
if starts with line string %
begin
set seenpercent = tr... | def extract(path):
# --------------------------------------------------------------------
body = []
func = ""
brief = ""
seenfunction = False
seenpercent = False
for l in open(path):
line = l.strip().lstrip()
if line.startswith('%'): seenpercent = True
... | Python | nomic_cornstack_python_v1 |
function article id
begin
set all_articles = call get_articles id
print all_articles
set source = id
set search_article = get args string article_query
if search_article
begin
return call redirect call url_for string search article_name=search_article
end
else
begin
return call render_template string articles.html arti... | def article(id):
all_articles = get_articles(id)
print(all_articles)
source = id
search_article = request.args.get('article_query')
if search_article:
return redirect(url_for('search', article_name = search_article))
else:
return render_template('articles.html', articles = all_ar... | Python | nomic_cornstack_python_v1 |
import binascii
import mnemonic
import base58
set ashex = lambda b -> decode call hexlify seed string ascii
set ENGLISH = set list comprehension strip w for w in read lines open string wordlist.txt
set recovery = input string Enter the first 23 words of your recovery phrase:
set words = list comprehension strip w for w... | import binascii
import mnemonic
import base58
ashex = lambda b: binascii.hexlify(seed).decode('ascii')
ENGLISH = set([w.strip() for w in open("wordlist.txt").readlines()])
recovery = input("Enter the first 23 words of your recovery phrase:\n")
words = [w.strip() for w in recovery.split(" ")]
if len(words) != 23:
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import torch
function pad_list l max_len pad_value=none
begin
set l = l + list pad_value * max_len - length l
return l
end function
class Vocabulary extends object
begin
function __init__ self start_word=none end_word=none unknown_word=none pad_word=none
begin
call __init__
set _word_to_index = dict ... | import numpy as np
import torch
def pad_list(l, max_len, pad_value=None):
l += [pad_value] * (max_len - len(l))
return l
class Vocabulary(object):
def __init__(self, start_word=None, end_word=None, unknown_word=None, pad_word=None) -> None:
super().__init__()
self._word_to_index = {}
... | Python | zaydzuhri_stack_edu_python |
comment Example Text Editor
comment Ryan Paul (SegPhault) - 07/12/2009
import gtk , webkit
class Editor extends Window
begin
function __init__ self note catalogue=none
begin
set catalogue = catalogue
set note = note
call __init__ self
call set_title call get_title
call resize 500 500
set editor = call WebView
call set_... | #
# Example Text Editor
# Ryan Paul (SegPhault) - 07/12/2009
#
import gtk, webkit
class Editor(gtk.Window):
def __init__(self, note, catalogue=None):
self.catalogue = catalogue
self.note = note
gtk.Window.__init__(self)
self.set_title(note.get_title())
self.resize(500, 500)
self.editor = w... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame
from sklearn.model_selection import train_test_split
import keras
from keras.models import Sequential
from keras.layers import Dense , Dropout
from keras import backend as K
set points = 3000
set points_test = 100
seed 0
comment triangle 1:... | import matplotlib.pyplot as plt
import numpy as np
from pandas import DataFrame
from sklearn.model_selection import train_test_split
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras import backend as K
points = 3000
points_test = 100
np.random.seed(0)
# triangle 1: ... | Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
comment class TreeNode:
comment def __init__(self, val=0, left=None, right=None):
comment self.val = val
comment self.left = left
comment self.right = right
class Solution
begin
function deleteNode self root key
begin
string my own solution. iterative solution. 两种方法 时间复杂度:\mat... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
""" my own solution. iterative solution.... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
import math
import cv2.aruco as aruco
import serial
import csv
comment CROPPING THE IMAGE TO GET RID OF THE EYANTRA LOGO.
set cap = call VideoCapture 1
set fps = get cap CAP_PROP_FPS
set 3 640
set 4 480
set tuple ret img = read cap
set img_gray = call cvtColor img COLOR_BGR2GRAY
set edges ... | import cv2
import numpy as np
import math
import cv2.aruco as aruco
import serial
import csv
#CROPPING THE IMAGE TO GET RID OF THE EYANTRA LOGO.
cap = cv2.VideoCapture(1)
fps = cap.get(cv2.CAP_PROP_FPS)
cap.set(3, 640)
cap.set(4, 480)
ret, img = cap.read()
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY... | Python | zaydzuhri_stack_edu_python |
import sys
set N = integer read line stdin
set dp = list comprehension list 0 0 0 for _ in range 1001
for n in range 1 N + 1
begin
set dp at n = list map int split read line stdin
set dp at n at 0 = min dp at n - 1 at 1 dp at n - 1 at 2 + dp at n at 0
set dp at n at 1 = min dp at n - 1 at 0 dp at n - 1 at 2 + dp at n a... | import sys
N = int(sys.stdin.readline())
dp = [[0, 0, 0] for _ in range(1001)]
for n in range(1, N+1):
dp[n] = list(map(int, sys.stdin.readline().split()))
dp[n][0] = min(dp[n-1][1], dp[n-1][2]) + dp[n][0]
dp[n][1] = min(dp[n - 1][0], dp[n - 1][2]) + dp[n][1]
dp[n][2] = min(dp[n - 1][0], dp[n - 1][1])... | Python | zaydzuhri_stack_edu_python |
function get_metrics G
begin
set res = dictionary
set nnodes = call number_of_nodes
set res at string average out-degree = sum list comprehension x at 1 for x in call out_degree / decimal nnodes
set res at string assortativity coefficient = call degree_pearson_correlation_coefficient G
set res at string reciprocity = c... | def get_metrics(G):
res = dict()
nnodes = G.number_of_nodes()
res['average out-degree'] = sum([x[1] for x in G.out_degree()])/float(nnodes)
res['assortativity coefficient'] = nx.algorithms.degree_pearson_correlation_coefficient(G)
res['reciprocity'] = nx.algorithms.reciprocity(G)
# all_pairs_... | Python | nomic_cornstack_python_v1 |
import itertools
function compute_unfairness lst
begin
set output = 0
for index in range length lst
begin
for index2 in range index + 1 length lst
begin
set output = output + absolute lst at index - lst at index2
end
end
return output
end function
function output input_list
begin
set LU = 0
set a = input_list at slice ... | import itertools
def compute_unfairness(lst):
output = 0
for index in range(len(lst)):
for index2 in range(index+1,len(lst)):
output += abs(lst[index]-lst[index2])
return output
def output(input_list):
LU = 0
a = input_list[2:]
values = []
for i in xrange(1,input_list[0... | Python | zaydzuhri_stack_edu_python |
function test_is_temperature_valid self
begin
set Tdata = array list 200 400 600 800 1000 1200 1400 1600 1800 2000
set validdata = array list false true true true true true true true true true bool
for tuple T valid in zip Tdata validdata
begin
set valid0 = call is_temperature_valid T
assert equal valid0 valid
end
end ... | def test_is_temperature_valid(self):
Tdata = np.array([200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000])
validdata = np.array([False, True, True, True, True, True, True, True, True, True], np.bool)
for T, valid in zip(Tdata, validdata):
valid0 = self.kinetics.is_temperature_va... | Python | nomic_cornstack_python_v1 |
for i in range 0 n
begin
set a = input
set b = input
append nums input
end
for i in range 0 n
begin
if nums at i == string 10 22 5 75 65 80
begin
print 87
end
else
if nums at i == string 20 580 420 900
begin
print 1040
end
else
if nums at i == string 100 90 80 50 25
begin
print 0
end
else
if nums at i == string 20 58 4... | for i in range(0,n):
a =input()
b =input()
nums.append(input())
for i in range(0,n):
if nums[i]=="10 22 5 75 65 80":
print(87)
elif nums[i]=="20 580 420 900":
print(1040)
elif nums[i]=="100 90 80 50 25":
print(0)
elif nums[i]=="20 58 42 90":
print(86)
eli... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import scrapy
from scrapy import Selector
class test extends Spider
begin
set name = string test
function start_requests self
begin
set urls = list string http://lab.scrapyd.cn/page/1/
for url in urls
begin
yield call Request url=url callback=parse
end
end function
function parse self resp... | # -*- coding: utf-8 -*-
import scrapy
from scrapy import Selector
class test(scrapy.Spider):
name = "test"
def start_requests(self):
urls = [
'http://lab.scrapyd.cn/page/1/',
]
for url in urls:
yield scrapy.Request(url=url,callback=self.parse)
def parse... | Python | zaydzuhri_stack_edu_python |
from skimage.util import random_noise
import numpy as np
from scipy import misc
function apply_noise img ratio mode=string s&p scale=1
begin
string :param img: :param ratio: :param mode: :param scale: the noise function by default normalise the iamge between 0 and 1. so set the scale to 255 if you want. :return:
set im... | from skimage.util import random_noise
import numpy as np
from scipy import misc
def apply_noise(img, ratio, mode='s&p', scale=1):
"""
:param img:
:param ratio:
:param mode:
:param scale: the noise function by default normalise the iamge between 0 and 1. so set the scale to 255 if you want.
:re... | Python | zaydzuhri_stack_edu_python |
function save_map m
begin
import time
set tool_output = call Output
set tool_output = tool_output
call clear_output wait=true
set save_map_widget = call VBox
set save_type = call ToggleButtons options=list string HTML string PNG string JPG tooltips=list string Save the map as an HTML file string Take a screenshot and s... | def save_map(m):
import time
tool_output = widgets.Output()
m.tool_output = tool_output
tool_output.clear_output(wait=True)
save_map_widget = widgets.VBox()
save_type = widgets.ToggleButtons(
options=["HTML", "PNG", "JPG"],
tooltips=[
"Save the map as an HTML file",... | Python | nomic_cornstack_python_v1 |
class student
begin
pass
end class
set dark = call student
set web = call student
set name = string dark
set std = string 13th
set section = string bca
set name = string web
set std = string 14th
set section = string bca sy
print section section | class student:
pass
dark = student()
web = student()
dark.name = "dark"
dark.std = "13th"
dark.section = "bca"
web.name = "web"
web.std = "14th"
web.section = "bca sy"
print (dark.section , web.section) | Python | zaydzuhri_stack_edu_python |
function reset self dimensions lower_bound upper_bound objective_function
begin
set position = list
for i in range dimensions
begin
if lower_bound at i < upper_bound at i
begin
extend position random integer lower_bound at i upper_bound at i + 1 1 dtype=int
end
else
if lower_bound at i == upper_bound at i
begin
extend... | def reset(self,
dimensions,
lower_bound,
upper_bound,
objective_function):
position = []
for i in range(dimensions):
if lower_bound[i] < upper_bound[i]:
position.extend(np.random.randint(lower_bound[i], upper_bou... | Python | nomic_cornstack_python_v1 |
function get_aligned_dna_sequences self
begin
set tuple q s = tuple list list
for posobj in _positions
begin
set tuple _q _s = call _return_print_dna
append q _q
append s _s
end
return tuple replace join string q string string - replace join string s string string -
end function | def get_aligned_dna_sequences(self):
q,s = [],[]
for posobj in self._positions:
(_q,_s) = posobj._return_print_dna()
q.append(_q)
s.append(_s)
return ( "".join(q).replace(" ","-"), "".join(s).replace(" ","-") ) | Python | nomic_cornstack_python_v1 |
string extract all item name and corresponding ids
import json
from multiprocessing import Pool
function get_purchased_items match_file
begin
set items = set
with open match_file as f
begin
set match = load json f
set players = match at string players
for player in players
begin
set purchase_log = player at string purc... | '''
extract all item name and corresponding ids
'''
import json
from multiprocessing import Pool
def get_purchased_items(match_file):
items = set()
with open(match_file) as f:
match = json.load(f)
players = match['players']
for player in players:
purchase_log = player['purc... | Python | zaydzuhri_stack_edu_python |
if length a != length b
begin
set flag = false
end
else
begin
set i = 0
while i < length a and flag
begin
if a at i != b at length b - 1 - i
begin
set flag = false
end
else
begin
set i = i + 1
end
end
end | if len(a) != len(b):
flag = False
else:
i = 0
while i < len(a) and flag:
if a[i] != b[len(b)-1-i]:
flag = False
else:
i += 1 | Python | zaydzuhri_stack_edu_python |
function simulate_data nobs
begin
set exp_param = 9000
set poisson_param = 15
set b = array list 1 2
set x1 = call exponential scale=exp_param size=nobs
set x2 = poisson lam=poisson_param size=nobs
set X = T
set epsilon = call normal 0 1 nobs
set y = dot X b + epsilon
set data = dict string X X ; string y y ; string ep... | def simulate_data(nobs):
exp_param = 9000
poisson_param = 15
b = np.array([1,2])
x1 = np.random.exponential(scale=exp_param,size=nobs)
x2 = np.random.poisson(lam=poisson_param,size=nobs)
X = np.vstack((x1,x2)).T
epsilon = np.random.normal(0,1,nobs)
y = np.dot(X,b) + epsilon
... | Python | nomic_cornstack_python_v1 |
set arr = list 4 23 1 7 10
set n = length arr
for i in range n
begin
for j in range 0 n - i - 1
begin
if arr at j > arr at j + 1
begin
set tuple arr at j arr at j + 1 = tuple arr at j + 1 arr at j
end
end
end
print string Sorted array in non-decreasing order:
print arr | arr = [4, 23, 1, 7, 10]
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print("Sorted array in non-decreasing order:")
print(arr)
| Python | greatdarklord_python_dataset |
function sync_from_server self
begin
comment list all remote files. include delete entries so we can delete them locally, if needs be.
set resp = call files_list_folder _media_path_remote include_deleted=true
comment sync local folder with remote listing
call _sync_with_list_folder_entries entries
comment return cursor... | def sync_from_server( self ):
# list all remote files. include delete entries so we can delete them locally, if needs be.
resp = self._dbx.files_list_folder( self._media_path_remote, include_deleted=True )
# sync local folder with remote listing
self._sync_with_list_folder_entr... | Python | nomic_cornstack_python_v1 |
function intputs prompt=string >> invalid_message=string Invalid input
begin
string Generates a sequence of integers read from standard input, one per row, until an empty line is reached. For non-numeric inputs, displays invalid_input to the users, and continues input.
comment ----- YOUR CODE HE5RE! -------------------... | def intputs(prompt=">> ", invalid_message="Invalid input"):
"""Generates a sequence of integers read from standard input, one per row,
until an empty line is reached. For non-numeric inputs, displays
invalid_input to the users, and continues input.
"""
# ----- YOUR CODE HE5RE! ----------------... | Python | zaydzuhri_stack_edu_python |
comment един час има 60 минути , които се умножават по часовете и след товасе прибавят минутите, за да се получи общият сбор на минутите.
comment преобразуване всичко в минути (трябва да работим в една мерна единица - минути)
set now_in_minutes = hours * 60 + minutes
comment после прибавяме 15 минути към предните минут... | # един час има 60 минути , които се умножават по часовете и след товасе прибавят минутите, за да се получи общият сбор на минутите.
now_in_minutes = hours * 60 + minutes # преобразуване всичко в минути (трябва да работим в една мерна единица - минути)
time_after_15_minutes = now_in_minutes + 15 # после прибавяме 15 м... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function intersect self nums1 nums2
begin
set dic = dict
for n1 in nums1
begin
if n1 not in dic
begin
set dic at n1 = 1
end
else
begin
set dic at n1 = dic at n1 + 1
end
end
set res = list
for n2 in nums2
begin
if n2 in dic and dic at n2 > 0
begin
append res n2
set dic at n2 = dic at n2 - 1
end
en... | class Solution:
def intersect(self, nums1: [int], nums2: [int]) -> [int]:
dic = {}
for n1 in nums1:
if n1 not in dic:
dic[n1] = 1
else:
dic[n1] += 1
res = []
for n2 in nums2:
if n2 in dic and dic[n2] > 0:
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from idlpy import interpolate
class InterpLonLat
begin
function __init__ self origLon origLat
begin
set newLon = none
set newLat = none
set dLon = none
set dLat = none
set _xint = none
set _yint = none
set origLon = origLon
set origLat = origLat
end function
decorator property
function origLon self
b... | import numpy as np
from idlpy import interpolate
class InterpLonLat():
def __init__(self, origLon, origLat):
self.newLon = None
self.newLat = None
self.dLon = None
self.dLat = None
self._xint = None
self._yint = None
self.origLon = origLon
self.origLat = origLat
@pro... | Python | zaydzuhri_stack_edu_python |
async function set_bob self data mtype cid=none max_age=none
begin
if cid is none
begin
set cid = string sha1+%s@bob.xmpp.org % hex digest sha1 data
end
set bob = call BitsOfBinary
set bob at string data = data
set bob at string type = mtype
set bob at string cid = cid
if max_age is not none
begin
set bob at string max... | async def set_bob(self, data: bytes, mtype: str, cid: Optional[str] = None,
max_age: Optional[int] = None) -> str:
if cid is None:
cid = 'sha1+%s@bob.xmpp.org' % hashlib.sha1(data).hexdigest()
bob = BitsOfBinary()
bob['data'] = data
bob['type'] = mtype
... | Python | nomic_cornstack_python_v1 |
function _make_real self check=true
begin
string Convert the complex SHCoeffs class to the real class.
comment Test if the coefficients correspond to a real grid.
comment This is not very elegant, and the equality condition
comment is probably not robust to round off errors.
if check
begin
for l in call degrees
begin
i... | def _make_real(self, check=True):
"""Convert the complex SHCoeffs class to the real class."""
# Test if the coefficients correspond to a real grid.
# This is not very elegant, and the equality condition
# is probably not robust to round off errors.
if check:
for l in ... | Python | jtatman_500k |
function prenext self
begin
next
end function | def prenext(self):
self.next() | Python | nomic_cornstack_python_v1 |
from pdb import run
from db.run_sql import run_sql
from models.employee import Employee
from models.animal import Animal
import repositories.animal_repo as animals_repo
comment Add a delete all method
function delete_all
begin
set sql = string DELETE FROM animals
call run_sql sql
end function
comment Add a member of st... | from pdb import run
from db.run_sql import run_sql
from models.employee import Employee
from models.animal import Animal
import repositories.animal_repo as animals_repo
# Add a delete all method
def delete_all():
sql= "DELETE FROM animals"
run_sql(sql)
# Add a member of staff
def add_animal(animal):
sql... | Python | zaydzuhri_stack_edu_python |
function hydrate_arguments cls static_view_io
begin
return dict none call hydrate_arguments static_view_io ; string animations map hydrate animations
end function | def hydrate_arguments(cls, static_view_io: StaticViewIO) -> Dict:
return {
**super().hydrate_arguments(static_view_io),
"animations": map(Animation.hydrate, static_view_io.animations),
} | 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.