code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Name: Ahsan Khan
comment Date: 09/26/20
comment Description: Use a dictionary to store information of anyone, and print each value on the screen
set my_info = dict string first_name string ahsan ; string last_name string khan ; string age 20 ; string city string new york
comment print(my_info)
print string Firs... | # Name: Ahsan Khan
# Date: 09/26/20
# Description: Use a dictionary to store information of anyone, and print each value on the screen
my_info = {
'first_name':'ahsan',
'last_name':'khan',
'age':20,
'city':'new york',
}
#print(my_info)
print(f"First Name: {my_info['first_name'].title()}")
print(f"Las... | Python | zaydzuhri_stack_edu_python |
import os
class Utils
begin
string Class to store util functions
function __init__ self
begin
string Defines the allowed archive extensions and their extraction methods
set allowed_archive_exts = list string .tar.gz string .tgz
set file_extract_methods = dict string .tar.gz string tar xvf ; string .tgz string tar xvf
e... | import os
class Utils:
"""
Class to store util functions
"""
def __init__(self):
"""
Defines the allowed archive extensions and their extraction methods
"""
self.allowed_archive_exts = [".tar.gz", ".tgz"]
self.file_extract_methods = {".tar.gz": "tar xvf ",
... | Python | zaydzuhri_stack_edu_python |
function _register_dataparser self plugin_name plugin_instance
begin
string Register a parser. :param plugin_name: Parser name :param plugin_instance: PluginBase :return: Nothing
for parser in keys call get_parsers
begin
if call has_parser parser
begin
raise call PluginException format string Parser {} already register... | def _register_dataparser(self, plugin_name, plugin_instance):
"""
Register a parser.
:param plugin_name: Parser name
:param plugin_instance: PluginBase
:return: Nothing
"""
for parser in plugin_instance.get_parsers().keys():
if self.responseparser.has... | Python | jtatman_500k |
function _gen_random_dataframe size=150 freq=string B
begin
set dates = call date_range string 2011-04-23 periods=size freq=freq
set name = string date
set X = cumulative sum np randn size
set Y = 2.0 + cumulative sum np randn size * 0.75
set Z = random integer - 3 4 size
return call DataFrame dict string X X ; string ... | def _gen_random_dataframe(size=150, freq='B'):
dates = pd.date_range('2011-04-23', periods=size, freq=freq)
dates.name = "date"
X = np.cumsum(np.random.randn(size))
Y = 2. + np.cumsum(np.random.randn(size)) * 0.75
Z = np.random.randint(-3, 4, size)
return pd.DataFrame({'X': X,
... | Python | nomic_cornstack_python_v1 |
if s at 0 at 0 == s at 1 at 0
begin
set now = 1
set ans = 3
set v = true
end
else
begin
set now = 2
set ans = 6
set v = false
end
while now < n
begin
if s at 0 at now == s at 1 at now and v
begin
comment タテ タテ
set ans = ans * 2 % mod
set now = now + 1
set v = true
end
else
if s at 0 at now == s at 1 at now
begin
commen... | if s[0][0] == s[1][0]:
now = 1
ans = 3
v = True
else:
now = 2
ans = 6
v = False
while now < n:
if s[0][now] == s[1][now] and v:
# タテ タテ
ans = (ans*2)%mod
now+=1
v = True
elif s[0][now] == s[1][now]:
# ヨコ タテ
ans = (ans*1)%mod
now+=1... | Python | zaydzuhri_stack_edu_python |
if liczba % 2 == 0
begin
print string Parzysta
end
else
begin
print string Nieparzysta
end
print string Dobranoc! | if liczba % 2 == 0:
print("Parzysta")
else:
print("Nieparzysta")
print("Dobranoc!")
| Python | zaydzuhri_stack_edu_python |
from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
from msrest.authentication import CognitiveServicesCredentials
import sentiment_analysis.config as config
import itertools
import pprint
import re
import jsonpickle
set credentials = call CognitiveServicesCredentials key
set client = call Te... | from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
from msrest.authentication import CognitiveServicesCredentials
import sentiment_analysis.config as config
import itertools
import pprint
import re
import jsonpickle
credentials = CognitiveServicesCredentials(config.key)
client = TextAnalyt... | Python | zaydzuhri_stack_edu_python |
function slide_value_temp self
begin
return call value
end function | def slide_value_temp(self):
return self.horizontalSliderTemp.value() | Python | nomic_cornstack_python_v1 |
function update_match_settings self
begin
call setCurrentText get overall_config MATCH_CONFIGURATION_HEADER GAME_MODE
call setCurrentText get overall_config MATCH_CONFIGURATION_HEADER GAME_MAP
call setChecked call getboolean MATCH_CONFIGURATION_HEADER SKIP_REPLAYS
call setChecked call getboolean MATCH_CONFIGURATION_HEA... | def update_match_settings(self):
self.mode_type_combobox.setCurrentText(self.overall_config.get(MATCH_CONFIGURATION_HEADER, GAME_MODE))
self.map_type_combobox.setCurrentText(self.overall_config.get(MATCH_CONFIGURATION_HEADER, GAME_MAP))
self.skip_replays_checkbox.setChecked(self.overall_config.g... | Python | nomic_cornstack_python_v1 |
function artist_detail request artist_id
begin
return call object_detail request queryset=all object_id=artist_id template_object_name=string artist
end function | def artist_detail(request, artist_id):
return object_detail(request,
queryset = Artist.objects.all(),
object_id = artist_id,
template_object_name="artist"
) | Python | nomic_cornstack_python_v1 |
import json
set withcoord = 0
set withoutcoord = 0
for line in open string data/stream_GSTForNewIndia.json
begin
set ob = loads line
set coords = get ob string coordinates 0
end | import json
withcoord = withoutcoord = 0
for line in open("data/stream_GSTForNewIndia.json"):
ob = json.loads(line)
coords = ob.get("coordinates", 0) | Python | zaydzuhri_stack_edu_python |
function printHelp
begin
print string League Replay Analyzer v1.0
print string Usage: main.py <gameID> [OPTIONS <optional_arguments>]
print string Options:
print string -t | -T | --tilt tilt-related stats (mute stats, surrender votes, AFKs etc)
print string -i | -I | --items item related stats (build, wards, consumable... | def printHelp():
print("League Replay Analyzer v1.0")
print("Usage: main.py <gameID> [OPTIONS <optional_arguments>]")
print("Options:")
print("-t | -T | --tilt tilt-related stats (mute stats, surrender votes, AFKs etc)")
print("-i | -I | --items item related st... | Python | nomic_cornstack_python_v1 |
function calculateTotalCost items
begin
set total_cost = 0
for item in items
begin
set total_cost = total_cost + item at 1
end
return total_cost
end function
comment Usage
set total_cost = call calculateTotalCost items
print total_cost | def calculateTotalCost(items):
total_cost = 0
for item in items:
total_cost += item[1]
return total_cost
# Usage
total_cost = calculateTotalCost(items)
print(total_cost) | Python | iamtarun_python_18k_alpaca |
import random
class Histogram
begin
function __init__ self source_text
begin
set totalCount = 0
set histDict = call makeHistogram source_text
end function
function makeHistogram source_text
begin
set hist_dict = dict
set doc = open source_text
set lines = read lines doc
for line in lines
begin
for word in split line s... | import random
class Histogram:
def __init__(self, source_text):
self.totalCount = 0
self.histDict = self.makeHistogram(source_text)
def makeHistogram(source_text):
hist_dict = {}
doc = open(source_text)
lines = doc.readlines()
for line in lines:
fo... | Python | zaydzuhri_stack_edu_python |
from multiply import multiply
from divide import divide
from add import add
from subtract import subtract
import sys
if __name__ == string __main__
begin
print string 1. multiply
print string 2. divide
print string 3. subtract
print string 4. add
set a = integer argv at 1
set x = integer argv at 2
set y = integer argv ... | from multiply import multiply
from divide import divide
from add import add
from subtract import subtract
import sys
if __name__ == '__main__':
print("1. multiply")
print("2. divide")
print("3. subtract")
print("4. add")
a=int(sys.argv[1])
x=int(sys.argv[2])
y=int(sys.argv[3])
if (a==1) :
print(multiply(... | Python | zaydzuhri_stack_edu_python |
comment !--encoding=utf-8--
comment 请按照 [题目id]\[flag] 的格式提交
comment 如challenge_id为1,flag为flag{123-123}则attack函数返回 "1\flag{123-123}"
from yaml import safe_load
import submitters
import re
import requests
import time
class CTFdSubmitter extends Submitter
begin
set nonce_re = compile string var csrf_nonce = "(.*)"
set non... | #!--encoding=utf-8--
# 请按照 [题目id]\[flag] 的格式提交
# 如challenge_id为1,flag为flag{123-123}则attack函数返回 "1\flag{123-123}"
from yaml import safe_load
import submitters
import re
import requests
import time
class CTFdSubmitter(submitters.Submitter):
nonce_re = re.compile(r'var csrf_nonce = "(.*)"')
nonce_new = re.compi... | Python | zaydzuhri_stack_edu_python |
import unittest
from factorial import facto
class test_facto extends TestCase
begin
function test_negative self
begin
assert equal string Factorial cannot be computed for negative numbers call facto - 5
end function
function test_zero self
begin
assert equal 1 call facto 0
end function
function test_one self
begin
asse... | import unittest
from factorial import facto
class test_facto(unittest.TestCase):
def test_negative(self):
self.assertEqual('Factorial cannot be computed for negative numbers', facto(-5))
def test_zero(self):
self.assertEqual(1, facto(0))
def test_one(self):
self... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import os
import matplotlib.pyplot as plt
import math
import seaborn as sns
import pandas as pd
from collections import Counter
set path_videogames = join path get current directory string datasets string vgsales.csv
set videogames = read csv path_videogames delimiter=string ,
function get_vgs_propor... | import numpy as np
import os
import matplotlib.pyplot as plt
import math
import seaborn as sns
import pandas as pd
from collections import Counter
path_videogames = os.path.join(os.getcwd(), 'datasets', 'vgsales.csv')
videogames = pd.read_csv(path_videogames, delimiter = ',')
def get_vgs_proportion():
#Proportion... | Python | zaydzuhri_stack_edu_python |
function dist lst n
begin
if length lst == 0
begin
return list
end
return list tuple lst at 0 n + call dist lst at slice 1 : : n
end function
print call dist list 3 | def dist(lst, n):
if len(lst) == 0: return []
return [(lst[0],n)] + dist(lst[1:],n)
print(dist([],3)) | Python | zaydzuhri_stack_edu_python |
import pymysql
class DBConnect
begin
function __init__ self
begin
set conn = call connect host=string localhost user=string root password=string root db=string moon charset=string utf8mb4
set curs = call cursor DictCursor
end function
function select_list self
begin
set ret = list
try
begin
set sql = string select tex... | import pymysql
class DBConnect:
def __init__(self):
self.conn = pymysql.connect(host='localhost', user='root', password='root', db='moon', charset='utf8mb4')
self.curs = self.conn.cursor(pymysql.cursors.DictCursor)
def select_list(self):
ret = []
try:
sql = """selec... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import streamlit as st
import tensorflow as tf
from PIL import Image , ImageOps
function import_and_predict image_data model
begin
set size = tuple 32 32
set image = fit ImageOps image_data size
comment image = image.convert('RGB')
set image = call asarray image
set image = as type image float32 / 25... | import numpy as np
import streamlit as st
import tensorflow as tf
from PIL import Image, ImageOps
def import_and_predict(image_data, model):
size = (32,32)
image = ImageOps.fit(image_data, size)
#image = image.convert('RGB')
image = np.asarray(image)
image = ... | Python | zaydzuhri_stack_edu_python |
function name self
begin
set description = description
if description is not none and length description > 0
begin
return string { name } { description }
end
return name
end function | def name(self) -> str | UndefinedType | None:
description = self._analog_output_cluster_handler.description
if description is not None and len(description) > 0:
return f"{super().name} {description}"
return super().name | Python | nomic_cornstack_python_v1 |
function _get_grid_rows entities schema
begin
set rows = list
for entity in entities
begin
set obj = dict
for field in list_fields
begin
set value = get attribute entity field
if value is none
begin
set value = string
end
else
if is instance value WKBElement
begin
set value = string Geometry
end
else
begin
set value... | def _get_grid_rows(entities, schema):
rows = []
for entity in entities:
obj = {}
for field in schema.list_fields:
value = getattr(entity, field)
if value is None:
value = ''
else:
if isinstance(value, WKBElement):
... | Python | nomic_cornstack_python_v1 |
function formatExactiveList unformatted
begin
set data = list
set inclist = list
comment remove unwanted special characters
set unformatted = replace unformatted string ² string 2
set unformatted = replace unformatted string string -
comment allow splitting for tune file
set lines = split replace unformatted string... | def formatExactiveList(unformatted):
data = []
inclist = []
# remove unwanted special characters
unformatted = unformatted.replace('\xb2', '2')
unformatted = unformatted.replace('\x97', '-')
# allow splitting for tune file
lines = unformatted.replace('Tunefile', 'Tunefile ').split('\r\n')
... | Python | nomic_cornstack_python_v1 |
function final
begin
if DEBUG
begin
print string Cleaning up message queues queues
print string Cleaning up processes procs
end
for q in queues
begin
remove q
end
for proc in procs
begin
terminate proc
end
end function | def final():
if DEBUG:
print("Cleaning up message queues", queues)
print("Cleaning up processes", procs)
for q in queues:
q.remove()
for proc in procs:
proc.terminate() | Python | nomic_cornstack_python_v1 |
function _get_subnet_cached self context subnet_id
begin
if subnet_id not in subnet_cache
begin
set subnet = call get_subnet context subnet_id
set subnet_cache at subnet_id = subnet
end
return subnet_cache at subnet_id
end function | def _get_subnet_cached(self, context, subnet_id):
if subnet_id not in self.subnet_cache:
subnet = self.plugin.db._core_plugin.get_subnet(
context,
subnet_id
)
self.subnet_cache[subnet_id] = subnet
return self.subnet_cache[subnet_id] | Python | nomic_cornstack_python_v1 |
from scipy.optimize import curve_fit
import numpy as np
comment this is your 'straight line' y=f(x)
function f x A B
begin
return A * x + B
end function
set x = list 1 2 3
set y = list 4 5 6
comment your data x, y to fit
set tuple A B = curve fit f x y at 0
print A B
set y = array x * A + B
print y | from scipy.optimize import curve_fit
import numpy as np
def f(x, A, B): # this is your 'straight line' y=f(x)
return A*x + B
x=[1,2,3]
y=[4,5,6]
A,B = curve_fit(f, x, y)[0] # your data x, y to fit
print(A,B)
y =np.array(x)*A + B
print(y)
| Python | zaydzuhri_stack_edu_python |
function get_symbol num
begin
set symbol = string
if num == 1
begin
set symbol = string X
end
else
if num == - 1
begin
set symbol = string O
end
return symbol
end function | def get_symbol(num):
symbol = ' '
if num == 1:
symbol = 'X'
elif num == -1:
symbol = 'O'
return symbol | Python | nomic_cornstack_python_v1 |
class Duration
begin
function __init__ self weeks days hours
begin
if type weeks is not int
begin
raise call TypeError string Cannot instantiate an object with non-int values.
end
if weeks < 0
begin
raise call ValueError string Values cannot be negative.
end
if type days is not int
begin
raise call TypeError string Can... | class Duration:
def __init__(self, weeks, days, hours):
if type(weeks) is not int:
raise TypeError("Cannot instantiate an object with non-int values.")
if weeks < 0:
raise ValueError("Values cannot be negative.")
if type(days) is not int:
raise Type... | Python | zaydzuhri_stack_edu_python |
function parameter name **kwargs
begin
function decorator func
begin
if has attribute func string parameter
begin
set parameter at name = kwargs
end
else
begin
set parameter = dict name kwargs
end
return func
end function
return decorator
end function | def parameter(name, **kwargs):
def decorator(func):
if hasattr(func, 'parameter'):
func.parameter[name] = kwargs
else:
func.parameter = {name: kwargs}
return func
return decorator | Python | nomic_cornstack_python_v1 |
function getNeighbors self cell mc=false
begin
comment cells in same sub-grid as 'cell'
set subGrid = call getSubGrid cell at 0 cell at 1
comment cells in same column as 'cell'
set column = set list comprehension tuple row cell at 1 for row in range _n
comment cells in same row as 'cell'
set row = set list comprehensio... | def getNeighbors(self, cell, mc = False):
# cells in same sub-grid as 'cell'
subGrid = self.getSubGrid(cell[0], cell[1])
# cells in same column as 'cell'
column = set([(row, cell[1]) for row in range(self._n)])
# cells in same row as 'cell'
row = set([(cell[0], col) for c... | Python | nomic_cornstack_python_v1 |
function _set_LY ds first=1 dim=string lead
begin
return call assign dict dim array range first first + size
end function | def _set_LY(ds, first=1, dim='lead'):
return ds.assign({dim: np.arange(first, first + ds[dim].size)}) | Python | nomic_cornstack_python_v1 |
function load_bundle_files self bundle_dir
begin
comment pragma: no cover
pass
end function | def load_bundle_files(self, bundle_dir):
pass # pragma: no cover | Python | nomic_cornstack_python_v1 |
from import db
from containers import Containers
import datetime
class Readings extends Model
begin
string Readings model for readings
set __tablename__ = string readings
set id = call Column Integer primary_key=true autoincrement=true
set container_id = call Column Integer call ForeignKey id nullable=false
set weight... | from .. import db
from .containers import Containers
import datetime
class Readings(db.Model):
"""
Readings model for readings
"""
__tablename__ = 'readings'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
container_id = db.Column(db.Integer, db.ForeignKey(Containers.id), nul... | Python | zaydzuhri_stack_edu_python |
import math
import random
import threading
import time
from modules.configuration import bcolors
from modules import colorutils
from PIL import Image , ImageDraw , ImageEnhance , ImageFont , ImageOps
string config.percentage will be the global config variable for display of progress
function reDraw
begin
string BOX AND... | import math
import random
import threading
import time
from modules.configuration import bcolors
from modules import colorutils
from PIL import Image, ImageDraw, ImageEnhance, ImageFont, ImageOps
"""
config.percentage will be the global config variable for display of progress
"""
def reDraw():
"""""" """""" """"... | Python | zaydzuhri_stack_edu_python |
function _upgrade_chunk_info chunk_info improved_chunk_info
begin
for tuple key improved_info in items improved_chunk_info
begin
set original_info = get chunk_info key improved_info
if improved_info at string shape at slice 1 : : != original_info at string shape at slice 1 : :
begin
raise call ValueError format str... | def _upgrade_chunk_info(chunk_info, improved_chunk_info):
for key, improved_info in improved_chunk_info.items():
original_info = chunk_info.get(key, improved_info)
if improved_info['shape'][1:] != original_info['shape'][1:]:
raise ValueError("Original '{}' array has shape {} while improv... | Python | nomic_cornstack_python_v1 |
function main argv
begin
call correct_font *argv[1:]
end function | def main(argv):
correct_font(*argv[1:]) | Python | nomic_cornstack_python_v1 |
import math
set kg = decimal input
set x = integer input
set y = integer input
set total = kg / 5
set b1 = total / 0.535
set kasNum = b1 / y
set total1 = floor total
print format string Total lutenica: {} kilograms. total1
if x > kasNum
begin
set diff = x - kasNum
print format string {} more boxes needed. floor diff
pr... | import math
kg = float(input())
x = int(input())
y = int(input())
total = kg / 5
b1 = total / 0.535
kasNum = b1 / y
total1=math.floor(total)
print("Total lutenica: {} kilograms.".format(total1))
if x > kasNum:
diff = x - kasNum
print("{} more boxes needed.".format(math.floor(diff)))
print("{} more jars need... | Python | zaydzuhri_stack_edu_python |
from PIL import Image , ImageDraw
import numpy as np
function DrawObservation obs width height
begin
set tuple field bot = obs
set tuple nrRows nrColumns = tuple shape at 0 shape at 1
set cellWidth = width / nrColumns
set cellHeight = height / nrRows
set botWidth = 0.25 / nrColumns
set botHeight = 0.25 / nrRows
set im ... | from PIL import Image, ImageDraw
import numpy as np
def DrawObservation(obs, width, height):
field, bot = obs
nrRows, nrColumns = field.shape[0], field.shape[1]
cellWidth = width / nrColumns
cellHeight = height / nrRows
botWidth = 0.25 / nrColumns
botHeight = 0.25 / nrRows
im = Image.new(... | Python | zaydzuhri_stack_edu_python |
function petsc_manager
begin
return call PetscManager
end function | def petsc_manager():
return PetscManager() | Python | nomic_cornstack_python_v1 |
import csv
from collections import Counter
with open string height.csv as f
begin
set data = reader f
set filedata = list data
end
pop filedata 0
set newdata = list
for i in range length filedata
begin
set num = filedata at i at 2
append newdata decimal num
end
print newdata
set n = length newdata
set total = 0
for x ... | import csv
from collections import Counter
with open('height.csv') as f:
data = csv.reader(f)
filedata = list(data)
filedata.pop(0)
newdata = []
for i in range(len(filedata)):
num = filedata[i][2]
newdata.append(float(num))
print(newdata)
n = len(newdata)
total = 0
for x in newdata:
... | Python | zaydzuhri_stack_edu_python |
function required_data_connectors self
begin
return get pulumi self string required_data_connectors
end function | def required_data_connectors(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['SecurityMLAnalyticsSettingsDataSourceArgs']]]]:
return pulumi.get(self, "required_data_connectors") | Python | nomic_cornstack_python_v1 |
function install
begin
if not call installed
begin
call sudo string pacman -S nginx --noconfirm
end
if call status
begin
print string nginx is already running.
end
else
begin
print string nginx is not running.
call initializer
start
end
end function | def install():
if not installed():
sudo('pacman -S nginx --noconfirm')
if status():
print('nginx is already running.')
else:
print('nginx is not running.')
initializer()
start() | Python | nomic_cornstack_python_v1 |
import pika
import threading
import time
import sys
set id_client = none
class HandShake extends Thread
begin
function __init__ self
begin
call __init__ self
end function
function run self
begin
set connected = 0
while connected == 0
begin
try
begin
set connection = call BlockingConnection call ConnectionParameters str... | import pika
import threading
import time
import sys
id_client = None
class HandShake(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self.connected = 0
while(self.connected == 0):
try:
self.connection = pika.BlockingCon... | Python | zaydzuhri_stack_edu_python |
function wait_for_answers socket wait_time msg_id
begin
set remaining = wait_time
set start = time
while poll socket remaining == POLLIN
begin
set msg = call recv_json
if msg at string header at string msg_id == msg_id
begin
yield msg
end
else
begin
error string unexpected msg_id: got %s but expected %s % tuple msg at ... | def wait_for_answers(socket, wait_time, msg_id):
remaining = wait_time
start = time.time()
while socket.poll(remaining) == zmq.POLLIN:
msg = socket.recv_json()
if msg['header']['msg_id'] == msg_id:
yield msg
else:
logging.error('unexpected msg_id: got %s but e... | Python | nomic_cornstack_python_v1 |
comment @lc app=leetcode.cn id=6 lang=python3
comment [6] Z 字形变换
class Solution
begin
function convert self s numRows
begin
if numRows == 1 or numRows >= length s
begin
return s
end
comment z前半个(|/)个数两行减2
set p = 2 * numRows - 1
set result = list string * numRows
for i in range length s
begin
comment 一个形状轮回的位置
set flo... | #
# @lc app=leetcode.cn id=6 lang=python3
#
# [6] Z 字形变换
#
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1 or numRows >= len(s):
return s
# z前半个(|/)个数两行减2
p = 2 * (numRows - 1)
result = [""] * numRows
for i in range(len(s)):
... | Python | zaydzuhri_stack_edu_python |
if avg >= 5
begin
if attendance >= 0.8
begin
print string Congratulations you've passed the exam
end
else
begin
print string Sorry you've failed, due to attendence rate lower than 80%
end
end
else
if attendance >= 0.8
begin
print string Sorry you've failed, due to avg lower than 5
end
else
begin
print string Sorry you'... | if (avg >= 5):
if (attendance >= 0.8):
print("Congratulations you've passed the exam")
else:
print("Sorry you've failed, due to attendence rate lower than 80%")
elif (attendance >= 0.8):
print("Sorry you've failed, due to avg lower than 5")
else:
print("Sorry you've failed, due to at... | Python | zaydzuhri_stack_edu_python |
function register_temperature_changed_callback self callback=none
begin
return call register_temperature_changed_callback callback=callback
end function | def register_temperature_changed_callback(self, callback=None):
return self._arm.register_temperature_changed_callback(callback=callback) | Python | nomic_cornstack_python_v1 |
function index self req
begin
set items = call _get_flavors req is_detail=false
return dictionary flavors=items
end function | def index(self, req):
items = self._get_flavors(req, is_detail=False)
return dict(flavors=items) | Python | nomic_cornstack_python_v1 |
for i in range 2 N + 1
begin
append kai1 kai1 at - 1 * i % MOD
append inverse - inverse at MOD % i * MOD // i % MOD
append kai2 kai2 at - 1 * inverse at - 1 % MOD
end
function comb n r
begin
if r < 0 or r > n
begin
return 0
end
set r = min r n - r
return kai1 at n * kai2 at r * kai2 at n - r % MOD
end function
if K >= ... | for i in range(2, N + 1):
kai1.append((kai1[-1] * i) % MOD)
inverse.append((-inverse[MOD % i] * (MOD // i)) % MOD)
kai2.append((kai2[-1] * inverse[-1]) % MOD)
def comb(n, r):
if r < 0 or r > n:
return 0
r = min(r, n - r)
return (kai1[n] * kai2[r] * kai2[n - r]) % MOD
if K >= 2:
A.sort(reverse = True... | Python | zaydzuhri_stack_edu_python |
from math import floor
while true
begin
try
begin
set x = integer input
set inp = list
while length inp < x
begin
extend inp split input
end
set inp = list comprehension integer x for x in inp
set mediana = floor length inp / 2 + 1
set rangel = inp at slice : mediana :
set gugu = inp at slice mediana : :
set total... | from math import floor
while True:
try:
x = int(input())
inp = []
while len(inp) < x:
inp.extend(input().split())
inp = [int(x) for x in inp]
mediana = floor(len(inp)/2) + 1
rangel = inp[:mediana]
gugu = inp[mediana:]
total = s... | Python | zaydzuhri_stack_edu_python |
comment 구구단
comment N을 입력받은 뒤, 구구단 N단을 출력하는 프로그램을 작성하시오. 출력 형식에 맞춰서 출력하면 된다.
string num= int(input()) i=1 while i: print(num, "*", i, "=", num*i) i += 1 if i>9: break
set num = integer input
for i in range 1 10
begin
print num string * i string = num * i
end | # 구구단
# N을 입력받은 뒤, 구구단 N단을 출력하는 프로그램을 작성하시오. 출력 형식에 맞춰서 출력하면 된다.
'''
num= int(input())
i=1
while i:
print(num, "*", i, "=", num*i)
i += 1
if i>9: break
'''
num= int(input())
for i in range(1,10):
print(num, "*", i, "=", num*i)
| Python | zaydzuhri_stack_edu_python |
class Solution
begin
function reverse self x
begin
set str_x = string absolute x
set rev_x = integer str_x at slice : : - 1
if rev_x > 2 ^ 31 - 1
begin
return 0
end
if x < 0
begin
return rev_x * - 1
end
return rev_x
end function
end class | class Solution:
def reverse(self, x: int) -> int:
str_x = str(abs(x))
rev_x = int(str_x[::-1])
if rev_x > ((2**31)-1):
return 0
if x < 0:
return (rev_x*-1)
return rev_x
| Python | zaydzuhri_stack_edu_python |
function map_save_path_routine file_path
begin
if file_path == string ~/Desktop/vizcovidfr_files/
begin
set A = expand user path string ~
set B = string Desktop
set file_path = join path A B
end
if not exists path join path file_path string vizcovidfr_files
begin
make directory os join path file_path string vizcovidfr_... | def map_save_path_routine(file_path):
if (file_path == '~/Desktop/vizcovidfr_files/'):
A = os.path.expanduser("~")
B = "Desktop"
file_path = os.path.join(A, B)
if not os.path.exists(os.path.join(file_path, "vizcovidfr_files")):
os.mkdir(os.path.join(file_path, "vizcovidfr_files"... | Python | nomic_cornstack_python_v1 |
string Simple transform augmentations. - Author: Jongkuk Lim - Contact: lim.jeikei@gmail.com
import numpy as np
function jitter x sigma=0.1
begin
string Add a random jittering. Args: x: sensor data. sigma: amount of the noise. Returns: x + normal random with sigma STD.
set jitter_noise = call normal loc=0 scale=sigma s... | """Simple transform augmentations.
- Author: Jongkuk Lim
- Contact: lim.jeikei@gmail.com
"""
import numpy as np
def jitter(x: np.ndarray, sigma: float = 0.1) -> np.ndarray:
"""Add a random jittering.
Args:
x: sensor data.
sigma: amount of the noise.
Returns:
x + normal random ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[13]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
comment In[14]... | #!/usr/bin/env python
# coding: utf-8
# In[13]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
# In[14]:
#Retrieving the ... | Python | zaydzuhri_stack_edu_python |
comment Module allowing to read parameters from .cfg files
import configparser
from pprint import pprint
class CfgFileParser
begin
comment Read the LkdParse.cfg file to get parameters
set Config = dict
function file_reader self filename
begin
comment Open the file
set config = config parser
read config filename
commen... | # Module allowing to read parameters from .cfg files
import configparser
from pprint import pprint
class CfgFileParser:
# Read the LkdParse.cfg file to get parameters
Config = {}
def file_reader(self, filename):
# Open the file
config = configparser.ConfigParser()
config.read(fil... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Feb 26 18:33:59 2021 Codigo del metodo de Newton-Cotes de Trapecio para la aproximar la solucion del desplazamiento de un objeto @author: acraw
comment Tiempo inicial
set a = 0
comment Tiempo final
set b = 100
comment Numero de intervalos para realizar el calculo
set ... | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 26 18:33:59 2021
Codigo del metodo de Newton-Cotes de Trapecio para la aproximar la solucion del desplazamiento de un objeto
@author: acraw
"""
#Tiempo inicial
a=0
#Tiempo final
b=100
#Numero de intervalos para realizar el calculo
N=100
h=(b-a)/(N-1)
#Veloci... | Python | zaydzuhri_stack_edu_python |
from datetime import datetime
from struct import Struct
from import filesystem as fs
class Entry
begin
comment formato binario
set entry_namesize = 31
set entry_fmt = string entry_namesize + string s + string BIiiiH
set entry_struct = call Struct fmt_options + entry_fmt
set entry_filetypes = list string empty string d... | from datetime import datetime
from struct import Struct
from . import filesystem as fs
class Entry:
#formato binario
entry_namesize = 31
entry_fmt = str(entry_namesize)+'s' + 'BIiiiH'
entry_struct = Struct(fs.fmt_options + entry_fmt)
entry_filetypes = ['empty', 'dir', 'file']
def __init__(self, pos, new=Fals... | Python | zaydzuhri_stack_edu_python |
function simulator self rotors_settings=tuple 1 2 3 string A string A string A plugboard_settings=none plain_text=string
begin
call clear_screen
set user_label = call Label root text=string Hello + username font=title_font bg=bg_color height=2
grid pady=10 padx=50 row=0 column=11 columnspan=5
if plain_text == string
b... | def simulator(self, rotors_settings=(1, 2, 3, 'A', 'A', 'A'),
plugboard_settings=None, plain_text=""):
self.clear_screen()
user_label = Label(self.root, text="Hello " + self.username,
font=self.title_font, bg=self.bg_color, height=2)
user_label.g... | Python | nomic_cornstack_python_v1 |
from import *
import ipaddress
class IsEmailAddress extends And
begin
function __init__ self
begin
call __init__ call ToType unicode call IsRegexMatch string ^[a-z0-9\._\+%-]+@[a-z0-9\.-]+(\.[A-Z]{2,4})+$ error_message=string The specified value "{value}" is not a valid email address
end function
end class
class IsIpv... | from . import *
import ipaddress
class IsEmailAddress(base.And):
def __init__(self):
super(IsEmailAddress, self).__init__(
base.types.ToType(unicode),
base.strings.IsRegexMatch(r'^[a-z0-9\._\+%-]+@[a-z0-9\.-]+(\.[A-Z]{2,4})+$'),
error_message='The specified value "{value}" is not a valid email address'
... | Python | zaydzuhri_stack_edu_python |
function update_gen_data self gendata
begin
for tuple var_key var_val in items gendata
begin
set jsondata at var_key = var_val
end
return true
end function | def update_gen_data(self, gendata):
for var_key, var_val in gendata.items():
self.jsondata[var_key] = var_val
return True | Python | nomic_cornstack_python_v1 |
function yfit self
begin
return dot amatrix acoeff
end function | def yfit(self):
return np.dot(self.amatrix,self.acoeff) | Python | nomic_cornstack_python_v1 |
function inasafe_place_value_coefficient number feature parent
begin
string Given a number, it will return the coefficient of the place value name. For instance: * inasafe_place_value_coefficient(10) -> 1 * inasafe_place_value_coefficient(1700) -> 1.7 It needs to be used with inasafe_number_denomination_unit.
comment N... | def inasafe_place_value_coefficient(number, feature, parent):
"""Given a number, it will return the coefficient of the place value name.
For instance:
* inasafe_place_value_coefficient(10) -> 1
* inasafe_place_value_coefficient(1700) -> 1.7
It needs to be used with inasafe_number_denomination_un... | Python | jtatman_500k |
function update self context data
begin
set context = context
set data = data
set dt = call get_datetime
for tuple tkt bo in items _d_orders at string trades
begin
set price = price
update bo price dt
end
end function | def update(self, context, data):
self.context = context
self.data = data
dt = get_datetime()
for tkt, bo in self._d_orders['trades'].items():
price = self.data[bo.symbol].price
bo.update(price, dt) | Python | nomic_cornstack_python_v1 |
from random import randint
function is_prime_ferma p test_amount=1
begin
for _ in range test_amount
begin
set a = random integer 2 p - 1
if a ^ p - 1 % p != 1
begin
return false
end
end
return true
end function
function main
begin
set number = integer input string Введите число для проверки:
set test_amount = integer i... | from random import randint
def is_prime_ferma(p, test_amount = 1):
for _ in range(test_amount):
a = randint(2, p-1)
if (a ** (p-1)) % p != 1:
return False
return True
def main():
number = int(input("Введите число для проверки: "))
test_amount = int(input("Введите количество тестов: "))
if is_prime_ferma(n... | Python | zaydzuhri_stack_edu_python |
import sys
set stdin = open string B13458.txt string r
set N = integer input
set arr = list map int split input
set tuple B C = map int split input
set re = N
for j in range length arr
begin
set arr at j = arr at j - B
if arr at j > 0
begin
set t = arr at j // C
set re = re + t
set r = arr at j % C
if r
begin
set re = ... | import sys
sys.stdin = open('B13458.txt', 'r')
N = int(input())
arr = list(map(int, input().split()))
B,C = map(int, input().split())
re = N
for j in range(len(arr)):
arr[j] -= B
if arr[j] > 0:
t = arr[j]//C
re += t
r = arr[j]%C
if r:
re += 1
print(re)
#꼭 기억하기!!! 음... | Python | zaydzuhri_stack_edu_python |
function evalClusterRecall **kargs
begin
comment import seaborn as sns
comment import matplotlib.pyplot as plt
set style=string whitegrid
comment [params]
comment ctype: sequence type
comment otype: strictly ordered, partial
comment ptype: prior (to diagnosis), mixed, post
comment general naming pattern of cluster moti... | def evalClusterRecall(**kargs):
# import seaborn as sns
# import matplotlib.pyplot as plt
sns.set(style="whitegrid")
# [params]
# ctype: sequence type
# otype: strictly ordered, partial
# ptype: prior (to diagnosis), mixed, post
# general naming pattern of cluster m... | Python | nomic_cornstack_python_v1 |
for i in range 1 11
begin
print i
end | for i in range(1, 11):
print(i)
| Python | flytech_python_25k |
function _read_json self path
begin
return load json open path
end function | def _read_json(self, path):
return json.load(open(path)) | Python | nomic_cornstack_python_v1 |
string General functions for the load and saving of netcdf files
import netCDF4 as nc
import pandas as pd
function read_nc nc_filename outputDir=none output_filename=none output_h5_key=none time_col=string time time_unit_parser=string days since
begin
set d_nc = call Dataset nc_filename mode=string r
comment Setup the ... | '''
General functions for the load and saving of netcdf files
'''
import netCDF4 as nc
import pandas as pd
def read_nc(nc_filename,
outputDir = None, output_filename = None, output_h5_key = None,
time_col = 'time', time_unit_parser = 'days since '
):
d_nc = nc.Dataset(nc_file... | Python | zaydzuhri_stack_edu_python |
import cv2
import sys
import re
import numpy as np
import os
from random import shuffle
from tqdm import tqdm
import tensorflow as tf
import matplotlib.pyplot as plt
import tflearn
from tflearn.layers.conv import conv_2d , max_pool_2d
from tflearn.layers.core import input_data , dropout , fully_connected
from tflearn.l... | import cv2
import sys
import re
import numpy as np
import os
from random import shuffle
from tqdm import tqdm
import tensorflow as tf
import matplotlib.pyplot as plt
import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.laye... | Python | zaydzuhri_stack_edu_python |
function play_video self video_id
begin
set video = call get_video video_id
if video is none
begin
print string Cannot play video: Video does not exist
return
end
if flag is not none
begin
print string Cannot play video: Video is currently flagged (reason: { flag } )
return
end
if _current_video
begin
call stop_video
e... | def play_video(self, video_id):
video = self._video_library.get_video(video_id)
if video is None:
print("Cannot play video: Video does not exist")
return
if video.flag is not None:
print(f"Cannot play video: Video is currently flagged (reason: {video.flag})")
... | Python | nomic_cornstack_python_v1 |
function set_axis_label self axis label
begin
if is instance axis Integral
begin
set axis = call assert_axis_in_bounds axis ndim
if axis_labels at axis != string label
begin
set full_axis_labels = list axis_labels
set full_axis_labels at axis = string label
set axis_labels = full_axis_labels
end
set last_used = axis
en... | def set_axis_label(
self,
axis: Union[int, Sequence[int]],
label: Union[str, Sequence[str]],
):
if isinstance(axis, Integral):
axis = assert_axis_in_bounds(axis, self.ndim)
if self.axis_labels[axis] != str(label):
full_axis_labels = list(self.a... | Python | nomic_cornstack_python_v1 |
function cli
begin
if cookie_token is none
begin
print string ERROR: Please set the PACKET_TOKEN environment variable to your packet session cookie.
exit 1
end
end function | def cli():
if cookie_token is None:
print("ERROR: Please set the PACKET_TOKEN environment variable to your packet session cookie.")
exit(1) | Python | nomic_cornstack_python_v1 |
from Crypto.Cipher import AES
from PIL import Image
import sys
import random
import string
comment 用argv決定要加密的圖檔,並打開他
set im = call convert string RGB
comment 把圖檔轉成bytes
set arr = call tobytes
comment 先開好output的圖檔
set result = string CBCencrypt.png
set encrypt = b''
set arrBlock = string
set key_stream = string
set p... | from Crypto.Cipher import AES
from PIL import Image
import sys
import random
import string
im = Image.open(sys.argv[1]).convert('RGB') #用argv決定要加密的圖檔,並打開他
arr = im.tobytes()#把圖檔轉成bytes
result = "CBCencrypt.png"#先開好output的圖檔
encrypt = b""
arrBlock = ''
key_stream = ''
padding = 16 - len(arr) % 16
arr += bytes(padding ... | Python | zaydzuhri_stack_edu_python |
function process_enrollment enrollment dicts=list dictionary
begin
string Field contents: Random ID AcadYr_Session Gender Code Session Classification Code Session Major 1 Description Concentration 1 Description Course Work Course Number Course Work Course Title
comment break out the enrollment data
set identifier = str... | def process_enrollment(enrollment, dicts = [dict()]):
'''
Field contents:
Random ID
AcadYr_Session
Gender Code
Session Classification Code
Session Major 1 Description
Concentration 1 Description
Course Work Course Number
Course Work Course Title
'''
# break out the enrollment data
identifier ... | Python | nomic_cornstack_python_v1 |
function get_board_by_id self board_id
begin
set boards = call boards
for board in boards
begin
if starts with name board_id
begin
return board
end
end
return none
end function | def get_board_by_id(self, board_id):
boards = self._jira_connection.boards()
for board in boards:
if board.name.startswith(board_id):
return board
return None | Python | nomic_cornstack_python_v1 |
function set_tags self tags
begin
string Sets this object's tags to only those tags. * tags: a sequence of tag names or Tag objects.
set c_old_tags = list
set old_tags = list
set c_new_tags = list
set new_tags = list
set to_remove = list
set to_add = list
set tags_on_server = call get_tags
for tag in tags_on_serv... | def set_tags(self, tags):
"""Sets this object's tags to only those tags.
* tags: a sequence of tag names or Tag objects.
"""
c_old_tags = []
old_tags = []
c_new_tags = []
new_tags = []
to_remove = []
to_add = []
tags_on_server = self.get... | Python | jtatman_500k |
function poll self timeout interval=0.1
begin
if timeout is none
begin
set timeout = maxint
end
set length = 0
set tmax = time + timeout
try
begin
while length == 0
begin
set length = call PeekNamedPipe incoming 0 at 1
if time >= tmax
begin
break
end
sleep interval
end
end
except TypeError
begin
set ex = call exc_info ... | def poll(self, timeout, interval = 0.1):
if timeout is None:
timeout = sys.maxint
length = 0
tmax = time.time() + timeout
try:
while length == 0:
length = win32pipe.PeekNamedPipe(self.incoming, 0)[1]
if time.time() >= tmax:
... | Python | nomic_cornstack_python_v1 |
function export self dir
begin
set docs = dict
set tuple cre standard = tuple none none
set cres_written = dict
comment internal links are Group/HigherLevelCRE -> CRE
for link in call __get_internal_links
begin
set group = link at 0
set cre = link at 1
set type = link at 2
set grp = none
comment when cres link to eac... | def export(self, dir):
docs = {}
cre, standard = None, None
cres_written = {}
# internal links are Group/HigherLevelCRE -> CRE
for link in self.__get_internal_links():
group = link[0]
cre = link[1]
type = link[2]
grp = None
... | Python | nomic_cornstack_python_v1 |
comment Problem number 5, diving right in!
set D = call arrayer string 2 0; 0 0.5
set R = lambda theta -> array list list cos theta - sin theta list sin theta cos theta
set matrix_product = lambda theta -> dot call R - theta dot D call R theta
set eigs_product = lambda theta -> call eig call matrix_product theta
commen... | #### Problem number 5, diving right in!
D = arrayer('2 0; 0 0.5')
R = lambda theta: np.array([[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]])
matrix_product = lambda theta: np.dot(R(-theta), np.dot(D, R(theta)))
eigs_product = lambda theta: np.linalg.eig(matrix_product(theta))
# let's take this thing... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from urllib.parse import urlencode
import requests
from lxml import etree
import pandas as pd
set ua = string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240
function get_content url
begin
with call request s... | #-*- coding: utf-8 -*-
from urllib.parse import urlencode
import requests
from lxml import etree
import pandas as pd
ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240"
def get_content(url):
with requests.request('GET',u... | Python | zaydzuhri_stack_edu_python |
function _get_dl self dlpath filename expected_checksum
begin
assert starts with dlpath string /dl/ msg string bad download path
set tuple status reason body = call _make_request dlpath
set checksum = hex digest sha256 body
if expected_checksum != checksum
begin
raise call TiError string invalid download checksum. Expe... | def _get_dl(self, dlpath, filename, expected_checksum):
assert dlpath.startswith("/dl/"), "bad download path"
status, reason, body = self._make_request(dlpath)
checksum = hashlib.sha256(body).hexdigest()
if expected_checksum != checksum:
raise TiEr... | Python | nomic_cornstack_python_v1 |
function _visit self
begin
if f is not none
begin
call visit _visit_item
end
set iteminfos = sorted iteminfos key=call itemgetter 0
return iteminfos
end function | def _visit(self):
if self.f is not None:
self.f.visit(self._visit_item)
self.iteminfos = sorted(self.iteminfos, key=operator.itemgetter(0))
return self.iteminfos | Python | nomic_cornstack_python_v1 |
function __init__ self kernel_size filters stage block
begin
call __init__ name=string identity + string stage + block
set tuple filters1 filters2 filters3 = filters
if call image_data_format == string channels_last
begin
set bn_axis = 3
end
else
begin
set bn_axis = 1
end
set conv_name_base = string res + string stage ... | def __init__(self, kernel_size, filters, stage, block):
super().__init__(name='identity' + str(stage) + block)
filters1, filters2, filters3 = filters
if K.image_data_format() == 'channels_last':
bn_axis = 3
else:
bn_axis = 1
conv_name_base = 'res' + str(stage) + block + '_branch'
bn... | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
string 测试关键词提取 textrank 算法
import codecs
from preprocess import preprocess
from gensim.summarization import keywords
set keywords_dict = dictionary
with open string ../data/sensortower_reviews.csv string rb string utf-8 string ignore as infile
begin
read line infile
for tuple line_ser line in enume... | #coding:utf-8
"""
测试关键词提取 textrank 算法
"""
import codecs
from preprocess import preprocess
from gensim.summarization import keywords
keywords_dict = dict()
with codecs.open('../data/sensortower_reviews.csv', 'rb', 'utf-8', 'ignore') as infile:
infile.readline()
for line_ser, line in enumerate(infile):
i... | Python | zaydzuhri_stack_edu_python |
function embed_input x hps
begin
set x_embed = call get_variable string x_embed list n_bin n_state initializer=call random_normal_initializer stddev=0.02
set pos_embed = call get_variable string pos_embed list n_x n_state initializer=call random_normal_initializer stddev=0.01
set h = add tf call embedding_lookup x_embe... | def embed_input(x, hps):
x_embed = tf.get_variable('x_embed', [hps.n_bin, hps.n_state], initializer=tf.random_normal_initializer(stddev=0.02))
pos_embed = tf.get_variable('pos_embed', [hps.n_x, hps.n_state], initializer=tf.random_normal_initializer(stddev=0.01))
h = tf.add(embedding_lookup(x_embed, x)... | Python | nomic_cornstack_python_v1 |
function rotz t
begin
set c = cos t
set s = sin t
return array list list c - s 0 list s c 0 list 0 0 1
end function | def rotz(t):
c = np.cos(t)
s = np.sin(t)
return np.array([[c, -s, 0],
[s, c, 0],
[0, 0, 1]]) | Python | nomic_cornstack_python_v1 |
function __init__ self db_path=string db/monitor.db
begin
set _conn = call connect database=db_path
set _curr = call cursor
set text_factory = str
end function | def __init__(self, db_path='db/monitor.db'):
self._conn = sqlite3.connect(database=db_path)
self._curr = self._conn.cursor()
self._conn.text_factory = str | Python | nomic_cornstack_python_v1 |
function get_possible_composition_configs self num_active_cores
begin
set num_cores_base = call largest_power_of_two_divisor num_active_cores
set composed_core_configs_list = call get_core_composition_configs num_cores_base
set num_threads_list = list comprehension num_active_cores / c at 0 * c at 1 for c in composed_c... | def get_possible_composition_configs(self, num_active_cores):
num_cores_base = largest_power_of_two_divisor(num_active_cores)
composed_core_configs_list = self.get_core_composition_configs(num_cores_base)
num_threads_list = [num_active_cores/(c[0] * c[1]) for c in composed_core_configs_list]
... | Python | nomic_cornstack_python_v1 |
comment bu yerda len() methodi orqali listni uzunligini ko'rib chiqamiz
set name = list string Jhon string jamshid string Alex string lola
comment bu len() listni uzunli necha elementdan tashkil topganligi degani
length name
print length name | # bu yerda len() methodi orqali listni uzunligini ko'rib chiqamiz
name=["Jhon","jamshid","Alex","lola"]
len(name) # bu len() listni uzunli necha elementdan tashkil topganligi degani
print(len(name)) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment Write a Python program to reverse a string.
set yourString = input string Enter your desired string :
set reversedString = string
for i in yourString
begin
set reversedString = i + reversedString
end
print string Your string was: yourString
print string The reversed string is: rev... | #!/usr/bin/env python3
# Write a Python program to reverse a string.
yourString = input("Enter your desired string : ")
reversedString = " "
for i in yourString:
reversedString = i + reversedString
print("\nYour string was: ", yourString)
print("\nThe reversed string is: ",reversedString)
| Python | zaydzuhri_stack_edu_python |
function __init__ self session _id=none name=none server=none options=none
begin
set session : string Session = session
set id : int = if expression _id is not none then _id else call next_node_id
set name : str = name or string { __name__ } { id }
set server : string DistributedServer = server
set model : Optional at ... | def __init__(
self,
session: "Session",
_id: int = None,
name: str = None,
server: "DistributedServer" = None,
options: NodeOptions = None,
) -> None:
self.session: "Session" = session
self.id: int = _id if _id is not None else self.session.next_node_i... | Python | nomic_cornstack_python_v1 |
comment 首字母大写
print title name
comment 所有字母大写
print upper name
comment 所有字母小写
print lower name
comment 拼接字符串
set first = string ada
set last_name = string lovelace
set full_name = first + string + last_name
print full_name
print string hello, + title full_name + string !
set message = string hello, + title full_name +... | #首字母大写
print(name.title())
#所有字母大写
print(name.upper())
#所有字母小写
print(name.lower())
#拼接字符串
first="ada"
last_name="lovelace"
full_name=first+" "+last_name
print(full_name)
print("hello, "+full_name.title()+"!")
message="hello, "+full_name.title()+"!"
print(message)
#制表符
print("\tPython")
#换行符
print("Languages:\nPython\... | Python | zaydzuhri_stack_edu_python |
comment 8. Write a function, is_prime, that takes an integer and returns True if the number is prime and False if the number is not prime.
function is_prime integer
begin
if integer > 1
begin
for i in range 2 integer
begin
if integer % i == 0
begin
return false
end
end
for else
begin
return true
end
end
else
begin
retu... | # 8. Write a function, is_prime, that takes an integer and returns True if the number is prime and False if the number is not prime.
def is_prime(integer):
if integer > 1:
for i in range(2, integer):
if integer % i == 0:
return False
else:
return True
els... | Python | zaydzuhri_stack_edu_python |
import urllib.request , json
import certifi
import ssl
set battleDB = list
set users = list
function getUserBattles username
begin
with url open string https://game-api.splinterlands.com/battle/history?player= + username context=call create_default_context cafile=where as url
begin
set data = loads decode read url
se... | import urllib.request,json
import certifi
import ssl
battleDB = []
users = []
def getUserBattles(username):
with urllib.request.urlopen('https://game-api.splinterlands.com/battle/history?player='+username, context=ssl.create_default_context(cafile=certifi.where())) as url:
data = json.loads(url.read().dec... | Python | zaydzuhri_stack_edu_python |
string https://app.glider.ai/practice/problem/algorithms/queries-in-array/problem related problem finding floor and ciel of element in the array using binary search (problem reference ceil_ele_sorted_arr.py) https://www.geeksforgeeks.org/ceiling-in-a-sorted-array/ Given an array of N integers and Q/2 queries, each incl... | """
https://app.glider.ai/practice/problem/algorithms/queries-in-array/problem
related problem finding floor and ciel of element in the array using binary search (problem reference ceil_ele_sorted_arr.py)
https://www.geeksforgeeks.org/ceiling-in-a-sorted-array/
Given an array of N integers and Q/2 queries, each inc... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
comment Loading data (Substitute UUN)
set train_mat = call loadmat string ../data/train_data.mat
set test_mat = call loadmat string ../data/test_data.mat
set train_x = array train_mat at string train_x
set train_y = array train_mat at string train_y
set... | import numpy as np
import matplotlib.pyplot as plt
import scipy.io
# Loading data (Substitute UUN)
train_mat = scipy.io.loadmat('../data/train_data.mat')
test_mat = scipy.io.loadmat('../data/test_data.mat')
train_x = np.array(train_mat['train_x'])
train_y = np.array(train_mat['train_y'])
test_x = np.array(test_mat['t... | Python | zaydzuhri_stack_edu_python |
function handle_batch self full_batch
begin
set final_batch = full_batch at slice : :
set batch_size = length full_batch
set prev_preds_dict = dictionary comprehension i : list final_batch at i for i in range length final_batch
set short_ids = list comprehension i for i in range length full_batch if length full_batc... | def handle_batch(self, full_batch):
final_batch = full_batch[:]
batch_size = len(full_batch)
prev_preds_dict = {i: [final_batch[i]] for i in range(len(final_batch))}
short_ids = [i for i in range(len(full_batch))
if len(full_batch[i]) < self.min_len]
pred_ids... | 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.