code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get self key
begin
if key in lru_cache
begin
set value = lru_cache at key
call move_to_end key
if key in lfu_cache
begin
set lfu_cache at key = lfu_cache at key + 1
end
else
begin
set lfu_cache at key = 1
end
return value
end
end function | def get(self, key):
if key in self.lru_cache:
value = self.lru_cache[key]
self.lru_cache.move_to_end(key)
if key in self.lfu_cache:
self.lfu_cache[key] += 1
else:
self.lfu_cache[key] = 1
return value | Python | nomic_cornstack_python_v1 |
from kivy.app import App
from random import random , randint
from kivy.uix.widget import Widget
from kivy.graphics import Color , Line , Rectangle
from kivy.core.window import Window
from kivy.clock import Clock
from math import sin
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.uix.button imp... | from kivy.app import App
from random import random, randint
from kivy.uix.widget import Widget
from kivy.graphics import Color, Line, Rectangle
from kivy.core.window import Window
from kivy.clock import Clock
from math import sin
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.uix.button import... | Python | zaydzuhri_stack_edu_python |
function text self
begin
return decode read open string utf-8
end function | def text(self) -> str:
return self.load().open().read().decode('utf-8') | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template , request
from gnupg import GnuPG
set app = call Flask __name__
set gpg = call GnuPG
function fingerprint_to_color fp
begin
set colors = list string red string orange string yellow string green string blue string indigo string violet
set max_num = integer string fffffffffffffff... | from flask import Flask, render_template, request
from gnupg import GnuPG
app = Flask(__name__)
gpg = GnuPG()
def fingerprint_to_color(fp):
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet']
max_num = int('ffffffffffffffffffffffffffffffffffffffff', 16)
blocksize = max_num / len(colo... | Python | zaydzuhri_stack_edu_python |
function try_demo_mode_now
begin
set tuple msg status = tuple string true
try
begin
sleep 10
if platform == string android
begin
string Getting y_elem as destination element
set y_elem = call ui_element call get_obj_identifier string common_widget_scrollview
string Getting x_elem as source element
set x_elem = call ui... | def try_demo_mode_now():
msg, status = "", True
try:
sleep(10)
if g.platform == 'android':
'Getting y_elem as destination element'
y_elem = ui_controls.ui_element(get_obj_identifier('common_widget_scrollview'))
'Getting x_elem as source element'
... | Python | nomic_cornstack_python_v1 |
function print_workout_days workout my_workouts=WORKOUTS
begin
set days = list comprehension title day for tuple day wo in items my_workouts if lower workout in lower wo
print if expression days then join string , days else string No matching workout
end function | def print_workout_days(workout: str, my_workouts: dict = WORKOUTS) -> None:
days = [day.title() for day, wo in my_workouts.items()
if workout.lower() in wo.lower()]
print(', '.join(days) if days else 'No matching workout') | Python | nomic_cornstack_python_v1 |
for num in range 11
begin
if num == 5
begin
continue
end
if num % 2 == 0
begin
print num
end
end | for num in range(11):
if num == 5:
continue
if num % 2 == 0:
print(num)
| Python | greatdarklord_python_dataset |
function test_ace_swepam_hourly_omni_norm_bad_keys self
begin
with raises ValueError as verr
begin
call ace_swepam_hourly_omni_norm testInst
end
comment Test the error message for missing data variables
assert find string verr string instrument missing variable >= 0
return
end function | def test_ace_swepam_hourly_omni_norm_bad_keys(self):
with pytest.raises(ValueError) as verr:
mm_ace.ace_swepam_hourly_omni_norm(self.testInst)
# Test the error message for missing data variables
assert str(verr).find("instrument missing variable") >= 0
return | Python | nomic_cornstack_python_v1 |
print string 1.Lấy link tuyển dụng 2.Thu thập thông tin tuyển dụng(Tiêu đề, mô tả, vị trí tuyển dụng, . . .) 3.Thu thập thông tin ứng viên(Tên, bằng cấp, địa chỉ, . . ) 4.Loại bỏ Stopword 5.Thống kê ngành nghề tuyển dụng 6.Thống kê địa điểm tuyển dụng 7.Thoát
print string 1. tieude 2. mota | print("""
1.Lấy link tuyển dụng
2.Thu thập thông tin tuyển dụng(Tiêu đề, mô tả, vị trí tuyển dụng, . . .)
3.Thu thập thông tin ứng viên(Tên, bằng cấp, địa chỉ, . . )
4.Loại bỏ Stopword
5.Thống kê ngành nghề tuyển dụng
6.Thống kê địa điểm tuyển dụng
7.Thoát
""")
print("""
1. t... | Python | zaydzuhri_stack_edu_python |
function entropy loc=0 scale=1
begin
with call extradps 5
begin
set tuple loc scale = call _validate_loc_scale loc scale
return log 2 * pi + log scale
end
end function | def entropy(loc=0, scale=1):
with mp.extradps(5):
loc, scale = _validate_loc_scale(loc, scale)
return mp.log(2*mp.pi) + mp.log(scale) | Python | nomic_cornstack_python_v1 |
import sys
set f = open argv at 1
set testcasecount = integer read line f
for testcase in range testcasecount
begin
comment print("Case #%d:" % (testcase+1))
set testinp = split read line f at slice : - 1 : string
comment print(testinp)
set Smax = integer testinp at 0
set audience = testinp at 1
set guestcount = 0
se... | import sys
f = open(sys.argv[1])
testcasecount = int(f.readline())
for testcase in range(testcasecount):
#print("Case #%d:" % (testcase+1))
testinp = f.readline()[:-1].split(" ")
#print(testinp)
Smax = int(testinp[0])
audience = testinp[1]
guestcount = 0
standing = 0
lvl = 0
wh... | Python | zaydzuhri_stack_edu_python |
function test_compliance_rule
begin
set client = call CBWApi API_URL API_KEY SECRET_KEY
set validate_compliance_rule = string cbw_object(id=6891, audit='Verify cron is enabledchecks:=[{"order" = 1,"content" = "systemctl is-enabled cron","success" = "enabled","failure" = "disabled"},{"order" = 2,"content" = "service cro... | def test_compliance_rule():
client = CBWApi(API_URL, API_KEY, SECRET_KEY)
validate_compliance_rule = """cbw_object(id=6891, audit='Verify cron is enabledchecks:=[{"order" = 1,\
"content" = "systemctl is-enabled cron","success" = "enabled","failure" = "disabled"},{"order" = 2,\
"content" = "service cron... | Python | nomic_cornstack_python_v1 |
function parse cls source
begin
set self = call cls source
set pt = call syntax_tree
call visit pt
comment one indexing
set lineno_end = count source string + 2
call process_finished lineno_end
return self
end function | def parse(cls, source):
self = cls(source)
pt = self.syntax_tree()
self.visit(pt)
lineno_end = source.count('\n') + 2 # one indexing
self.process_finished(lineno_end)
return self | Python | nomic_cornstack_python_v1 |
function getPermisosByRol idrol
begin
set yourPermisos = all
return yourPermisos
end function | def getPermisosByRol(idrol):
yourPermisos = db_session.query(Permiso).join(RolPermiso, RolPermiso.id_permiso == Permiso.id).filter(RolPermiso.id_rol == idrol).all()
return yourPermisos | Python | nomic_cornstack_python_v1 |
function _append_value self value _file _name
begin
string Call this function to write contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file * _name - str, name of current content dict
set _tabs = string * _tctr
set _cmma = if expression _vctr at _tctr then string , else strin... | def _append_value(self, value, _file, _name):
"""Call this function to write contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
* _name - str, name of current content dict
"""
_tabs = '\t' * self._tctr
... | Python | jtatman_500k |
comment coding=utf-8
import paramiko
import os , threading , datetime , logging , time , sys
import re
call reload sys
call setdefaultencoding string utf8
append path string ../
from base import *
from flask import session , redirect , url_for
class ConnectNode extends object
begin
function __init__ self
begin
string i... | # coding=utf-8
import paramiko
import os, threading, datetime, logging, time, sys
import re
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append('../')
from base import *
from flask import session, redirect, url_for
class ConnectNode(object):
def __init__(self):
"""
init connect
... | Python | zaydzuhri_stack_edu_python |
if num == 0
begin
set result = string 0
end
while num > 0
begin
set result = string num % 2 + result
set num = num / 2
end
for i in range p - length result
begin
set result = string 0 + result
end
set result = result at slice 0 : - p : + string . + result at slice - p : :
print string The binary representaion of the... | if num==0:
result='0'
while num>0:
result = str(num%2)+result
num = num/2
for i in range(p-len(result)):
result='0'+result
result = result[0:-p]+ '.' + result[-p:]
print('The binary representaion of the decimal '+ str(x)+' is '+str(result))
| Python | zaydzuhri_stack_edu_python |
function bold self text
begin
return join string list comprehension ch + string + ch for ch in text
end function | def bold(self, text):
return ''.join([ch+'\b'+ch for ch in text]) | Python | nomic_cornstack_python_v1 |
comment Go to https://polisci.wustl.edu/faculty/specialization
comment Go to the page for each of the professors.
comment Create a .csv file with the following information for each professor:
comment -Specialization
comment -Name
comment -Title
comment -E-mail
comment -Web page
from bs4 import BeautifulSoup
import urll... | #Go to https://polisci.wustl.edu/faculty/specialization
#Go to the page for each of the professors.
#Create a .csv file with the following information for each professor:
# -Specialization
# -Name
# -Title
# -E-mail
# -Web page
from bs4 import BeautifulSoup
import urllib2
import csv
import random
import time
impo... | Python | zaydzuhri_stack_edu_python |
import csv
function fix_turnstile_data filenames
begin
string Filenames is a list of MTA Subway turnstile text files. A link to an example MTA Subway turnstile text file can be seen at the URL below: http://web.mta.info/developers/data/nyct/turnstile/turnstile_110507.txt As you can see, there are numerous data points i... | import csv
def fix_turnstile_data(filenames):
'''
Filenames is a list of MTA Subway turnstile text files. A link to an example
MTA Subway turnstile text file can be seen at the URL below:
http://web.mta.info/developers/data/nyct/turnstile/turnstile_110507.txt
As you can see, there are numerous dat... | Python | zaydzuhri_stack_edu_python |
string Module that contains a PNET network of the Mtcc algorithm
import Networks.Tensorflow.Network as n
class PNet extends Network
begin
function __init__ self trainable=true
begin
call __init__ string PNet trainable
end function
function createNetwork self
begin
call addInputLayer string data tuple none none none 3
c... | """ Module that contains a PNET network of the Mtcc algorithm """
import Networks.Tensorflow.Network as n
class PNet(n.Network):
def __init__(self, trainable=True):
super(PNet, self).__init__('PNet', trainable)
def createNetwork(self):
self.addInputLayer('data', (None, None, None, 3))
... | Python | zaydzuhri_stack_edu_python |
function summary self summary
begin
set _summary = summary
end function | def summary(self, summary):
self._summary = summary | Python | nomic_cornstack_python_v1 |
comment -*- coding: UTF-8 -*-
comment 作者:hao.ren3
comment 时间:2020/8/7 14:28
comment IDE:PyCharm
comment https://zhuanlan.zhihu.com/p/121799598
from Tools.data import get_train_test_data
import toad
from toad.plot import bin_plot
if __name__ == string __main__
begin
set tuple train_data test_data = call get_train_test_d... | # -*- coding: UTF-8 -*-
# 作者:hao.ren3
# 时间:2020/8/7 14:28
# IDE:PyCharm
# https://zhuanlan.zhihu.com/p/121799598
from Tools.data import get_train_test_data
import toad
from toad.plot import bin_plot
if __name__ == '__main__':
train_data, test_data = get_train_test_data()
# 返回每个特性的EDA报告,包括数据类型、分布、缺失率和惟一值。
... | Python | zaydzuhri_stack_edu_python |
function aspect_ratio self
begin
return w / decimal h
end function | def aspect_ratio(self):
return self.w / float(self.h) | Python | nomic_cornstack_python_v1 |
function __capitalise_keys__ self
begin
comment set function name
set _ = call display_func string __capitalise_keys__ __NAME__ string CaseInsensitiveDict
comment make keys a list
set keys = list keys self
comment loop around key in keys
for key in keys
begin
comment check if key is a string
if type key == str
begin
co... | def __capitalise_keys__(self):
# set function name
_ = display_func('__capitalise_keys__', __NAME__, 'CaseInsensitiveDict')
# make keys a list
keys = list(self.keys())
# loop around key in keys
for key in keys:
# check if key is a string
if type(ke... | Python | nomic_cornstack_python_v1 |
from data_structures.stacks_and_queues.stacks_and_queues import Node , Stack , EmptyQueueException
from queue_with_stacks import PseudoQueue
import pytest
function test_pseudoqueue_dequeue_multiple
begin
set testing_queue = call PseudoQueue stack
call enqueue 1
call enqueue 2
call dequeue
set expected = 2
set actual = ... | from data_structures.stacks_and_queues.stacks_and_queues import Node, Stack, EmptyQueueException
from queue_with_stacks import PseudoQueue
import pytest
def test_pseudoqueue_dequeue_multiple():
testing_queue = PseudoQueue(Stack())
testing_queue.enqueue(1)
testing_queue.enqueue(2)
testing_queue.dequeue(... | Python | zaydzuhri_stack_edu_python |
import csv
import glob
import os
import sys
from collections import OrderedDict
function get_products_for_wbs productlist wbs wbs_list
begin
comment Return a list of product descriptions which match the specified WBS
comment element.
comment We return products at the finest level of WBS to which they correspond.
commen... | import csv
import glob
import os
import sys
from collections import OrderedDict
def get_products_for_wbs(productlist, wbs, wbs_list):
# Return a list of product descriptions which match the specified WBS
# element.
# We return products at the finest level of WBS to which they correspond.
# That is, if... | Python | zaydzuhri_stack_edu_python |
function topic self
begin
return string { OUTBOUND_STATUS_PREFIX } { value }
end function | def topic(self):
return f"{OUTBOUND_STATUS_PREFIX}{self.value}" | Python | nomic_cornstack_python_v1 |
function detect_labels_uri uri n
begin
set results = dict
from google.cloud import vision
set client = call ImageAnnotatorClient
set image = call Image
set image_uri = uri
set response = call label_detection image=image max_results=n
set labels = label_annotations
set results = dictionary generator expression tuple de... | def detect_labels_uri(uri, n):
results = {}
from google.cloud import vision
client = vision.ImageAnnotatorClient()
image = vision.Image()
image.source.image_uri = uri
response = client.label_detection(image=image, max_results=n)
labels = response.label_annotations
results = di... | Python | nomic_cornstack_python_v1 |
function test_amin_general_function_01 self
begin
set result = call amin gentest
assert equal result min gentest
end function | def test_amin_general_function_01(self):
result = arrayfunc.amin(self.gentest )
self.assertEqual(result, min(self.gentest)) | Python | nomic_cornstack_python_v1 |
function get_order_number self
begin
return __order_number
end function | def get_order_number(self):
return self.__order_number | Python | nomic_cornstack_python_v1 |
function check_file
begin
comment print('request=', request)
comment print('request.data=', request.data)
comment print('request.form=', request.form)
comment print('request.files=', request.files)
comment print('request.json=', request.json)
set qdata = none
set adata = none
set Q = none
set A = none
if json
begin
set... | def check_file():
#print('request=', request)
#print('request.data=', request.data)
#print('request.form=', request.form)
#print('request.files=', request.files)
#print('request.json=', request.json)
qdata = None
adata = None
Q = None
A = None
if request.json:
qdata = req... | Python | nomic_cornstack_python_v1 |
function __lt__ self other
begin
return call __float__ < other
end function | def __lt__(self, other):
return self.__float__() < other | Python | nomic_cornstack_python_v1 |
from sklearn.feature_extraction.text import CountVectorizer
from sklearn import preprocessing
import scipy.sparse
import numpy as np
import csv
from sklearn.model_selection import train_test_split
set fname = string data.1.tsv
set fname_output = string features
set titles = list
set sources = list
set venues = list
... | from sklearn.feature_extraction.text import CountVectorizer
from sklearn import preprocessing
import scipy.sparse
import numpy as np
import csv
from sklearn.model_selection import train_test_split
fname = 'data.1.tsv'
fname_output = 'features'
titles = []
sources = []
venues = []
with open(fname) as tsvin:
tsvin ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import urllib.request , urllib.error , urllib.parse
from urllib.request import FancyURLopener
import threading
from robot import *
from config import *
from tools import *
class ExceptionUrlForbid extends Exception
begin
pass
end class
class ExceptionMaxTries extends Exception
begin
pass
e... | # -*- coding: utf-8 -*-
import urllib.request, urllib.error, urllib.parse
from urllib.request import FancyURLopener
import threading
from robot import *
from config import *
from tools import *
class ExceptionUrlForbid(Exception):
pass
class ExceptionMaxTries(Exception):
pass
class UrlHandler(FancyURLopener):
... | Python | zaydzuhri_stack_edu_python |
function get_stats_SWE self kelly_list svalex_list svalex2_list word_pictures=dict use_deprel=true use_ngrams=false
begin
set s = sent
set root_ref = call check_root s
set tokens = list
comment {"verb1": {arg1_pos:"PN", arg1_deprel:"SS", etc.},..}
set verb_args = dict
set stats at string finite = list
set stats at ... | def get_stats_SWE(self, kelly_list, svalex_list, svalex2_list, word_pictures={}, use_deprel=True,use_ngrams=False):
s = self.sent
root_ref = check_root(s)
tokens = []
verb_args = {} #{"verb1": {arg1_pos:"PN", arg1_deprel:"SS", etc.},..}
self.stats["finite"] = []
self.st... | Python | nomic_cornstack_python_v1 |
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 buildTree self inorder postorder
begin
comment inorder left root right
comment postorder l... | # 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 buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
# inorder left root right... | Python | zaydzuhri_stack_edu_python |
function values self
begin
return _values
end function | def values(self) -> Dict[str, float]:
return self._values | Python | nomic_cornstack_python_v1 |
from abc import ABC
from jComputers.jComputer import JComputer
class Constant extends JComputer
begin
function __init__ self nnOnly t rdep
begin
string J_ij = t , or if rdep is true, J_ij = t/r^3 t - self-explanatory rdep - whether or not to have J depend on r^3
call __init__ nnOnly
set t = t
set rdep = rdep
if rdep
be... | from abc import ABC
from jComputers.jComputer import JComputer
class Constant(JComputer) :
def __init__(self, nnOnly, t, rdep):
""" J_ij = t , or if rdep is true, J_ij = t/r^3
t - self-explanatory
rdep - whether or not to have J depend on r^3
"""
super().__init__(nnOnly)
self.t = t
self.... | Python | zaydzuhri_stack_edu_python |
function major_min self
begin
set result = if expression round_extrema then call rounded_down data_min major_delta else data_min
if not data_length
begin
set result = result - major_delta
end
return result
end function | def major_min (self) :
result = rounded_down (self.data_min, self.major_delta) \
if self.round_extrema else self.data_min
if not self.data_length :
result -= self.major_delta
return result | Python | nomic_cornstack_python_v1 |
class feature
begin
function __init__ self desc trav rough=none open=none lock=none search=none contain=none breakable=none
begin
comment description of the feature in question
set desc = desc
comment a flag which decides if a feature is traversable
set trav = trav
comment a flag which decides if the terrain is rough
s... | class feature:
def __init__(self, desc, trav, rough=None, open=None, lock=None, search=None, contain=None, breakable=None):
self.desc = desc #description of the feature in question
self.trav = trav #a flag which decides if a feature is traversable
self.rough = rough #a flag which decides i... | Python | zaydzuhri_stack_edu_python |
import json
import pickle
import random
from glob import glob
from kaggle_environments.envs.hungry_geese.hungry_geese import Configuration , Action
from game_state import GameState
from goose import Goose
function create_game_state steps
begin
set configuration = call Configuration dict string columns 11 ; string rows ... | import json
import pickle
import random
from glob import glob
from kaggle_environments.envs.hungry_geese.hungry_geese import Configuration, Action
from game_state import GameState
from goose import Goose
def create_game_state(steps):
configuration = Configuration({"columns": 11,
... | Python | zaydzuhri_stack_edu_python |
import os
import pandas as pd
import pandas_datareader.data as web
from collections import OrderedDict
function get_stock_data symbol start_date=none end_date=none
begin
string Get daily resolution O/H/L/C stock data from Yahoo Finance for a single symbol. If start_date and end_date are None, get's all possible data. :... | import os
import pandas as pd
import pandas_datareader.data as web
from collections import OrderedDict
def get_stock_data(symbol, start_date=None, end_date=None):
"""
Get daily resolution O/H/L/C stock data from Yahoo Finance for a single symbol.
If start_date and end_date are None, get's all possible dat... | Python | zaydzuhri_stack_edu_python |
function decorator meth
begin
return call XmlAttributeProperty name meth deserialize=deserialize version=version
end function | def decorator(meth):
return XmlAttributeProperty(name, meth, deserialize=deserialize, version=version) | Python | nomic_cornstack_python_v1 |
string Dispatcher module.
import asyncio
import logging
import time
from typing import List
from monitor import Monitor
class Dispatcher
begin
function __init__ self monitors
begin
set _monitors = monitors
set _monitor_tasks : List at Task = list
set _logger = call getLogger __name__
set _stopping = true
end function
... | """Dispatcher module."""
import asyncio
import logging
import time
from typing import List
from monitor import Monitor
class Dispatcher:
def __init__(self, monitors: List[Monitor]) -> None:
self._monitors = monitors
self._monitor_tasks: List[asyncio.Task] = []
self._logger = logging.get... | Python | zaydzuhri_stack_edu_python |
function writeData self page_data
begin
set url = page_data at 0
set links = page_data at 1
set assets = page_data at 2
set w = w
write w url + string
write w string LINKS:
for link in links
begin
write w string + link + string
end
write w string ASSETS:
for asset in assets
begin
write w string + asset + string
end
w... | def writeData(self, page_data):
url = page_data[0]
links = page_data[1]
assets = page_data[2]
w = self.w
w.write(url + '\n')
w.write('LINKS:\n')
for link in links:
w.write(' ' + link + '\n')
w.write('ASSETS:\n')
for asset in assets:
w.write(' ' + asset + '\n')
... | Python | nomic_cornstack_python_v1 |
function privileged_polling self **kwargs
begin
return call api_request call _get_method_fullname string privileged_polling kwargs
end function | def privileged_polling(self, **kwargs):
return self.api_request(self._get_method_fullname("privileged_polling"), kwargs) | Python | nomic_cornstack_python_v1 |
function pc_output_buffers_full_avg self *args
begin
return call ScapyRadio_PDU_to_TS_sptr_pc_output_buffers_full_avg self *args
end function | def pc_output_buffers_full_avg(self, *args):
return _scapy_radio_swig.ScapyRadio_PDU_to_TS_sptr_pc_output_buffers_full_avg(self, *args) | Python | nomic_cornstack_python_v1 |
while command != string End
begin
set suitcase_volume = decimal command
if number_of_suitcase_loaded % 3 == 0
begin
suitcase_volume * 1.1
end
set total_suitcase_volume = total_suitcase_volume + suitcase_volume
if airplane_cargo_capacity <= total_suitcase_volume
begin
set is_cargo_full = true
break
end
set number_of_sui... | while command != "End":
suitcase_volume = float(command)
if number_of_suitcase_loaded % 3 == 0:
suitcase_volume * 1.1
total_suitcase_volume += suitcase_volume
if airplane_cargo_capacity <= total_suitcase_volume:
is_cargo_full = True
break
number_of_suitcase_loaded += 1
co... | Python | zaydzuhri_stack_edu_python |
function part_a puzzle_input
begin
set instructions = split join string puzzle_input
set players = integer instructions at 0
set last_marble_point = integer instructions at 6
set max_score = call play_marbles players last_marble_point
return string max_score
end function | def part_a(puzzle_input):
instructions = ''.join(puzzle_input).split()
players = int(instructions[0])
last_marble_point = int(instructions[6])
max_score = play_marbles(players, last_marble_point)
return str(max_score) | Python | nomic_cornstack_python_v1 |
comment Nowhere in the code is a file imported or opened.
comment The mrjob library works by reading in a file passed to it in the terminal.
from mrjob.job import MRJob
class Bacon_count extends MRJob
begin
comment Divides up the work
function mapper self _ line
begin
for word in split line
begin
if lower word == strin... | # Nowhere in the code is a file imported or opened.
# The mrjob library works by reading in a file passed to it in the terminal.
from mrjob.job import MRJob
class Bacon_count(MRJob):
# Divides up the work
def mapper(self, _, line):
for word in line.split():
if word.lower() == "bacon":
... | Python | zaydzuhri_stack_edu_python |
function reduce_to_planar_3_coloring G
begin
if call is_planar
begin
return G
end
set H = call from_graph G
for e in false_edges
begin
set tuple u v = e
comment set a combinatorial embedding in H
call is_planar
comment find the minimum crossing path from u to v
set path = call min_crossing_path H u v
comment apply the ... | def reduce_to_planar_3_coloring(G):
if G.is_planar():
return G
H = FalsePlanarGraph.from_graph(G)
for e in H.false_edges:
u, v = e
# set a combinatorial embedding in H
H.is_planar()
# find the minimum crossing path from u to v
path = min_crossing_path(H, ... | Python | nomic_cornstack_python_v1 |
set person = dict string name string John ; string age 20 ; string gender string Male ; string occupation string Engineer | person = {
"name": "John",
"age": 20,
"gender": "Male",
"occupation": "Engineer"
}
| Python | jtatman_500k |
import matplotlib
call use string Agg
import os
import io
import base64
import numpy as np
import numpy.matlib
import scipy.signal
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
from scipy.io import loadmat
from utils import prepare_gt
function visualize_mil videoname frame_... | import matplotlib
matplotlib.use('Agg')
import os
import io
import base64
import numpy as np
import numpy.matlib
import scipy.signal
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
from scipy.io import loadmat
from utils import prepare_gt
def visualize_mil(
videoname, ... | Python | zaydzuhri_stack_edu_python |
function filter_empty_rows self table
begin
call _requires_table table
set empty = list
for tuple idx row in call iter_lists
begin
if all generator expression value is none for value in row
begin
append empty idx
end
end
call delete_rows empty
end function | def filter_empty_rows(self, table: Table):
self._requires_table(table)
empty = []
for idx, row in table.iter_lists():
if all(value is None for value in row):
empty.append(idx)
table.delete_rows(empty) | Python | nomic_cornstack_python_v1 |
function private_key_decrypt_message self encrypted_message private_key
begin
set priv = call load_key_string private_key
set p = get attribute RSA string pkcs1_padding
set ptxt = call public_decrypt encrypted_message p
return ptxt
end function | def private_key_decrypt_message(self, encrypted_message, private_key):
priv = RSA.load_key_string(private_key)
p = getattr(RSA, 'pkcs1_padding')
ptxt = priv.public_decrypt(encrypted_message, p)
return ptxt | Python | nomic_cornstack_python_v1 |
comment import cv2
comment import numpy as np
comment import math
comment img = cv2.imread("/home/aditya/diptemp/sudoku.png")
comment grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
comment gau = cv2.GaussianBlur(grey,(11,11),math.sqrt(2),math.sqrt(2))
comment edges = cv2.Canny(gau,50,150,apertureSize = 3)
comment cv2.imwr... | # import cv2
# import numpy as np
# import math
# img = cv2.imread("/home/aditya/diptemp/sudoku.png")
# grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# gau = cv2.GaussianBlur(grey,(11,11),math.sqrt(2),math.sqrt(2))
# edges = cv2.Canny(gau,50,150,apertureSize = 3)
# cv2.imwrite("/home/aditya/diptemp/sudoku_edges.png",edg... | Python | zaydzuhri_stack_edu_python |
function main
begin
set parser = call ArgumentParser
call add_argument string --light action=string store_true default=false help=string Import without downloading any new files
call add_argument string --username default=string
call add_argument string --password default=string
call add_argument string --lastmail acti... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--light', action='store_true', default=False,
help='Import without downloading any new files')
parser.add_argument('--username', default='')
parser.add_argument('--password', default='')
parser.add_argument('... | Python | nomic_cornstack_python_v1 |
if y % 4 == 0 and y % 100 != 0
begin
print 1
end
else
if y % 400 == 0
begin
print 1
end
else
begin
print 0
end | if y % 4 == 0 and y % 100 != 0: print(1)
elif y % 400 == 0: print(1)
else: print(0)
| Python | zaydzuhri_stack_edu_python |
import random
function is_innotas
begin
set prod = call get_product
if prod == string Innotas
begin
return true
end
else
begin
return false
end
end function
function get_product
begin
set prod = random choice list string PVE string PP string Innotas
return prod
end function
print call is_innotas | import random
def is_innotas():
prod = get_product()
if prod == 'Innotas':
return True
else:
return False
def get_product():
prod = random.choice(['PVE', 'PP', 'Innotas'])
return prod
print(is_innotas()) | Python | zaydzuhri_stack_edu_python |
import random as r
class Hive
begin
function __init__ this num_start repchance deathchance
begin
set num_start = num_start
set repchance = repchance
set deathchance = deathchance
set bees = list
call populate
end function
function __str__ this
begin
set rep = 0
set death = 0
set pop = length bees
for bee in bees
begin... | import random as r
class Hive():
def __init__(this, num_start, repchance, deathchance):
this.num_start = num_start
this.repchance = repchance
this.deathchance = deathchance
this.bees = []
this.populate()
def __str__(this):
rep = 0;
death = 0;
po... | Python | zaydzuhri_stack_edu_python |
comment flask packages
from flask import jsonify
from flask import request
from flask_restful import Resource
from flask_jwt_extended import jwt_required , get_jwt_identity
comment mongo-engine classes
from MongoEngineDB.Models.Users import User
class UsersApi extends Resource
begin
decorator jwt_required
function get ... | # flask packages
from flask import jsonify
from flask import request
from flask_restful import Resource
from flask_jwt_extended import jwt_required, get_jwt_identity
# mongo-engine classes
from MongoEngineDB.Models.Users import User
class UsersApi(Resource):
@jwt_required
def get(self):
output = User.... | Python | zaydzuhri_stack_edu_python |
import os
import pyqrcode
from PIL import Image
set pre = input string Enter the Prefix Name:
set strg = integer input string Enter the starting range:
set edrg = integer input string Enter the Ending range:
set inc = integer input string Enter the increment:
set fol = input string Enter the Output folder name:
set inc... | import os
import pyqrcode
from PIL import Image
pre=input('Enter the Prefix Name: ')
strg=int(input('Enter the starting range: '))
edrg=int(input('Enter the Ending range: '))
inc=int(input('Enter the increment: '))
fol=input('Enter the Output folder name: ')
inc= inc if inc>=0 else -inc
os.system(f"mkdir {fol}... | Python | zaydzuhri_stack_edu_python |
function get_targets self group_set target_set=list
begin
set result_id = list
if not is instance group_set list
begin
for target in select call _db target
begin
append result_id id
end
end
else
begin
set rows = select call _db targetgroup
for row in rows
begin
if id in group_set
begin
set targets = loads targets
for ... | def get_targets(self, group_set, target_set=[]):
result_id = []
if not isinstance(group_set, list):
for target in self._db(self._db.target).select():
result_id.append(target.id)
else:
rows = self._db(self._db.targetgroup).select()
for ro... | Python | nomic_cornstack_python_v1 |
function first_gap self
begin
set a = call gap_indices
try
begin
return a at 0
end
except IndexError
begin
return none
end
end function | def first_gap(self):
a = self.gap_indices()
try:
return a[0]
except IndexError:
return None | Python | nomic_cornstack_python_v1 |
comment 投信買賣超彙總表
comment sqlite3 can only run in console
from sqlite3 import *
set conn = call connect string C:\Users\ak66h_000\Documents\TEJ.sqlite3
set c = call cursor
import requests
from bs4 import BeautifulSoup
from numpy import *
from pandas import *
from functools import *
import re
function mymerge x y
begin
s... | ##投信買賣超彙總表
# sqlite3 can only run in console
from sqlite3 import *
conn = connect('C:\\Users\\ak66h_000\\Documents\\TEJ.sqlite3')
c = conn.cursor()
import requests
from bs4 import BeautifulSoup
from numpy import *
from pandas import *
from functools import *
import re
def mymerge(x, y):
m = merge(x, y, how='oute... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import sys
set IMPOSSIBLE = list
function transpose grid
begin
return map list zip *grid
end function
function find_grid R C M
begin
string Return a grid of a solution, if one exists, otherwise [] Observations: * WLOG, C <= R (otherwise, take the transpose of a solution) * Trivial cases ar... | #!/usr/bin/env python
import sys
IMPOSSIBLE = []
def transpose(grid):
return map(list, zip(*grid))
def find_grid(R, C, M):
"""Return a grid of a solution, if one exists, otherwise []
Observations:
* WLOG, C <= R (otherwise, take the transpose of a solution)
* Trivial cases are:
- M = 0 or... | Python | zaydzuhri_stack_edu_python |
function sbm a b c d
begin
set f = dict string cvview_dcvview_dcvview_d vsip_cvsbm_d ; string cvview_fcvview_fcvview_f vsip_cvsbm_f ; string vview_dvview_dvview_d vsip_vsbm_d ; string vview_fvview_fvview_f vsip_vsbm_f
set t = call getType a at 1 + call getType b at 1 + call getType c at 1
assert t in f msg string Type ... | def sbm(a,b,c,d):
f={'cvview_dcvview_dcvview_d':vsip_cvsbm_d,
'cvview_fcvview_fcvview_f':vsip_cvsbm_f,
'vview_dvview_dvview_d':vsip_vsbm_d,
'vview_fvview_fvview_f':vsip_vsbm_f}
t=getType(a)[1]+getType(b)[1]+getType(c)[1]
assert t in f,'Type <:%s:> not supported by sbm.'%t
f[t](a,b,c... | Python | nomic_cornstack_python_v1 |
set x = integer input
set i = map int split input
set integer_list = tuple i
set k = call hash integer_list
print integer_list
print k | x = int(input())
i = map(int,input().split())
integer_list = tuple(i)
k = hash(integer_list)
print (integer_list)
print(k) | Python | zaydzuhri_stack_edu_python |
function domino n
begin
for i in range n
begin
for j in range i n
begin
print string | { i } || { j } |
end
end
end function
call domino 6 | def domino(n):
for i in range(n):
for j in range(i, n):
print(f'| {i} || {j} |')
domino(6) | Python | zaydzuhri_stack_edu_python |
import csv
set ifile = open string testIBMMSFTAAPL.csv string rb
set reader = reader ifile
set rownum = 0
set msftCount = 0
set ibmCount = 0
set aaplCount = 0
for row in reader
begin
comment Save header row
if rownum == 0
begin
set header = row
end
comment print row
if string MSFT in row
begin
set msftCount = msftCount... | import csv
ifile = open('testIBMMSFTAAPL.csv', 'rb')
reader = csv.reader(ifile)
rownum = 0
msftCount = 0
ibmCount = 0
aaplCount = 0
for row in reader:
# Save header row
if rownum == 0:
header = row
# print row
if "MSFT" in row:
msftCount += 1
elif "IBM" in row:
ibmCount +... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import os , sys , random
import Graph
set debugLegalMoves = false
set debugWhiteRandom = false
set Color = dict string White 0 ; string Black 1
set BoardState = dict string None 0 ; string Checkmate 1 ; string Stalemate 2
class AIChessGame extends object
begin
function __init__ self
begin
s... | #!/usr/bin/env python
import os, sys, random
import Graph
debugLegalMoves = False
debugWhiteRandom = False
Color = {"White":0, "Black":1}
BoardState = {"None":0, "Checkmate":1, "Stalemate":2}
class AIChessGame(object):
def __init__(self):
self.lookahead = 4
self.testCase = 0
self.useHeuristicY = False
self... | Python | zaydzuhri_stack_edu_python |
set file = open string C:\Users\jaspr\OneDrive\Desktop\python in vs code\abc.txt string a
set str = input string Enter the text to send it to the file =
set st = write file str
print string The statemwnt contains st string character
write file string
close file | file = open("C:\\Users\\jaspr\\OneDrive\\Desktop\\python in vs code\\abc.txt",'a')
str = input("Enter the text to send it to the file = ")
st = file.write(str)
print("The statemwnt contains",st,"character")
file.write("\n")
file.close() | Python | zaydzuhri_stack_edu_python |
from sum_matrix import sum_matrix
function matrix_bombing_plan m
begin
set coords = list comprehension tuple x y for x in range 3 for y in range 3
set bombed = dict
for cor in coords
begin
set matrix_to_bomb = list comprehension list comprehension x for x in y for y in m
set bombed at cor = call sum_matrix call negati... | from sum_matrix import sum_matrix
def matrix_bombing_plan(m):
coords = [(x, y) for x in range(3) for y in range(3)]
bombed = {}
for cor in coords:
matrix_to_bomb = [[x for x in y] for y in m]
bombed[cor] = sum_matrix(negative_to_zero(bomb(matrix_to_bomb, cor)))
return bombed
def bomb... | Python | zaydzuhri_stack_edu_python |
function allSites self expandSeries=true
begin
for siteNames in values _typeDict
begin
for name in siteNames
begin
set site = get attribute self name
if is instance site IconSiteSeries
begin
if expandSeries
begin
for s in sites
begin
yield s
end
end
else
begin
yield site
end
end
else
if is instance site IconSite
begin
... | def allSites(self, expandSeries=True):
for siteNames in self._typeDict.values():
for name in siteNames:
site = getattr(self, name)
if isinstance(site, IconSiteSeries):
if expandSeries:
for s in site.sites:
... | Python | nomic_cornstack_python_v1 |
comment !C:\python36
string Created on Feb 18, 2017 @author: Kyle Doubleday
import pronouncing , random , sys
set phones = list
set haikuString = list
set workingText = list
set myListofSyllableCounts = list
with open argv at 1 mode=string r as inputFile
begin
set text = read inputFile
end
set text = lower replace ... | #!C:\python36
'''
Created on Feb 18, 2017
@author: Kyle Doubleday
'''
import pronouncing, random, sys
phones = []
haikuString = []
workingText = []
myListofSyllableCounts = []
with open(sys.argv[1], mode="r") as inputFile:
text = inputFile.read()
text = text.replace('\n',' ').replace('\r','... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding: utf-8 -*-
string author: Eufrázio Alexandre & Johnny Pereira email: (eufrazius,johnnyuft)@gmail.com last modified: March 2017
import numpy as np
comment *******************************
comment 1ª FASE DO PROCESSO
comment Definição da classe principal Automato()
comment junt... | # !/usr/bin/python3
# -*- coding: utf-8 -*-
"""
author: Eufrázio Alexandre & Johnny Pereira
email: (eufrazius,johnnyuft)@gmail.com
last modified: March 2017
"""
import numpy as np
# *******************************
# 1ª FASE DO PROCESSO
# Definição da classe principal Automato()
# juntamente com seus métodos e atribut... | Python | zaydzuhri_stack_edu_python |
function parameterize fields values=none
begin
set fields = if expression is instance fields str then list fields else fields
set params = list comprehension dictionary zip fields vals for vals in values
function decorate cls
begin
set test_cls_module = __dict__
for tuple i values in enumerate params
begin
set test_cls... | def parameterize(fields, values=None):
fields = [fields] if isinstance(fields, str) else fields
params = [dict(zip(fields, vals)) for vals in values]
def decorate(cls):
test_cls_module = sys.modules[cls.__module__].__dict__
for i, values in enumerate(params):
test_cls = dict(cls... | Python | nomic_cornstack_python_v1 |
import cv2
function nothing x
begin
pass
end function
comment cria janela de trackbars
call namedWindow string trackbars
call createTrackbar string x string trackbars 0 800 nothing
call createTrackbar string y string trackbars 0 800 nothing
call createTrackbar string w string trackbars 100 800 nothing
call createTrackb... | import cv2
def nothing(x):
pass
#cria janela de trackbars
cv2.namedWindow("trackbars")
cv2.createTrackbar("x","trackbars",0,800,nothing)
cv2.createTrackbar("y","trackbars",0,800,nothing)
cv2.createTrackbar("w","trackbars",100,800,nothing)
cv2.createTrackbar("h","trackbars",100,800,nothing)
#Captura... | Python | zaydzuhri_stack_edu_python |
comment instance of hybrid vehicle optimization problem,
comment exercise 4.65 in Boyd & Vandenberghe, Convex Optimization
comment fuel use is given by F(p) = p+ gamma*p^2 (for p>=0)
import numpy as np
import matplotlib.pyplot as plt
comment define Preq, required power at wheels
comment Preq is piecewise linear
comment... | # instance of hybrid vehicle optimization problem,
# exercise 4.65 in Boyd & Vandenberghe, Convex Optimization
# fuel use is given by F(p) = p+ gamma*p^2 (for p>=0)
import numpy as np
import matplotlib.pyplot as plt
# define Preq, required power at wheels
# Preq is piecewise linear
# a is slope of each piece
#a=np.a... | Python | zaydzuhri_stack_edu_python |
function get_kinematic_mask particle_types
begin
return call equal particle_types KINEMATIC_PARTICLE_ID
end function | def get_kinematic_mask(particle_types):
return tf.equal(particle_types, KINEMATIC_PARTICLE_ID) | Python | nomic_cornstack_python_v1 |
from DummyStorage import DummyStorage , ensurePathExists , fileHash
from boto import s3
from django.conf import settings
import os
class S3Storage extends DummyStorage
begin
function __init__ self
begin
set connection = call Connection aws_access_key_id=AWS_ACCESS_KEY_ID aws_secret_access_key=AWS_SECRET_ACCESS_KEY
set ... | from .DummyStorage import DummyStorage, ensurePathExists, fileHash
from boto import s3
from django.conf import settings
import os
class S3Storage(DummyStorage):
def __init__(self):
self.connection = s3.Connection(
aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
aws_secret_access_key=... | Python | zaydzuhri_stack_edu_python |
function new_data self base first last
begin
set ohlcv = call get_data base first last
set fdf = call get_data base first last
set tdf = call get_data base first last
if tdf is none or empty
begin
return none
end
set pred = call predict_batch base fdf
set pdf = call DataFrame data=pred index=index columns=keys self
set... | def new_data(self, base: str, first: pd.Timestamp, last: pd.Timestamp):
ohlcv = self.predictor.ohlcv.get_data(base, first, last)
fdf = self.predictor.features.get_data(base, first, last)
tdf = self.predictor.targets.get_data(base, first, last)
if (tdf is None) or tdf.empty:
r... | Python | nomic_cornstack_python_v1 |
function create_base_random_list self
begin
set random_list = list
for i in range integer mountain_frq * PRECISION
begin
append random_list MOUNTAIN
end
for i in range integer field_frq * PRECISION
begin
append random_list FIELD
end
for i in range integer hill_frq * PRECISION
begin
append random_list HILL
end
for i in... | def create_base_random_list(self) -> List[TerrainType]:
random_list = []
for i in range(int(self.mountain_frq * PRECISION)):
random_list.append(TerrainType.MOUNTAIN)
for i in range(int(self.field_frq * PRECISION)):
random_list.append(TerrainType.FIELD)
for i in... | Python | nomic_cornstack_python_v1 |
function get_first_and_last input_string
begin
return tuple input_string at slice 0 : 10 : input_string at slice - 10 : :
end function | def get_first_and_last(input_string):
return input_string[0: 10], input_string[-10:] | Python | nomic_cornstack_python_v1 |
function last_result self
begin
if _res is none
begin
return call ValueError string Please run fit first
end
return best_fit
end function | def last_result(self):
if self._res is None:
return ValueError("Please run fit first")
return self._res.best_fit | Python | nomic_cornstack_python_v1 |
comment Sum Square Difference
function square_sum_diff n=100
begin
set tuple sum square_sum diff = tuple 0 0 0
for i in range n + 1
begin
set sum = sum + i ^ 2
set square_sum = square_sum + i
end
set square_sum = square_sum ^ 2
set diff = square_sum - sum
return diff
end function
print call square_sum_diff | # Sum Square Difference
def square_sum_diff(n=100):
sum, square_sum, diff = 0, 0, 0
for i in range(n + 1):
sum += i**2
square_sum += i
square_sum **= 2
diff = square_sum - sum
return diff
print(square_sum_diff())
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import scipy.constants as const
import scipy.fftpack as ft
from numpy import linalg as LA
import time
comment %% define grid and build kinetic energy and momentum operator
set hbar = 1
set m = 1
set Ngrid = 10... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import scipy.constants as const
import scipy.fftpack as ft
from numpy import linalg as LA
import time
#%% define grid and build kinetic energy and momentum operator
hbar = 1
m = 1
Ngrid = 1001
xmin = -10
xmax = 10
xvec... | Python | zaydzuhri_stack_edu_python |
function run self
begin
set config_path = config
set editor = call getenv string EDITOR call getenv string VISUAL none
if not editor
begin
raise call RuntimeError string EDITOR or VISUAL environment variable not defined
end
debug string Opening { config_path }
debug string Editor: { editor }
run list editor config_path... | def run(self: ConfigEditApp) -> None:
config_path = path[self.site_name].config
editor = os.getenv('EDITOR', os.getenv('VISUAL', None))
if not editor:
raise RuntimeError('EDITOR or VISUAL environment variable not defined')
log.debug(f'Opening {config_path}')
log.deb... | Python | nomic_cornstack_python_v1 |
function setScreenMode self size=none
begin
if not size
begin
if fullscreen
begin
set size = list current_w current_h
end
else
begin
set size = list 2 * current_w // 3 2 * current_h // 3
end
end
if fullscreen
begin
set screen = call set_mode size FULLSCREEN
end
else
begin
set screen = call set_mode size RESIZABLE
end
e... | def setScreenMode(self, size=None):
if not size:
if self.fullscreen:
size = [self.info.current_w, self.info.current_h]
else:
size = [2 * self.info.current_w // 3, 2 * self.info.current_h // 3]
if self.fullscreen:
self.screen = pygame.di... | Python | nomic_cornstack_python_v1 |
function latest_scan self
begin
return get pulumi self string latest_scan
end function | def latest_scan(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "latest_scan") | Python | nomic_cornstack_python_v1 |
function get_scenario self scenario_id
begin
return call DSSScenario client project_key scenario_id
end function | def get_scenario(self, scenario_id):
return DSSScenario(self.client, self.project_key, scenario_id) | Python | nomic_cornstack_python_v1 |
comment punctul a
print string Suma primelor 3 componente a variabilei x este x at 0 + x at 1 + x at 2
comment puntul b
print string Suma tuturor coponentelor variabilei y este sum y
comment punctul c
print string Produsul tuturor componentelor variabile x este x at 0 * x at 1 * x at 2 * x at 3 * x at 4
comment punctul... | #punctul a
print("Suma primelor 3 componente a variabilei x este ",x[0]+x[1]+x[2])
#puntul b
print("Suma tuturor coponentelor variabilei y este ",sum(y))
#punctul c
print("Produsul tuturor componentelor variabile x este ",x[0]*x[1]*x[2]*x[3]*x[4])
#punctul d
print("Valoarea absoluta a componentei a 3 a variabile... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import unittest
from datetime import datetime
from dateutil.relativedelta import relativedelta
from pymongo.database import CollectionInvalid
from mock import Mock , patch
from api import core , utils
class BaseMongoTestCase extends TestCase
begin
function setUp self
begin
set client = call... | #!/usr/bin/env python
import unittest
from datetime import datetime
from dateutil.relativedelta import relativedelta
from pymongo.database import CollectionInvalid
from mock import Mock, patch
from api import core, utils
class BaseMongoTestCase(unittest.TestCase):
def setUp(self):
client = utils._get... | Python | zaydzuhri_stack_edu_python |
class Employee extends object
begin
set emp_raise = 1.02
string Initializes the object with these variables, attributes
function __init__ self firstname lastname id salary
begin
set firstname = firstname
set lastname = lastname
set id = id
set salary = salary
set email = lower format string {0}.{1}@example.com firstnam... | class Employee(object):
emp_raise = 1.02
"""
Initializes the object with these variables, attributes
"""
def __init__(self, firstname, lastname, id, salary):
self.firstname = firstname
self.lastname = lastname
self.id = id
self.salary = salary
self.email = "{0}.{1}@example.com".format(firstname, lastna... | Python | zaydzuhri_stack_edu_python |
from sqlalchemy import Column , ForeignKey , Integer , String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
set Base = call declarative_base
class User extends Base
begin
set __tablename__ = string user
set id = call Column Integer p... | from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name =... | Python | zaydzuhri_stack_edu_python |
comment Conversor de temperaturas: escreva um programa que converta uma temperatura digitada em ºC para ºF
set celsius = decimal input string Digite a temperatura em Celsius:
set farenheit = 1.8 * celsius + 32
print string { celsius } ºC correspondem a { farenheit } ºF. | # Conversor de temperaturas: escreva um programa que converta uma temperatura digitada em ºC para ºF
celsius = float(input("Digite a temperatura em Celsius: \n"))
farenheit = ((1.8 * celsius) + 32)
print(f"{celsius}ºC correspondem a {farenheit:.1f}ºF.") | Python | zaydzuhri_stack_edu_python |
function create_players self num_players
begin
set list_players = list
for num in range num_players
begin
set name = input format string Enter your name player {player_num}: player_num=num
append list_players call Player name
end
set list_players = list_players
return list_players
end function | def create_players(self, num_players):
list_players = []
for num in range(num_players):
name = input("Enter your name player {player_num}: ".format(player_num = num))
list_players.append(Player(name))
self.list_players = list_players
return list_players | Python | nomic_cornstack_python_v1 |
function __init__ self print_indexed_cb=print_fortran_indexed openmp=true default_type=string real heap_interm=true explicit_bounds=false **kwargs
begin
if openmp
begin
set add_templ = dict string term_prelude _FORTRAN_OMP_TERM_PRELUDE ; string term_finale _FORTRAN_OMP_TERM_FINALE
end
else
begin
set add_templ = none
en... | def __init__(
self, print_indexed_cb=print_fortran_indexed, openmp=True,
default_type='real', heap_interm=True, explicit_bounds=False,
**kwargs
):
if openmp:
add_templ = {
'term_prelude': _FORTRAN_OMP_TERM_PRELUDE,
'term_finale... | Python | nomic_cornstack_python_v1 |
function __finalize self
begin
if act2_data at string mfg_session_id == act2_data at string mfg_end_session_id
begin
debug format string ACT2 Mfg Session ENDED ({0}) act2_data at string mfg_end_session_id
if exists path act2_mfg_session_file
begin
debug string Removing session file.
set result = call shellcmd format st... | def __finalize(self):
if self.act2_data['mfg_session_id'] == self.act2_data['mfg_end_session_id']:
log.debug("ACT2 Mfg Session ENDED ({0})".format(self.act2_data['mfg_end_session_id']))
if os.path.exists(self.act2_mfg_session_file):
log.debug("Removing session file.")
... | 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.