code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function test_create_docker_image begin set client = call CBWApi API_URL API_KEY SECRET_KEY set info = dict string image_name string library/debian ; string image_tag string latest ; string docker_registry_id string 1 ; string docker_engine_id string 4 ; string node_id string 1 with call use_cassette string spec/fixtur...
def test_create_docker_image(): client = CBWApi(API_URL, API_KEY, SECRET_KEY) info = { "image_name": "library/debian", "image_tag": "latest", "docker_registry_id": "1", "docker_engine_id": "4", "node_id": "1", } with vcr.use_c...
Python
nomic_cornstack_python_v1
import unittest import sys from api.services.db import HbaseInternals from api.models import Document from api.services.db import document from api import canonicalize class DocumentTest extends TestCase begin function setUp self begin set updated_at = 12345678 set a = call Document url=call canonicalize string http://...
import unittest import sys from api.services.db import HbaseInternals from api.models import Document from api.services.db import document from api import canonicalize class DocumentTest(unittest.TestCase): def setUp(self): updated_at = 12345678 a = Document(url=canonicalize('http://www.buzzfeed...
Python
zaydzuhri_stack_edu_python
string Created on Jun 24, 2013 @author: lrvillan import sys import os import datetime import logging from mainwindowui import Ui_MainWindow from PyQt4.QtGui import QApplication , QPixmap , QMainWindow , QWidget from PyQt4.QtCore import Qt from PIL import Image from minimum_distance import distance_norm_1 , distance_nor...
''' Created on Jun 24, 2013 @author: lrvillan ''' import sys import os import datetime import logging from mainwindowui import Ui_MainWindow from PyQt4.QtGui import QApplication, QPixmap, QMainWindow, QWidget from PyQt4.QtCore import Qt from PIL import Image from minimum_distance import distance_norm_1, distance_no...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 comment import matplotlib.pyplot as plt import numpy as np import random function loadDataSet filename begin set dataMat = list set labelMat = list set numFeat = length split read line open filename string - 1 set fr = open filename for line in read lines fr begin set line = split strip line stri...
#coding:utf-8 # import matplotlib.pyplot as plt import numpy as np import random def loadDataSet(filename): dataMat = [] labelMat = [] numFeat = len(open(filename).readline().split('\t')) - 1 fr = open(filename) for line in fr.readlines(): line = line.strip().split('\t') lineArr = [...
Python
zaydzuhri_stack_edu_python
import speech_recognition as sr from datetime import datetime import webbrowser import time from gtts import gTTS from playsound import playsound import random import os from pasword import security call security set r = call Recognizer function record ask=false begin with call Microphone as source begin if ask begin c...
import speech_recognition as sr from datetime import datetime import webbrowser import time from gtts import gTTS from playsound import playsound import random import os from pasword import security security() r = sr.Recognizer() def record(ask = False): with sr.Microphone() as source: if ask: ...
Python
zaydzuhri_stack_edu_python
function plot5b nSamples begin set rv = binom 400 0.3 set tuple expectations variances = call simulate nSamples rv plot nSamples expectations variances 120 84 string Binomial distribution end function
def plot5b(nSamples): rv = stats.binom(400, 0.3) expectations, variances = simulate(nSamples, rv) plot(nSamples, expectations, variances, 120, 84, "Binomial distribution")
Python
nomic_cornstack_python_v1
from pandas import Series , DataFrame import pandas as pd import numpy as np comment 打开文件 set car_complain = read csv string car_complain.csv comment 拆分problem并建表 set df = join drop car_complain string problem axis=1 call get_dummies string , comment 获取问题标签 set tags = columns at slice 7 : : comment 品牌总投诉量 set df at s...
from pandas import Series, DataFrame import pandas as pd import numpy as np #打开文件 car_complain=pd.read_csv('car_complain.csv') #拆分problem并建表 df=car_complain.drop('problem',axis=1).join(car_complain.problem.str.get_dummies(',')) #获取问题标签 tags=df.columns[7:] #品牌总投诉量 df['brand']=df['brand'].replace('一汽-大众','一汽大众'...
Python
zaydzuhri_stack_edu_python
function clip_gradient optimizer grad_clip begin for group in param_groups begin for param in group at string params begin if grad is not none begin call clamp_ - grad_clip grad_clip end end end end function
def clip_gradient(optimizer, grad_clip): for group in optimizer.param_groups: for param in group['params']: if param.grad is not None: param.grad.data.clamp_(-grad_clip, grad_clip)
Python
nomic_cornstack_python_v1
with open string C-large-practice.in as i begin set n = integer read line i for j in call xrange n begin append strings read line i end end set translated_strings = list for i in strings begin set temp = string set i = replace i string string for j in call xrange length i begin if j == length i - 1 begin set temp = ...
with open("C-large-practice.in") as i: n = int(i.readline()) for j in xrange(n): strings.append(i.readline()) translated_strings = [] for i in strings: temp = "" i = i.replace("\n","") for j in xrange(len(i)): if j == len(i)-1: temp += codes[i[j]]
Python
zaydzuhri_stack_edu_python
from urllib import parse import json import requests import simulatorTester import random class Methods begin decorator staticmethod comment parse the post request function parse_post_path path begin print string Inside parsePostPath: + string set path_parse = url parse path set i = 0 while path_parse at i begin print ...
from urllib import parse import json import requests import simulatorTester import random class Methods: # parse the post request @staticmethod def parse_post_path(path): print('Inside parsePostPath:' + '\n') path_parse = parse.urlparse(path) i = 0 while path_parse[i]: ...
Python
zaydzuhri_stack_edu_python
comment importamos el módulo 2 de la siguiente manera import modulo2 comment podemos acceder a los elementos de su diccionario print items diccionario comment de esta manera podemos acceder a su función 'suma', la cual recibe 3 parámetros print call suma 2 3 7
import modulo2 #importamos el módulo 2 de la siguiente manera print(modulo2.diccionario.items()) # podemos acceder a los elementos de su diccionario print(modulo2.suma(2,3,7)) # de esta manera podemos acceder a su función 'suma', la cual recibe 3 parámetros
Python
zaydzuhri_stack_edu_python
function snmpget self snmp_get_oid begin set tuple errorIndication errorStatus _ varBinds = call getCmd call CommunityData string my-agent pwboard_snmp_rw_community_string 0 call UdpTransportTarget tuple pw_board pw_snmp_service_port snmp_get_oid if errorIndication or errorStatus != 0 or not varBinds begin raise call C...
def snmpget(self, snmp_get_oid): errorIndication, errorStatus, _, varBinds = \ cmdgen.CommandGenerator().getCmd( cmdgen.CommunityData('my-agent', self.pwboard_snmp_rw_community_string, 0), cmdgen.UdpTransportTarget((self.pw_board, self.pw_snmp_service_port)), ...
Python
nomic_cornstack_python_v1
function mvn_chisquare x mu cov begin set L = call cholesky cov set y = call solve L x - mu return dot y y end function
def mvn_chisquare(x,mu,cov): L = np.linalg.cholesky(cov) y = np.linalg.solve(L,x-mu) return np.dot(y,y)
Python
nomic_cornstack_python_v1
string Author: Chris Zhou, Contributor: Meina Zhou This module cleans census data downloaded from UCI Machine Learning Repository, reads data into pandas dataframe, drops missing values, transforms data into catogorical variable, and return a cleaned dataframe ready to use in building prediction model. import pandas as...
''' Author: Chris Zhou, Contributor: Meina Zhou This module cleans census data downloaded from UCI Machine Learning Repository, reads data into pandas dataframe, drops missing values, transforms data into catogorical variable, and return a cleaned dataframe ready to use in building prediction model. ''' import pandas ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2.6 comment encoding: utf-8 string untitled.py Created by kdm on 2010-02-10. Copyright (c) 2010 __MyCompanyName__. All rights reserved. import sys comment import getopt import time from datetime import date from datetime import timedelta from time import strptime import os import string impo...
#!/usr/bin/env python2.6 # encoding: utf-8 """ untitled.py Created by kdm on 2010-02-10. Copyright (c) 2010 __MyCompanyName__. All rights reserved. """ import sys #import getopt import time from datetime import date from datetime import timedelta from time import strptime import os import string import subprocess imp...
Python
zaydzuhri_stack_edu_python
function resolve_image_name image_definition start_line end_line begin if not image_definition begin return string end for tuple idx step in enumerate list comprehension step for step in get image_definition string docker or list if step begin if is instance get image_definition string docker dict begin if step == st...
def resolve_image_name(image_definition: dict[str, Any], start_line: int, end_line: int) -> str: if not image_definition: return "" for idx, step in enumerate([step for step in image_definition.get('docker') or [] if step]): if isinstance(image_definition.get('docker'), dict): ...
Python
nomic_cornstack_python_v1
comment Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd comment Importing the dataset set dataset = read csv string Mall_Customers.csv set X = values comment y = dataset.iloc[:, 3].values comment plotting dendogram import scipy.cluster.hierarchy as sch call dendrogram call...
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('Mall_Customers.csv') X = dataset.iloc[:, [3, 4]].values # y = dataset.iloc[:, 3].values #plotting dendogram import scipy.cluster.hierarchy as sch sch.dendrogram(sch.linkage(X...
Python
zaydzuhri_stack_edu_python
function post_event request pk=none begin set event_pk = get POST string event_pk print string post event_pk event_pk if method == string POST begin set p = get objects pk=pk if event_pk == string None begin comment add new event print string no event, new form set form = call EventForm initial=dict string paper p data...
def post_event(request, pk=None): event_pk = request.POST.get('event_pk') print('post event_pk', event_pk) if request.method == "POST": p=Paper.objects.get(pk=pk) if event_pk=="None": # add new event print('no event, new form') form = EventForm(initial={'p...
Python
nomic_cornstack_python_v1
comment encoding = utf-8 function binary_search alist item begin if length alist == 0 begin return false end set mid = length alist // 2 if alist at mid == item begin return true end else if item < alist at mid begin return call binary_search alist at slice : mid : item end else begin comment 这里边是要去掉中值的,因为第一次二分查找找的中值...
# encoding = utf-8 def binary_search(alist, item): if len(alist) == 0: return False mid = len(alist) // 2 if alist[mid] == item: return True else: if item < alist[mid]: return binary_search(alist[:mid],item) else: # 这里边是要去掉中值的,因为第一次二分查找找...
Python
zaydzuhri_stack_edu_python
import requests from bs4 import BeautifulSoup function paper_titles site begin comment シカゴ Historyo of religions set url = site set HP = get requests url set soup = call BeautifulSoup text string html.parser set papers = find all soup class_=string hlFld-Title comment journalの名前 print call getText comment 論文の名前 del pap...
import requests from bs4 import BeautifulSoup def paper_titles(site): #シカゴ Historyo of religions url = site HP = requests.get(url) soup = BeautifulSoup(HP.text, "html.parser") papers = soup.find_all(class_="hlFld-Title") #journalの名前 print(soup.find("title").getText()) #論文の名前 del ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt comment arbitrary data set data = list 1 4 6 3 8 3 7 9 1 comment create bins of values set bins = list 0 2 4 6 8 10 comment create the histogram histogram data bins histtype=string bar rwidth=0.8 comment label the axes x label string Data Values y label string Number of Occurrences comme...
import matplotlib.pyplot as plt # arbitrary data data = [1, 4, 6, 3, 8, 3, 7, 9, 1] # create bins of values bins = [0, 2, 4, 6, 8, 10] # create the histogram plt.hist(data, bins, histtype='bar', rwidth=0.8) # label the axes plt.xlabel('Data Values') plt.ylabel('Number of Occurrences') # add title plt.title('Histog...
Python
jtatman_500k
function move num_letters text begin set text = text at slice num_letters : : + text at slice : num_letters : return text end function function insert text idx val begin if not idx < 0 or idx > length text begin set text = text at slice : idx : + val + text at slice idx : : end return text end function function...
def move(num_letters, text): text = text[num_letters:] + text[:num_letters] return text def insert(text, idx, val): if not idx < 0 or idx > len(text): text = text[:idx] + val + text[idx:] return text def change(text, key_val, new_val): if key_val in text: text = text.replace(key_...
Python
zaydzuhri_stack_edu_python
function sql_type self begin return get pulumi self string sql_type end function
def sql_type(self) -> pulumi.Input[str]: return pulumi.get(self, "sql_type")
Python
nomic_cornstack_python_v1
import scrapy class NewsSpider extends Spider begin set name = string news_spider set start_urls = list string https://www.example.com/news/ function parse self response begin for article_url in extract call css string a.article-title::attr(href) begin yield call Request url join article_url callback=parse_article end ...
import scrapy class NewsSpider(scrapy.Spider): name = 'news_spider' start_urls = ['https://www.example.com/news/'] def parse(self, response): for article_url in response.css('a.article-title::attr(href)').extract(): yield scrapy.Request(response.urljoin(article_url), callback=self.pars...
Python
iamtarun_python_18k_alpaca
import sys , os import argparse set s_loopDivider = list range 27 55 set s_postDivider = list 1 2 4 8 16 set s_lcdifPreDiv = list range 0 8 set s_lcdifDiv = list range 0 8 set s_maxPixelClockFreq = 75000000 set s_maxFreqError_1GHz = 1000000000 set kLcdResolution_480x272 = string 480x272 set kLcdResolution_800x600 = str...
import sys, os import argparse s_loopDivider = list(range(27, 55)) s_postDivider = [1, 2, 4, 8, 16] s_lcdifPreDiv = list(range(0, 8)) s_lcdifDiv = list(range(0, 8)) s_maxPixelClockFreq = 75000000 s_maxFreqError_1GHz = 1000000000 kLcdResolution_480x272 = '480x272' kLcdResolution_800x600 = '800x600' kLcdResolution_128...
Python
zaydzuhri_stack_edu_python
import MLP_3 as mlp import helper_functions as act_func import dataMethods as data import layer from datetime import datetime import matplotlib.pyplot as plt function get_start_data data_split val_split=- 1 begin set tuple train_set valid_set test_set = call get_data_from_files_with_vaildation_data data_split val_split...
import MLP_3 as mlp import helper_functions as act_func import dataMethods as data import layer from datetime import datetime import matplotlib.pyplot as plt def get_start_data(data_split, val_split = -1): train_set, valid_set, test_set = data.get_data_from_files_with_vaildation_data(data_split, val_split)...
Python
zaydzuhri_stack_edu_python
function make_wander_box self begin set x = integer location at 0 set y = integer location at 1 set box_list = list set box_rects = list for i in range x - 3 x + 4 begin append box_list list i y - 3 append box_list list i y + 3 end for i in range y - 2 y + 3 begin append box_list list x - 3 i append box_list list x +...
def make_wander_box(self): x = int(self.location[0]) y = int(self.location[1]) box_list = [] box_rects = [] for i in range(x-3, x+4): box_list.append([i, y-3]) box_list.append([i, y+3]) for i in range(y-2, y+3): box_list.append([x-3, ...
Python
nomic_cornstack_python_v1
function futures_get_position_mode self **params begin return call _request_futures_api string get string positionSide/dual true data=params end function
def futures_get_position_mode(self, **params): return self._request_futures_api('get', 'positionSide/dual', True, data=params)
Python
nomic_cornstack_python_v1
import re set phoneNumRegex = compile string \d\d\d-\d\d\d-\d\d\d\d set num = search string My number is 509-555-9911. print string Phone number: + call group
import re phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') num = phoneNumRegex.search('My number is 509-555-9911.') print('Phone number: ' + num.group())
Python
zaydzuhri_stack_edu_python
function parse_path path begin string Parse a rfc 6901 path. if not path begin raise call ValueError string Invalid path end if is instance path str begin if path == string / begin raise call ValueError string Invalid path end if path at 0 != string / begin raise call ValueError string Invalid path end return split pat...
def parse_path(path): """Parse a rfc 6901 path.""" if not path: raise ValueError("Invalid path") if isinstance(path, str): if path == "/": raise ValueError("Invalid path") if path[0] != "/": raise ValueError("Invalid path") return path.split(_PATH_SEP)[1:] elif isinstance(path, (tup...
Python
jtatman_500k
while sandwish_orders begin set sandwish = pop sandwish_orders append finished_sandwishes sandwish end for sandwish in finished_sandwishes begin print string Finish + sandwish + string sandwish! end
while sandwish_orders: sandwish=sandwish_orders.pop() finished_sandwishes.append(sandwish) for sandwish in finished_sandwishes: print("Finish "+sandwish+"sandwish!")
Python
zaydzuhri_stack_edu_python
function testOneAlignmentPerRead self begin set mockOpener = call mockOpen read_data=PARAMS + RECORD0 with call object builtins string open mockOpener begin set readsAlignments = call LightReadsAlignments string file.json DB set result = list filter oneAlignmentPerRead=true assert equal 1 length result assert equal 1 l...
def testOneAlignmentPerRead(self): mockOpener = mockOpen(read_data=PARAMS + RECORD0) with patch.object(builtins, 'open', mockOpener): readsAlignments = LightReadsAlignments('file.json', DB) result = list(readsAlignments.filter(oneAlignmentPerRead=True)) self.assertEqu...
Python
nomic_cornstack_python_v1
function updateGraphics begin call update_idletasks end function
def updateGraphics(): _root.update_idletasks()
Python
nomic_cornstack_python_v1
comment Ler um angulo em Graus e converter em Radianos set ang = decimal input string Digite um ângulo em Graus: set rad = ang * 3.14 / 180 print string O ângulo convertido em Radianos é: { rad }
# Ler um angulo em Graus e converter em Radianos ang = float(input('Digite um ângulo em Graus: ')) rad = ang * 3.14 / 180 print(f'O ângulo convertido em Radianos é: {rad}')
Python
zaydzuhri_stack_edu_python
set first_name = string input string Please enter your first name: set last_name = string input string Please enter your last name: print string { first_name } { last_name } print string Welcome! + first_name + string + last_name set goal = string input string What are you saving money for? set price = integer input s...
first_name= str(input("Please enter your first name: ")) last_name=str(input ("Please enter your last name: ")) print(f"{first_name} {last_name}" ) print("Welcome! " + first_name + " " + last_name) goal=str(input("What are you saving money for? ")) price= int(input( "What's the price for " + goal + "? ")) starting_...
Python
zaydzuhri_stack_edu_python
function divide n d begin try begin set result = n / d end except ZeroDivisionError as zde begin print zde end try else begin print string O resultado é: result return result end end function if __name__ == string __main__ begin set n = integer input string Digite um numerador: set d = integer input string Digite um de...
def divide(n, d): try: result = n / d except ZeroDivisionError as zde: print(zde) else: print('O resultado é:', result) return result if __name__ == '__main__': n = int(input('Digite um numerador:')) d = int(input('Digite um denominador:')) divide(n, d)
Python
zaydzuhri_stack_edu_python
function encrypt_card_number card_number begin set card_number = replace card_number string string set encrypted_number = string for tuple i symbol in enumerate card_number begin if i < 12 begin set encrypted_number = encrypted_number + string * end else begin set encrypted_number = encrypted_number + symbol end end ...
def encrypt_card_number(card_number: str) -> str: card_number = card_number.replace(' ', '') encrypted_number = '' for i, symbol in enumerate(card_number): if i < 12: encrypted_number += '*' else: encrypted_number += symbol return encrypted_number if __name__ ==...
Python
zaydzuhri_stack_edu_python
async function get_request cls req begin set url = string url debug string Getting data and status code extra=dict string has_body has_body ; string url url set query = call parse_qs query_string set headers = dictionary comprehension decode k : decode v for tuple k v in raw_headers set body = none if can_read_body beg...
async def get_request(cls, req): url = str(req.url) logger.debug('Getting data and status code', extra={'has_body': req.has_body, 'url': url}) query = parse_qs(req.rel_url.query_string) headers = {k.decode(): v.decode() for k, v in req.raw_headers} body = Non...
Python
nomic_cornstack_python_v1
string API app. from django.apps import AppConfig from django.db import connection from api.core.helpers import redis_hash , redis_leaderboard from api.core.constants import USERS_INIT_SQL , LEADERBOARD_INIT_SQL , logger import orjson as json import uuid function get_users_dict cursor begin string Return a dict such th...
""" API app. """ from django.apps import AppConfig from django.db import connection from api.core.helpers import redis_hash, redis_leaderboard from api.core.constants import USERS_INIT_SQL, LEADERBOARD_INIT_SQL, logger import orjson as json import uuid def get_users_dict(cursor): """ Return a dict such that...
Python
zaydzuhri_stack_edu_python
function key self begin return get pulumi self string key end function
def key(self) -> str: return pulumi.get(self, "key")
Python
nomic_cornstack_python_v1
function _load_snmp_config self begin set ctxt = call get_admin_context set marker = none set finished = false set limit = DEFAULT_LIMIT while not finished begin set alert_sources = call alert_source_get_all ctxt marker=marker limit=limit for alert_source in alert_sources begin set snmp_config = dictionary update snmp_...
def _load_snmp_config(self): ctxt = context.get_admin_context() marker = None finished = False limit = constants.DEFAULT_LIMIT while not finished: alert_sources = db_api.alert_source_get_all(ctxt, marker=marker, ...
Python
nomic_cornstack_python_v1
function get_users begin set all_users = users call emit string users_all all_users end function
def get_users(): all_users = users emit("users_all", all_users)
Python
nomic_cornstack_python_v1
string Processes the data and converts it to an ARFF file from pandas import DataFrame , read_csv , Series , merge from handler.utils import ARFF_PATH , PTID_COL , CLUSTERING_PATH , CLUSTER_ID_COL , NUMERIC_COL_TYPE , get_data function arff_handler cohort dataset cluster_method n_clusters iteration n_kept_feats cluster...
"""Processes the data and converts it to an ARFF file""" from pandas import DataFrame, read_csv, Series, merge from handler.utils import ( ARFF_PATH, PTID_COL, CLUSTERING_PATH, CLUSTER_ID_COL, NUMERIC_COL_TYPE, get_data ) def arff_handler( cohort: str, dataset: str, cluster_method: str, n_clusters: int, ite...
Python
zaydzuhri_stack_edu_python
function _define_train self begin string print(" start_decay_step=%d, learning_rate=%g, decay_steps %d, " "decay_factor %g, learning_rate_warmup_steps=%d, " "learning_rate_warmup_factor=%g, starting_learning_rate=%g" % (self.hparams.start_decay_step, self.hparams.learning_rate, self.hparams.decay_steps, self.hparams.de...
def _define_train(self): """print(" start_decay_step=%d, learning_rate=%g, decay_steps %d, " "decay_factor %g, learning_rate_warmup_steps=%d, " "learning_rate_warmup_factor=%g, starting_learning_rate=%g" % (self.hparams.start_decay_step, self.hparams.learning_rate, sel...
Python
nomic_cornstack_python_v1
function test_constructor self begin set hand = call Hand list call Card string A string D assert is instance hand Hand end function
def test_constructor(self): hand = Hand([Card("A", "D")]) assert isinstance(hand, Hand)
Python
nomic_cornstack_python_v1
function initGui self begin set icon_path = string :/plugins/va_analyse/icon.png call add_action icon_path text=call tr string VA Analyse callback=run parent=call mainWindow comment will be set False in run() set first_start = true end function
def initGui(self): icon_path = ':/plugins/va_analyse/icon.png' self.add_action( icon_path, text=self.tr(u'VA Analyse'), callback=self.run, parent=self.iface.mainWindow()) # will be set False in run() self.first_start = True
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- comment 王刘俊 comment 2019/7/17 下午11:37 set menu_dic = dict string 北京 dict string 海淀 dict string 五道口 dict string soho dict ; string 网易 dict ; string google dict ; string 中关村 dict string 爱奇艺 dict ; string 汽车之家 dict ; string youku dict ; string 上地 dict string 百度 dict ; string 昌平 dict str...
# -*- coding:utf-8 -*- # 王刘俊 # 2019/7/17 下午11:37 menu_dic = { '北京': { '海淀': { '五道口': { 'soho': {}, '网易': {}, 'google': {} }, '中关村': { '爱奇艺': {}, '汽车之家': {}, 'youku': {}, ...
Python
zaydzuhri_stack_edu_python
import codecs import numpy as np import cv2 import os function resize image width=none height=none inter=INTER_AREA begin comment initialize the dimensions of the image to be resized and comment grab the image size set dim = none set tuple h w = shape at slice : 2 : comment if both the width and height are None, then...
import codecs import numpy as np import cv2 import os def resize(image, width=None, height=None, inter=cv2.INTER_AREA): # initialize the dimensions of the image to be resized and # grab the image size dim = None (h, w) = image.shape[:2] # if both the width and height are None, then return the ...
Python
zaydzuhri_stack_edu_python
function test_op_iadd_array_float self begin set device = devices at 0 set stream = call get_default_stream set a = array range 1 4711 * 1024 dtype=float set o = a + 1.3 set old_a = call empty_like a set old_o = call empty_like o set old_a at slice : : = a at slice : : set old_o at slice : : = o at slice : :...
def test_op_iadd_array_float(self): device = pymic.devices[0] stream = device.get_default_stream() a = numpy.arange(1, 4711 * 1024, dtype=float) o = a + 1.3 old_a = numpy.empty_like(a) old_o = numpy.empty_like(o) old_a[:] = a[:] old_o[:] = o[:] e...
Python
nomic_cornstack_python_v1
import numpy set value = split input set n = integer value at 0 set m = integer value at 1 set a = list for i in range n begin set list = list comprehension integer i for i in split strip input append a list end set a = array a print transpose a print flatten a
import numpy value=input().split() n=int(value[0]) m=int(value[1]) a=[] for i in range(n): list=[int(i) for i in input().strip().split()] a.append(list) a=numpy.array(a) print(a.transpose()) print(a.flatten())
Python
zaydzuhri_stack_edu_python
comment @lc app=leetcode.cn id=852 lang=python3 comment [852] 山脉数组的峰顶索引 comment @lc code=start class Solution begin function peakIndexInMountainArray self A begin set peak = decimal string -inf set res = 0 for tuple i top in enumerate A begin if top > peak begin set peak = top set res = i end end return res string # 二分...
# # @lc app=leetcode.cn id=852 lang=python3 # # [852] 山脉数组的峰顶索引 # # @lc code=start class Solution: def peakIndexInMountainArray(self, A: List[int]) -> int: peak = float('-inf') res = 0 for i, top in enumerate(A): if top > peak: peak=top res = i ...
Python
zaydzuhri_stack_edu_python
function change_color mutated_genome begin set index = random integer 0 max 0 length mutated_genome - 1 if color_mode == string RGB begin set color_red = random integer - 25 25 set color_green = random integer - 25 25 set color_blue = random integer - 25 25 set color = mutated_genome at index at 0 set newcolor = tuple ...
def change_color(mutated_genome): index = random.randint(0,max(0,len(mutated_genome)-1)) if color_mode == 'RGB': color_red = random.randint(-25,25) color_green = random.randint(-25,25) color_blue = random.randint(-25,25) color = mutated_genome[index][0] newcolor = (color[0]+color_red...
Python
nomic_cornstack_python_v1
set A = 40 print A print type A set B = false print B print type B set C = 20.5 print C print type C set D = string A print D print type D set E = string Aryan print E print type E set F = list 0 1 2 print F print type F
A=40 print(A) print(type(A)) B=False print(B) print(type(B)) C=20.5 print(C) print(type(C)) D='A' print(D) print(type(D)) E='Aryan' print(E) print(type(E)) F=[0,1,2] print(F) print(type(F))
Python
zaydzuhri_stack_edu_python
function get_args begin set parser = call ArgumentParser prog=string Metabat-Plot.py description=string Plot bin information from MetaBAT2. call add_argument string -i string --input required=true help=string The o2 format summary file from CheckM. call add_argument string -l string --label required=true help=string A ...
def get_args(): parser = argparse.ArgumentParser( prog='Metabat-Plot.py', description="""Plot bin information from MetaBAT2.""") parser.add_argument("-i", "--input", required=True, help="The o2 format summary file from CheckM.") parser.add_arg...
Python
nomic_cornstack_python_v1
function update self surface **kwargs begin for cell in cells begin update cell surface keyword kwargs end end function
def update(self, surface, **kwargs): for cell in self.cells: cell.update(surface, **kwargs)
Python
nomic_cornstack_python_v1
from covid import Covid import matplotlib.pyplot as plt from tkinter import * from PIL import Image , ImageTk function country begin set covid = call Covid set nme = get entt set string set data = call get_status_by_country_name nme comment print(data) set remove = list string id string country string latitude string l...
from covid import Covid import matplotlib.pyplot as plt from tkinter import * from PIL import Image, ImageTk def country(): covid = Covid() nme=entt.get() entt.set("") data=covid.get_status_by_country_name(nme) # print(data) remove=['id', 'country', 'latitude', 'longitude', 'last_upd...
Python
zaydzuhri_stack_edu_python
import numpy as np class NN begin function __init__ self inputLayerSize layerSizes=tuple 64 64 10 begin set weights = list reshape call normal 0 0.001 inputLayerSize * layerSizes at 0 tuple inputLayerSize layerSizes at 0 for i in range 1 length layerSizes begin append weights reshape call normal 0 0.001 layerSizes at i...
import numpy as np class NN: def __init__ (self, inputLayerSize, layerSizes = (64,64,10)): self.weights = [np.random.normal(0,0.001,inputLayerSize*layerSizes[0]).reshape((inputLayerSize, layerSizes[0]))] for i in range(1,len(layerSizes)): self.weights.append(np.random.normal(0,0.001,layerSizes[i-1]*lay...
Python
zaydzuhri_stack_edu_python
function monitor_batch_job batch_request config=none sleep_time=_DEFAULT_SLEEP_TIME analysis_sleep_time=_DEFAULT_ANALYSIS_SLEEP_TIME begin if sleep_time < _MIN_SLEEP_TIME begin raise call ValueError string To avoid making too many service requests please set sleep_time>= { _MIN_SLEEP_TIME } end set batch_request = call...
def monitor_batch_job( batch_request: BatchProcessRequestSpec, config: Optional[SHConfig] = None, sleep_time: int = _DEFAULT_SLEEP_TIME, analysis_sleep_time: int = _DEFAULT_ANALYSIS_SLEEP_TIME, ) -> DefaultDict[BatchTileStatus, List[dict]]: if sleep_time < _MIN_SLEEP_TIME: raise ValueError(f...
Python
nomic_cornstack_python_v1
import sys set read = lambda -> read line stdin while 1 begin set tuple w h = map int split input set matrix = list comprehension list map int list strip read for _ in range w set ans = list function dfs x y begin set matrix at x at y = 0 set n_x = list 1 1 1 - 1 - 1 - 1 0 0 set n_y = list 0 1 - 1 0 1 - 1 1 - 1 for i...
import sys read = lambda : sys.stdin.readline() while 1: w,h = map(int,input().split()) matrix = [list(map(int,list(read().strip()))) for _ in range(w)] ans = [] def dfs(x,y): matrix[x][y] = 0 n_x = [1, 1, 1,-1,-1,-1, 0, 0] n_y = [0, 1,-1, 0, 1,-1, 1,-1] for i in range...
Python
zaydzuhri_stack_edu_python
function adjust_intervals self begin if begin == 0 and end == 86400 begin return intervals end if begin >= 86399 or end <= 1 or begin >= end begin print string inadequate parameters, try again. return list end set new_intervals = list comment determine first to last relevant interval comment interval: [begin, end, pe...
def adjust_intervals(self) -> list: if self.begin == 0 and self.end == 86400: return self.intervals if self.begin >= 86399 or self.end <= 1 or self.begin >= self.end: print("inadequate parameters, try again.") return [] new_intervals = [] # determine ...
Python
nomic_cornstack_python_v1
function compilation_result self begin return get pulumi self string compilation_result end function
def compilation_result(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "compilation_result")
Python
nomic_cornstack_python_v1
function ticket_configuration self begin return get pulumi self string ticket_configuration end function
def ticket_configuration(self) -> str: return pulumi.get(self, "ticket_configuration")
Python
nomic_cornstack_python_v1
function CMP self value begin call _compare value string A end function
def CMP(self, value): self._compare(value, 'A')
Python
nomic_cornstack_python_v1
function format_date epocsecs begin set t = call gmtime epocsecs comment rolling own, as time.strftime is in part locale-dependent (e.g. '%a' for short weekday) set s = split string Mon Tue Wed Thu Fri Sat Sun at tm_wday + string , set s = s + string %02d % tuple tm_mday set s = s + split string Jan Feb Mar Apr May Jun...
def format_date(epocsecs): t = time.gmtime(epocsecs) # rolling own, as time.strftime is in part locale-dependent (e.g. '%a' for short weekday) s = "Mon Tue Wed Thu Fri Sat Sun".split()[t.tm_wday] + ", " s += "%02d " % (t.tm_mday,) s += "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()[t.tm_m...
Python
nomic_cornstack_python_v1
function initiate_stocktaking chunk_size=10 begin set stocktake_qs = objects comment Make sure that there is no stock-taking in progress if not count filter locked=false == 0 begin raise call APIException string Stock-taking already in progress. end set stocktake_obj = call create comment Order products by category, so...
def initiate_stocktaking(chunk_size=10): stocktake_qs = models.Stocktake.objects # Make sure that there is no stock-taking in progress if not stocktake_qs.filter(locked=False).count() == 0: raise exceptions.APIException('Stock-taking already in progress.') stocktake_obj = stocktake_qs.create() ...
Python
nomic_cornstack_python_v1
function geometric_seq numlist begin set a = true while true begin for i in numlist begin if string i in numlist begin return string Invalid Value set a = false end end end while a == true begin for i in range length numlist begin while true begin if 0 in numlist begin return false end else if 0 not in numlist begin if...
def geometric_seq(numlist): a = True while True: for i in numlist: if str(i) in numlist: return "Invalid Value" a = False while a == True: for i in range(len(numlist)): while True: if 0 in numlist: re...
Python
zaydzuhri_stack_edu_python
class Polygon begin function __init__ self no_of_sides begin set n = no_of_sides set sides = list comprehension 0 for i in range no_of_sides end function function inputSides self begin set sides = list comprehension decimal call raw_input string Enter side + string i + 1 + string : for i in range n end function end cla...
class Polygon: def __init__(self, no_of_sides): self.n = no_of_sides self.sides = [0 for i in range(no_of_sides)] def inputSides(self): self.sides = [float(raw_input("Enter side " + str(i+1) + " : ")) for i in range(self.n)]
Python
zaydzuhri_stack_edu_python
async function ContainerManagerConfig self type_ begin string type_ : str Returns -> typing.Mapping[str, str] comment map input types to rpc msg set _params = dictionary set msg = dictionary type=string Provisioner request=string ContainerManagerConfig version=3 params=_params set _params at string type = type_ set rep...
async def ContainerManagerConfig(self, type_): ''' type_ : str Returns -> typing.Mapping[str, str] ''' # map input types to rpc msg _params = dict() msg = dict(type='Provisioner', request='ContainerManagerConfig', version=3, ...
Python
jtatman_500k
function show type img begin comment print(img) image show type img call waitKey end function
def show(type,img): # print(img) cv2.imshow(type, img) cv2.waitKey()
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import r2_score
Python
zaydzuhri_stack_edu_python
async function dump_nbt_async root path options=dict begin set loop = call get_running_loop await call run_in_executor none dump_nbt root path options end function
async def dump_nbt_async( root: NbtCompound, path: Path, options: Dict[str, Any] = {}, ): loop = asyncio.get_running_loop() await loop.run_in_executor(None, dump_nbt, root, path, options)
Python
nomic_cornstack_python_v1
function xlsx_part self xlsx_part begin string Set the related |EmbeddedXlsxPart| to *xlsx_part*. Assume one does not already exist. set rId = call relate_to xlsx_part PACKAGE set externalData = call get_or_add_externalData set rId = rId end function
def xlsx_part(self, xlsx_part): """ Set the related |EmbeddedXlsxPart| to *xlsx_part*. Assume one does not already exist. """ rId = self._chart_part.relate_to(xlsx_part, RT.PACKAGE) externalData = self._chartSpace.get_or_add_externalData() externalData.rId = rId
Python
jtatman_500k
import random set lotto = list while length lotto < 6 begin set number = random integer 1 45 if number not in lotto begin append lotto number end end sort lotto print string 행운의 로또번호: lotto
import random lotto = [] while len(lotto)<6: number = random.randint(1, 45) if number not in lotto: lotto.append(number) lotto.sort() print('행운의 로또번호:', lotto)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python2 function rotate_word word rotation begin set new_word = string for x in word begin set new_word = new_word + character ordinal x + rotation end end function
#!/usr/bin/python2 def rotate_word(word, rotation): new_word = '' for x in word: new_word = new_word + chr(ord(x)+rotation)
Python
zaydzuhri_stack_edu_python
function _ssh_connect begin set client = call SSHClient call load_system_host_keys call set_missing_host_key_policy WarningPolicy call connect keyword SSH_CONFIG yield client close client end function
def _ssh_connect(): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy) client.connect(**SSH_CONFIG) yield client client.close()
Python
nomic_cornstack_python_v1
comment set1 = {3,2,6,4,1,3,6} comment # set1 = {3,2,6,4,1,3,6,[2]} #集合中的元素只能是不可变类型 comment print(set1) comment 去除列表中重复的元素 comment lst = [1,2,2,3,3,5,6,3] comment print(set(lst)) comment 集合增加 comment set1 = {1,2} comment # # set1.add(3) comment # set2 = {2,3} comment # set1.update(set2) comment set1.clear() comment pri...
# set1 = {3,2,6,4,1,3,6} # # set1 = {3,2,6,4,1,3,6,[2]} #集合中的元素只能是不可变类型 # print(set1) #去除列表中重复的元素 # lst = [1,2,2,3,3,5,6,3] # print(set(lst)) #集合增加 # set1 = {1,2} # # # set1.add(3) # # set2 = {2,3} # # set1.update(set2) # set1.clear() # print(set1) # print(dir(set1)) # lst = [1,2] # help(lst.remove) #集合数学运算 # set1 ...
Python
zaydzuhri_stack_edu_python
function get_waveform_for_arid arid conn tbefore=0.5 tafter=4.5 begin set ret = array set query = string select return ret end function
def get_waveform_for_arid(arid, conn, tbefore=0.5, tafter=4.5): ret = np.array() query = """ select """ return ret
Python
nomic_cornstack_python_v1
function transform self *args **kwargs begin return transform pipeline *args keyword kwargs end function
def transform(self, *args, **kwargs): return self.pipeline.transform(*args, **kwargs)
Python
nomic_cornstack_python_v1
function _parse_birth_date self player_info begin set date = call attr string data-birth set attribute self string _birth_date date end function
def _parse_birth_date(self, player_info): date = player_info('span[itemprop="birthDate"]').attr('data-birth') setattr(self, '_birth_date', date)
Python
nomic_cornstack_python_v1
function get_last_update self begin set last_update = call getmtime parent_filepath return last_update end function
def get_last_update(self): last_update = os.path.getmtime(self.parent_filepath) return last_update
Python
nomic_cornstack_python_v1
function parse_opts argv begin set options = dict string limit 3 ; string output none ; string lastname none ; string debug false ; string cache true comment limit fo pages to fetch in a single area try begin set tuple opts args = call getopt argv string dhl:o: list string limit= string output= end except GetoptError b...
def parse_opts(argv): options = { 'limit': 3, # limit fo pages to fetch in a single area 'output': None, 'lastname': None, 'debug': False, 'cache': True } try: opts, args = getopt.getopt(argv, "dhl:o:", ["limit=", "output="]) except getopt.GetoptError: ...
Python
nomic_cornstack_python_v1
function _invalidate self begin set _nexthop_matrix = none set _distance_matrix = none end function
def _invalidate(self): self._nexthop_matrix = None self._distance_matrix = None
Python
nomic_cornstack_python_v1
function test_users_params self begin set url = reverse string users_query assert equal url call unicode string /pwdsvc/users/query for pwd_data in pwd_data begin set pwd_data_parts = split pwd_data string : set name = pwd_data_parts at 0 set uid = pwd_data_parts at 2 set gid = pwd_data_parts at 3 set name_query = url ...
def test_users_params(self): url = reverse('users_query') self.assertEqual(url, unicode('/pwdsvc/users/query')) for pwd_data in USER_DATA.pwd_data: pwd_data_parts = pwd_data.split(':') name = pwd_data_parts[0] uid = pwd_data_parts[2] gid = pwd_dat...
Python
nomic_cornstack_python_v1
import random import itertools set PHYSICAL_MEM = 512 * 1024 * 1024 set PAGE_SIZE = 16 * 1024 * 1024 set VIRTUAL_MEM = 1024 * 1024 * 1024 set PROCESS_PAGE_COUNT = VIRTUAL_MEM / PAGE_SIZE set PHYSICAL_PAGE_COUNT = PHYSICAL_MEM / PAGE_SIZE set MAX_PROCESS_COUNT = 20 set PROCESSES_INCREMENT = 20 set PROCESS_ALIVE_MEAN = 5...
import random import itertools PHYSICAL_MEM = 512*1024*1024 PAGE_SIZE = 16*1024*1024 VIRTUAL_MEM = 1024*1024*1024 PROCESS_PAGE_COUNT = VIRTUAL_MEM / PAGE_SIZE PHYSICAL_PAGE_COUNT = PHYSICAL_MEM / PAGE_SIZE MAX_PROCESS_COUNT = 20 PROCESSES_INCREMENT = 20 PROCESS_ALIVE_MEAN = 500 PROCESS_ALIVE_VARIANCE = 150 TIME = 10...
Python
zaydzuhri_stack_edu_python
function prior_to_xarray self begin string Convert prior samples to xarray. return call dict_to_dataset dictionary comprehension k : call expand_dims v 0 for tuple k v in items prior library=pymc3 coords=coords dims=dims end function
def prior_to_xarray(self): """Convert prior samples to xarray.""" return dict_to_dataset( {k: np.expand_dims(v, 0) for k, v in self.prior.items()}, library=self.pymc3, coords=self.coords, dims=self.dims, )
Python
jtatman_500k
function lru_cache_factory hash_func begin decorator wraps lru_cache function mlru_cache *args **kwargs begin string An lru cache for mutable objects function _mlru_cache func begin string the actual decorator decorator least recent cache *args keyword kwargs function cached_func *args3 **kwargs3 begin string calls cac...
def lru_cache_factory(hash_func): @wraps(lru_cache) def mlru_cache(*args, **kwargs): """ An lru cache for mutable objects """ def _mlru_cache(func): """the actual decorator""" @lru_cache(*args, **kwargs) def cached_func(*args3, **kwargs3): ...
Python
nomic_cornstack_python_v1
from tkinter import * import requests from PIL import Image , ImageTk from io import BytesIO set root = call Tk title root string Online Image Viewer - Open online Images! call geometry string 600x500 call pack side=TOP set label = call Label root bg=string white call pack side=string top set var = call StringVar set e...
from tkinter import * import requests from PIL import Image, ImageTk from io import BytesIO root = Tk() root.title('Online Image Viewer - Open online Images!') root.geometry('600x500') Label(root, text='', width=22, height=9).pack(side=TOP) label = Label(root, bg='white') label.pack(side='top') var = StringVar() en...
Python
zaydzuhri_stack_edu_python
string https://www.codewars.com/kata/count-of-positives-slash-sum-of-negatives/train/python Count positive numbers, and sum negatives. function count_sheep n begin return join string generator expression string { i } sheep... for i in range 1 n + 1 end function import unittest class TestStringMethods extends TestCase ...
''' https://www.codewars.com/kata/count-of-positives-slash-sum-of-negatives/train/python Count positive numbers, and sum negatives. ''' def count_sheep(n): return ''.join(f"{i} sheep..." for i in range(1,n+1)) import unittest class TestStringMethods(unittest.TestCase): def test(self): self.assertEqual...
Python
zaydzuhri_stack_edu_python
function widgets std_prm begin set widgets = list comment The name widget set textEdit = call QLineEdit call setText std_prm at string name append widgets textEdit comment The input widget set inputWidget = call std_prm at string build method prms std_prm at string slot append widgets inputWidget comment Add the input...
def widgets(std_prm: Parameter) -> List[QWidget]: widgets = [] # The name widget textEdit = QLineEdit() textEdit.setText(std_prm["name"]) widgets.append(textEdit) # The input widget inputWidget = std_prm["build method"](std_prm["build method prms"], std_prm["slo...
Python
nomic_cornstack_python_v1
from lib.generator import generator from time import perf_counter import math function error rank last begin string 计算r_new与r_old差的模,即停止条件 set mysum = sum list map lambda x -> x at 0 - x at 1 ^ 2 zip rank last set mysum = square root mysum return mysum end function function PageRank N step beta=0.8 epsilon=1e-07 begin ...
from lib.generator import generator from time import perf_counter import math def error(rank: list, last: list) -> float: """计算r_new与r_old差的模,即停止条件""" mysum = sum(list(map(lambda x: (x[0]-x[1])**2, zip(rank, last)))) mysum = math.sqrt(mysum) return mysum def PageRank(N: int, step: int, beta=0.8, eps...
Python
zaydzuhri_stack_edu_python
with open string NmodM.txt string r as my_file begin for case in my_file begin set tuple N M = list comprehension integer x for x in split case string , set result = N % M end end
with open("NmodM.txt", "r") as my_file: for case in my_file: N, M = [int(x) for x in case.split(',')] result = N % M
Python
zaydzuhri_stack_edu_python
function add_source_ellipse self begin comment Add ellipse for source within positional uncertainty if plot_source begin set source_colour = if expression stokes == string v then string springgreen else string springgreen set pos = call SkyCoord ra=ra_deg_cont dec=dec_deg_cont unit=string deg set sourcepos = call to_pi...
def add_source_ellipse(self): # Add ellipse for source within positional uncertainty if self.plot_source: source_colour = 'springgreen' if self.stokes == 'v' else 'springgreen' pos = SkyCoord(ra=self.source.ra_deg_cont, dec=self.source.dec_deg_cont, unit='deg') self....
Python
nomic_cornstack_python_v1
function str self begin set P = call _check_valid return get P _name end function
def str(self): P = self._check_valid() return P.get(self._name)
Python
nomic_cornstack_python_v1
class BankAccount begin function __init__ self username balance begin set username = username set balance = balance end function function show_balance self begin print string Balance of { username } 's account is { balance } end function function deposit self amount begin if amount > 0 begin set balance = balance + amo...
class BankAccount: def __init__(self, username, balance): self.username = username self.balance = balance def show_balance(self): print(f"Balance of {self.username}'s account is {self.balance}") def deposit(self, amount): if amount > 0: self.balance += amoun...
Python
flytech_python_25k
function registered_device self registered_device begin set _registered_device = registered_device end function
def registered_device(self, registered_device): self._registered_device = registered_device
Python
nomic_cornstack_python_v1
import timeit import numpy as np from random import randint from decimalClasses.smallDecimal import Decimal from decimalClasses.decimalArray import DecimalArray class HMM begin string class for a Hidden Markov Model function __init__ self *args begin comment all parameters are initialized if length args == 5 begin set ...
import timeit import numpy as np from random import randint from decimalClasses.smallDecimal import Decimal from decimalClasses.decimalArray import DecimalArray class HMM: """class for a Hidden Markov Model""" def __init__(self, *args): if (len(args) == 5): # all parameters are initialized self.obs = args[0] ...
Python
zaydzuhri_stack_edu_python
comment Python中%是什么意思?如何使用? comment 这是一种将其他变量置入字符串特定位置以生成新字符串的操作,比如说: set n = string Aki print string My name is %s % n comment 这段代码首先定义了一个名为n的变量,内容为Aki。然后下方的字符串中有一个%s,他的含义是“这里将被替换成一个新的字符串” comment 用作替换的内容放在字符串后面的%后面,就是那个n。所以最终这个字符串会变成My name is Aki。 comment 字符串中的%后面会附带一个字母,代表着用来替换的变量的类型,比如说 %d 代表着你将替换到此处的变量是一个整数, comm...
# Python中%是什么意思?如何使用? # 这是一种将其他变量置入字符串特定位置以生成新字符串的操作,比如说: n = "Aki" print("My name is %s" % n) # 这段代码首先定义了一个名为n的变量,内容为Aki。然后下方的字符串中有一个%s,他的含义是“这里将被替换成一个新的字符串” # 用作替换的内容放在字符串后面的%后面,就是那个n。所以最终这个字符串会变成My name is Aki。 # 字符串中的%后面会附带一个字母,代表着用来替换的变量的类型,比如说 %d 代表着你将替换到此处的变量是一个整数, # 而 %s 代表着一个字符串。 # 另外,这种操作可以同时将多个变量放进字符串,只需要用括号...
Python
zaydzuhri_stack_edu_python
function calculate text_input begin import socket import multiprocessing set workers = 4 set output = dict set dirtyText = string set checkText = string comment convert text_input into string for entry in text_input begin set dirtyText = dirtyText + entry end comment sanitize dirtyText for char in dirtyText begin if...
def calculate(text_input): import socket import multiprocessing workers = 4 output = {} dirtyText = '' checkText = '' # convert text_input into string for entry in text_input: dirtyText += entry # sanitize dirtyText for char in dirtyText: if char.isalpha(): ...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np set model = sequential add model dense 64 activation=string relu add model dense 64 activation=string relu add model dense 10 activation=string softmax compile optimizer=adam 0.01 loss=string mse metrics=list string mae comment mean squared error comment mean absolute error se...
import tensorflow as tf import numpy as np model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(64, activation='relu')) model.add(tf.keras.layers.Dense(64, activation='relu')) model.add(tf.keras.layers.Dense(10, activation='softmax')) model.compile(optimizer=tf.keras.optimizers.Adam(0.01), loss...
Python
zaydzuhri_stack_edu_python
import pygame from justwar.data.GameElement import GameElement class Bar extends GameElement begin function __init__ self x y begin call __init__ self set x = x set y = y set barShape = call load_image_scaled string bar.png 1.0 set barRect = call Rect tuple x y tuple call get_width call get_height end function function...
import pygame from justwar.data.GameElement import GameElement class Bar(GameElement): def __init__(self, x, y): GameElement.__init__(self) self.x = x self.y = y self.barShape = self.load_image_scaled("bar.png", 1.0) self.barRect = pygame.Rect( (x,y), (self.barShape.get_width(), self.barShape.get_heigh...
Python
zaydzuhri_stack_edu_python