code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import tensorflow as tf if __name__ == string __main__ begin comment 第一个参数为卷积层的输出,ksize提供了过滤器的尺寸,虽然给出的是一个长度为4的一维数组,但是这个数组的第一个和最后一个数必须是1. comment 这意味着池化层的过滤器是不可以跨不同输入样例或者节点矩阵深度的。在实际应用中使用的最多的池化层过滤器尺寸为[1,2,2,1]或者[1,3,3,1] comment strides提供了步长信息,和卷积层中的步长意义是一样的,而且第一维和最后一维也只能为1,这意味着,池化层不能减少节点矩阵的深度或者输入样例的个数 comment padding提供了...
import tensorflow as tf if __name__ == "__main__": #第一个参数为卷积层的输出,ksize提供了过滤器的尺寸,虽然给出的是一个长度为4的一维数组,但是这个数组的第一个和最后一个数必须是1. # 这意味着池化层的过滤器是不可以跨不同输入样例或者节点矩阵深度的。在实际应用中使用的最多的池化层过滤器尺寸为[1,2,2,1]或者[1,3,3,1] # strides提供了步长信息,和卷积层中的步长意义是一样的,而且第一维和最后一维也只能为1,这意味着,池化层不能减少节点矩阵的深度或者输入样例的个数 # padding提供了是否使用全0填充 tf.nn...
Python
zaydzuhri_stack_edu_python
comment Uses python3 import sys from math import inf function get_change m begin comment write your code here set coins = list 1 3 4 set min_number_of_coins = list none * m + 1 set min_number_of_coins at 0 = 0 for i in range 1 m + 1 begin set min_number_of_coins at i = inf for whole_coin in coins begin if i >= whole_co...
# Uses python3 import sys from math import inf def get_change(m): # write your code here coins = [1, 3, 4] min_number_of_coins = [None] * (m + 1) min_number_of_coins[0] = 0 for i in range(1, m + 1): min_number_of_coins[i] = inf for whole_coin in coins: if i >= whole_...
Python
zaydzuhri_stack_edu_python
function rexists self begin comment There are no repositories by default: return call self end function
def rexists(self): # There are no repositories by default: return _rexists_map[self._func_rexists](self)
Python
nomic_cornstack_python_v1
set x = integer input string Enter celsius degree : print x string (C) = x * 1.8 + 32 string (F)
x = int(input('Enter celsius degree : ')) print(x,' (C) = ',x * 1.8 + 32,' (F)')
Python
zaydzuhri_stack_edu_python
import time class BruteForceLCS begin set comp = 0 function lcs self str1 str2 begin set start = time set size = length str1 - 1 set m = 1 ? size - 1 set maxLen = 0 set longest = string set step = - 1 for i in range m 0 step begin set sub = call getSubString i str1 set isSeq = call isSubSeq sub str2 if isSeq begin if ...
import time class BruteForceLCS: comp = 0 def lcs(self, str1, str2): start = time.time() size = len(str1) - 1 m = (1 << size) - 1 maxLen = 0 longest = "" step = -1 for i in range(m, 0, step): sub = self.getSubString(i, str1) isSeq...
Python
zaydzuhri_stack_edu_python
function trans_matrix_inv m begin set was2d = false if shape at 1 == 3 begin set was2d = true set m = call asarray list list 1.0 0.0 0.0 0.0 list 0.0 m at tuple 0 0 m at tuple 0 1 m at tuple 0 2 list 0.0 m at tuple 1 0 m at tuple 1 1 m at tuple 1 2 list 0.0 0.0 0.0 1.0 float64 end set trans = m at tuple slice 0 : 3 : ...
def trans_matrix_inv(m:numpy.ndarray): was2d = False if m.shape[1] == 3: was2d = True m = numpy.asarray([ [1.0, 0.0, 0.0, 0.0], [0.0, m[0,0], m[0,1], m[0,2]], [0.0, m[1,0], m[1,1], m[1,2]], [0.0, 0.0, 0.0, 1.0]], numpy.float64) trans = m[0:3,3]...
Python
nomic_cornstack_python_v1
function setUp self begin set output = call StringIO set saved_stdout = stdout set stdout = output end function
def setUp(self): self.output = StringIO() self.saved_stdout = sys.stdout sys.stdout = self.output
Python
nomic_cornstack_python_v1
function edge_refine_triangulation_by_triangles self triangles begin string return points defining a refined triangulation obtained by bisection of all edges in the triangulation that are associated with the triangles in the list of indices provided. Notes ----- The triangles are here represented as a single index. The...
def edge_refine_triangulation_by_triangles(self, triangles): """ return points defining a refined triangulation obtained by bisection of all edges in the triangulation that are associated with the triangles in the list of indices provided. Notes ----- The triang...
Python
jtatman_500k
function to_dict self begin set result = dict for tuple attr _ in call iteritems swagger_types begin set value = get attribute self attr if is instance value list begin set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value end else if has attribute value ...
def to_dict(self): result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value ...
Python
nomic_cornstack_python_v1
from flaskproject import create_application , crypt from flaskproject.database import database from flaskproject.config import Config string Build is used to initially create the applications database, it doesn't technically do anything else except build the database to the model. This is useful while testing and can b...
from flaskproject import create_application, crypt from flaskproject.database import database from flaskproject.config import Config """ Build is used to initially create the applications database, it doesn't technically do anything else except build the database to the model. This is useful while testing and can be ...
Python
zaydzuhri_stack_edu_python
function send_discussion_notification self site request=none begin set context_dict = dict if request is not none begin set context_dict = call RequestContext request context_dict end update context_dict dict string user user ; string submission submission ; string comment comment ; string date_submitted date_submitte...
def send_discussion_notification(self, site, request=None): context_dict = {} if request is not None: context_dict = RequestContext(request, context_dict) context_dict.update({ 'user': self.user, 'submission': self.submission, 'comment': self.comme...
Python
nomic_cornstack_python_v1
function plot_mpdf self param margin plot_type Nsplit=50 **kwargs begin set title = capitalize family + string Copula PDF comment We retrieve the univariate marginal distribution from the list set univariate1 = margin at 0 at string distribution set univariate2 = margin at 1 at string distribution set bounds = list - 3...
def plot_mpdf(self, param, margin, plot_type, Nsplit=50, **kwargs): title = self.family.capitalize() + " Copula PDF" # We retrieve the univariate marginal distribution from the list univariate1 = margin[0]["distribution"] univariate2 = margin[1]["distribution"] ...
Python
nomic_cornstack_python_v1
function increment d1 scale d2 begin for tuple f v in items d2 begin set d1 at f = get d1 f 0 + v * scale end end function
def increment(d1, scale, d2): for f, v in d2.items(): d1[f] = d1.get(f, 0) + v * scale
Python
nomic_cornstack_python_v1
function __init__ __self__ state begin set __self__ string state state end function
def __init__(__self__, *, state: str): pulumi.set(__self__, "state", state)
Python
nomic_cornstack_python_v1
function _do_load_page self **kwargs begin set _return = false set _attributes = call do_load_page self keyword kwargs call handler_block _lst_handler_id at 3 call set_active _attributes at string family_id call handler_unblock _lst_handler_id at 3 if _attributes at string hazard_rate_method_id == 2 begin call handler_...
def _do_load_page(self, **kwargs): _return = False _attributes = AssessmentInputs.do_load_page(self, **kwargs) self.cmbFamily.handler_block(self._lst_handler_id[3]) self.cmbFamily.set_active(_attributes['family_id']) self.cmbFamily.handler_unblock(self._lst_handler_id[3]) ...
Python
nomic_cornstack_python_v1
function run_nfp_service self context resource_data begin set msg = string ConfigScriptRpcManager received Create Heat request. debug msg set arg_dict = dict string context context ; string resource_data resource_data set ev = call new_event id=CREATE_NFP_SERVICE_EVENT data=arg_dict key=none call post_event ev end func...
def run_nfp_service(self, context, resource_data): msg = ("ConfigScriptRpcManager received Create Heat request.") LOG.debug(msg) arg_dict = {'context': context, 'resource_data': resource_data} ev = self.sc.new_event(id=const.CREATE_NFP_SERVICE_EVENT, ...
Python
nomic_cornstack_python_v1
function main begin print string Host: call gethostname print string Results directory: REPLICATED_RESULTS_DIR print string Selected forecasters: SELECTED_FORECASTERS print string Selected datasets: DATASETS comment import meta data set meta = call load_metadata DATADIR comment dictionary of forecasting horizons and se...
def main(): print("Host: ", socket.gethostname()) print("Results directory: ", REPLICATED_RESULTS_DIR) print("Selected forecasters: ", SELECTED_FORECASTERS) print("Selected datasets: ", DATASETS) # import meta data meta = load_metadata(DATADIR) # dictionary of forecasting horizons and seas...
Python
nomic_cornstack_python_v1
import sys function switch_count engines searches begin set switches = 0 set unused = set engines for s in searches begin if s in unused begin remove unused s end if length unused == 0 begin set switches = switches + 1 set unused = set engines remove unused s end end return string switches end function function do_one_...
import sys def switch_count(engines, searches): switches = 0 unused = set(engines) for s in searches: if s in unused: unused.remove(s) if len(unused) == 0: switches += 1 unused = set(engines) unused.remove(s) return str(switches) def do_o...
Python
zaydzuhri_stack_edu_python
import camelot from PyPDF2 import PdfFileReader import sys import os comment from pprint import pprint set filePath = argv at 1 set whereToSave = argv at 2 set fileName = argv at 3 if fileName at slice length fileName - 5 : : == string .docx begin call system string soffice --headless --convert-to pdf --outdir + stri...
import camelot from PyPDF2 import PdfFileReader import sys import os #from pprint import pprint filePath = sys.argv[1] whereToSave = sys.argv[2] fileName = sys.argv[3] if(fileName[len(fileName) - 5:] == '.docx'): os.system("soffice --headless --convert-to pdf --outdir " + "uploaded/tempPdf " +filePath) filePat...
Python
zaydzuhri_stack_edu_python
function __local_mt soup begin set news = list set ns = call get_ns string localMT set anchors = find all soup string a class_=string top10titulo for a in anchors begin set title = string set link = url + a at string href append news dictionary title=title link=link end return news end function
def __local_mt(soup): news = [] ns = get_ns('localMT') anchors = soup.find_all('a', class_='top10titulo') for a in anchors: title = a.string link = ns.url + a['href'] news.append(dict(title=title, link=link)) return news
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import os comment Подключим необходимые библиотеки. from PIL import Image , ImageDraw import json class HandlImage extends object begin function __init__ self path begin comment Открываем изображение. set image = open path comment Создаем инструмент для рисования. set draw = call Draw imag...
# -*- coding: utf-8 -*- import os from PIL import Image, ImageDraw #Подключим необходимые библиотеки. import json class HandlImage(object): def __init__(self, path): self.image = Image.open(path) #Открываем изображение. self.draw = ImageDraw.Draw(self.image) #Создаем инструмент для рисования. ...
Python
zaydzuhri_stack_edu_python
comment lect 3 task 1 print string ##lect 3 task 1 set y = input string input number of month: set y = integer y comment fuction season function season x begin if x in tuple 12 1 2 begin set ses = string wither end else if x in tuple 3 4 5 begin set ses = string sprint end else if x in tuple 6 7 8 begin set ses = strin...
##lect 3 task 1 print ('##lect 3 task 1') y= input ('input number of month:') y=int(y) #fuction season def season(x): if (x in (12,1,2)): ses='wither' elif (x in (3,4,5)): ses='sprint' elif (x in (6,7,8)): ses='summer' elif (x in (9,10,11)): ses='authumn' return ses ...
Python
zaydzuhri_stack_edu_python
function accuracy output target topk=tuple 1 begin set res = 0 set target = call numpy set output = call numpy set total = length target at tuple slice : : 0 for i in range total begin for j in range length output at tuple 0 slice : : begin if output at tuple i j > 0.25 begin set output at tuple i j = 1 end else b...
def accuracy(output, target, topk=(1,)): res = 0 target = target.cpu().numpy() output = output.cpu().numpy() total = len(target[:,0]) for i in range(total): for j in range(len(output[0,:])): if output[i,j] > 0.25: output[i,j] = 1 else: ...
Python
nomic_cornstack_python_v1
string Student Name: Marcelle Noukimi Institution: Kennesaw State University College: College of Computing and Software Engineering Department: Department of Computer Science Professor: Dr. Sarah North Course Code & Title: CS 4308 Concepts of Programming Languages Section 01 Fall 2021 Date: October 13, 2021 Assignment ...
""" Student Name: Marcelle Noukimi Institution: Kennesaw State University College: College of Computing and Software Engineering Department: Department of Computer Science Professor: Dr. Sarah North Course Code & Title: CS 4308 Concepts of Programming Languages Section 01 Fall 2021 Date: Oct...
Python
zaydzuhri_stack_edu_python
import numpy as np import pylab as plb import scipy.signal as sgn comment функция вывод передаточной функции для различных N function differentN s N begin comment Выводим коэффициенты set b_1 = call hilbert s N comment передаточн фкц set tuple w_1 h_1 = call freqz b_1 figure comment модуль нужен т.к.вещ число plot w_1 ...
import numpy as np import pylab as plb import scipy.signal as sgn # функция вывод передаточной функции для различных N def differentN(s,N): # Выводим коэффициенты b_1=sgn.hilbert(s,N) w_1, h_1 = sgn.freqz(b_1) #передаточн фкц plb.figure() plb.plot(w_1/np.pi,abs(h_1))#модуль нужен т.к.вещ число...
Python
zaydzuhri_stack_edu_python
function double_gauss_spotfinder img_data g1=2 g2=10 thresh=1.5 begin set blured_img = call gaussian_filter img_data g1 set background = call gaussian_filter img_data g2 set spots = call get_spots blured_img background thresh end function
def double_gauss_spotfinder(img_data, g1=2, g2=10, thresh=1.5): blured_img = ndi.filters.gaussian_filter(img_data, g1) background = ndi.filters.gaussian_filter(img_data, g2) spots = get_spots(blured_img, background, thresh)
Python
nomic_cornstack_python_v1
set a = 10 set b = 20 set c = a + b print c
a=10 b=20 c=a+b print(c)
Python
zaydzuhri_stack_edu_python
function create_review_form begin set Review_form = call ReviewForm return call render_template string review_form.html form=Review_form end function
def create_review_form(): Review_form = ReviewForm() return render_template("review_form.html", form=Review_form)
Python
nomic_cornstack_python_v1
function share_axis ax0 ax1 which begin if call _version_predates mpl string 3.5 begin set group = call get attribute ax0 string get_shared_ { which } _axes join group ax1 ax0 end else begin call get attribute ax1 string share { which } ax0 end end function
def share_axis(ax0, ax1, which): if _version_predates(mpl, "3.5"): group = getattr(ax0, f"get_shared_{which}_axes")() group.join(ax1, ax0) else: getattr(ax1, f"share{which}")(ax0)
Python
nomic_cornstack_python_v1
comment THE FOLLOWING IS MY PRACTICE WITH SOME FUNCTIONS USING PYTHON function main begin call bigOrSmallString string hi lol call oddOrEvenString string hi lol set listy = list 1 3 6 2 5 8 4 9 call medianOfArray listy call sumList listy call vowelCount string onomatopoeia call initials string Thalia Elizabeth Santamar...
# THE FOLLOWING IS MY PRACTICE WITH SOME FUNCTIONS USING PYTHON def main(): bigOrSmallString("hi lol") oddOrEvenString("hi lol") listy = [1, 3, 6, 2, 5, 8, 4, 9] medianOfArray(listy) sumList(listy) vowelCount("onomatopoeia") initials("Thalia Elizabeth Santamaria Parrales") # Bon...
Python
zaydzuhri_stack_edu_python
function __permuteReactionData self rxnData begin set permutedValues = call permutation list values rxnData set permutedRxnData = dict for tuple value rxn in zip permutedValues list keys rxnData begin set permutedRxnData at rxn = value end return permutedRxnData end function
def __permuteReactionData(self, rxnData): permutedValues = np.random.permutation(list(rxnData.values())) permutedRxnData = {} for value, rxn in zip(permutedValues, list(rxnData.keys())): permutedRxnData[rxn] = value return permutedRxnData
Python
nomic_cornstack_python_v1
function __contains__ self other begin return other in children or any generator expression other in child for child in children end function
def __contains__(self, other) -> bool: return other in self.children or any(other in child for child in self.children)
Python
nomic_cornstack_python_v1
function _setup_legend self begin set leg = call TLegend *self.legpos call SetFillColor 0 call SetFillStyle 0 call SetTextFont 42 call SetTextSize 0.035 call SetBorderSize 0 return leg end function
def _setup_legend(self): leg = r.TLegend(*self.legpos) leg.SetFillColor(0) leg.SetFillStyle(0) leg.SetTextFont(42) leg.SetTextSize(0.035) leg.SetBorderSize(0) return leg
Python
nomic_cornstack_python_v1
function atom_loop self selection=none str_id=none model_num=none mol_name_flag=false res_num_flag=false res_name_flag=false atom_num_flag=false atom_name_flag=false element_flag=false pos_flag=false mol_index_flag=false index_flag=false ave=false begin comment Check that the structure is loaded. if not length structur...
def atom_loop(self, selection=None, str_id=None, model_num=None, mol_name_flag=False, res_num_flag=False, res_name_flag=False, atom_num_flag=False, atom_name_flag=False, element_flag=False, pos_flag=False, mol_index_flag=False, index_flag=False, ave=False): # Check that the structure is loaded. if not ...
Python
nomic_cornstack_python_v1
function delitelji stevilo begin set d = list for i in range 1 stevilo begin if stevilo % i == 0 begin append d i end end return d end function function vsota seznam begin set v = 0 for stevilka in seznam begin set v = v + stevilka end return v end function function popolno stev begin return stev == call vsota call de...
def delitelji(stevilo): d = [] for i in range(1, stevilo): if stevilo % i == 0: d.append(i) return d def vsota(seznam): v = 0 for stevilka in seznam: v += stevilka return v def popolno(stev): return stev == vsota(delitelji(stev)) def vsa_popolna(n): s = ...
Python
zaydzuhri_stack_edu_python
function TransferToWindow self begin return true end function
def TransferToWindow(self): return True
Python
nomic_cornstack_python_v1
function product_of_odd_numbers numbers product=1 begin if not numbers begin return round product end else if 10 < numbers at 0 < 20 and numbers at 0 % 2 != 0 begin return call product_of_odd_numbers numbers at slice 1 : : product * numbers at 0 end else begin return call product_of_odd_numbers numbers at slice 1 : ...
def product_of_odd_numbers(numbers, product=1): if not numbers: return round(product) elif 10 < numbers[0] < 20 and numbers[0] % 2 != 0: return product_of_odd_numbers(numbers[1:], product * numbers[0]) else: return product_of_odd_numbers(numbers[1:], product) # Example usage numbers...
Python
jtatman_500k
with open string /Users/annallanza/Documents/Uni/4t/C/Laboratori/Practica 4/part2/CRL.txt as f begin for linea in f begin set linea = strip linea set linea = split linea string : if linea at 0 == string Serial Number begin set cont = cont + 1 end end end print cont
with open('/Users/annallanza/Documents/Uni/4t/C/Laboratori/Practica 4/part2/CRL.txt') as f: for linea in f: linea = linea.strip() linea = linea.split(':') if linea[0] == "Serial Number": cont = cont + 1 print(cont)
Python
zaydzuhri_stack_edu_python
function test_play_solos_method begin pass end function
def test_play_solos_method(): pass
Python
nomic_cornstack_python_v1
function delete_keys_from_dict self orig_dict keys_whitelist begin for k in list keys orig_dict begin if k not in keys_whitelist begin del orig_dict at k end end for v in values orig_dict begin if is instance v dict begin call delete_keys_from_dict v keys_whitelist end end return orig_dict end function
def delete_keys_from_dict(self, orig_dict, keys_whitelist): for k in list(orig_dict.keys()): if k not in keys_whitelist: del orig_dict[k] for v in orig_dict.values(): if isinstance(v, dict): self.delete_keys_from_dict(v, keys_whitelist) r...
Python
nomic_cornstack_python_v1
from pystyle import Colorate , Colors from pycenter import center from os import name , system import random function clear begin call system if expression name == string nt then string cls else string clear end function if name == string nt begin call system string title RandomPw & mode 190, 40 end set banner = string...
from pystyle import Colorate, Colors from pycenter import center from os import name, system import random def clear(): system("cls" if name == 'nt' else "clear") if name =='nt': system("title RandomPw & mode 190, 40 ") banner = """\n ██▀███ ▄▄▄ ███▄ █ ▓█████▄ ▒█████ ███▄...
Python
zaydzuhri_stack_edu_python
function experiment args begin comment Define experiment parameters set list seed tanl model_er obs_un obs_dim = args comment state dimension set sys_dim = 10 comment forcing set f = 8 comment number of analyses set nanl = 110 comment tlm integration step size (nonlinear step size is half) set h = 0.01 set nl_step = 0....
def experiment(args): #################################################################################################################### # Define experiment parameters [seed, tanl, model_er, obs_un, obs_dim] = args # state dimension sys_dim = 10 # forcing f = 8 # number of analyses...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding:utf-8 -*- string read.py set f = open string content string r comment read的一个参数是设置读取的大小,防止读取大文件全部放入内存中挂掉 set content = read f 200 print content close f
#!/usr/bin/env python # -*- coding:utf-8 -*- 'read.py' f = open('content','r') #read的一个参数是设置读取的大小,防止读取大文件全部放入内存中挂掉 content = f.read(200) print(content) f.close();
Python
zaydzuhri_stack_edu_python
function load_interpolator self begin set filename = string interpolator_ { source } _V { version } set filepath = join path GRIDS_PATH string sources source string interpolator filename call printv string Loading interpolator: { filepath } set interpolator = load pickle open filepath string rb end function
def load_interpolator(self): filename = f'interpolator_{self.source}_V{self.version}' filepath = os.path.join(GRIDS_PATH, 'sources', self.source, 'interpolator', filename) self.printv(f'Loading interpolator: {filepath}') self.interpolator = pickle.load(ope...
Python
nomic_cornstack_python_v1
function save self begin if _backingstore is none begin warning string backingstore cannot be None return false end if not is instance _backingstore str begin warning string backingstore needs to be a string return false end set data = dumps _store try begin write open _backingstore string w data end except Environment...
def save(self): if self._backingstore is None: log.warning('backingstore cannot be None') return False if not isinstance(self._backingstore, str): log.warning('backingstore needs to be a string') return False data = json.dumps(self._store) ...
Python
nomic_cornstack_python_v1
import requests import math import time set distance = 1000 function translate value leftMin leftMax rightMin rightMax begin set leftspan = leftMax - leftMin set rightspan = rightMax - rightMin set valuescaled = decimal value - leftMin / decimal leftspan return rightMin + valuescaled * rightspan end function for i in r...
import requests import math import time distance = 1000 def translate(value, leftMin, leftMax, rightMin, rightMax): leftspan = leftMax-leftMin rightspan = rightMax-rightMin valuescaled = float(value-leftMin)/float(leftspan) return rightMin + (valuescaled*rightspan) for i in range(0, distance+...
Python
zaydzuhri_stack_edu_python
comment import MySQLdb import sqlite3 import datetime set __author__ = string Shanshan set db_name = string Crawler_apple_pub function save_itunes_categories conn begin print string Start to load categories set f = open string ./itunes_categories.txt set cates = list for line in f begin set eles = split line string =>...
# import MySQLdb import sqlite3 import datetime __author__ = 'Shanshan' db_name='Crawler_apple_pub' def save_itunes_categories(conn): print('Start to load categories') f= open("./itunes_categories.txt") cates=[] for line in f: eles=line.split('=>') code=eles[0].strip() subcate...
Python
zaydzuhri_stack_edu_python
function test_simple_forbidden self begin set wisdom = call Knowledge for i in range 4 begin for j in range i begin call set_forbidden i j call set_forbidden j i end end set result = call run_fges string ../data/linear_1.txt knowledge=wisdom assert length edges == 0 end function
def test_simple_forbidden(self): wisdom = Knowledge() for i in range(4): for j in range(i): wisdom.set_forbidden(i, j) wisdom.set_forbidden(j, i) result = run_fges("../data/linear_1.txt", knowledge=wisdom) assert len(result['graph'].edges) == 0
Python
nomic_cornstack_python_v1
class Stack begin function __init__ self begin set node = list set count = 0 end function function sempty self begin return count == 0 end function function push self val begin append node val set count = count + 1 end function function pop self begin set count = count - 1 return pop node end function end class class ...
class Stack: def __init__(self): self.node = [] self.count = 0 def sempty(self): return self.count == 0 def push(self,val): self.node.append(val) self.count += 1 def pop(self): self.count -= 1 return self.node.pop() class Queue: def __init__(s...
Python
zaydzuhri_stack_edu_python
import random import afr.entity from afr.entitycomponent import EntityComponent class Fighter extends EntityComponent begin string Fighters can engage in combat with other entities. function __init__ self strength team begin string Create a fighter with strength on team. team is an arbitrary identifying string. set str...
import random import afr.entity from afr.entitycomponent import EntityComponent class Fighter(EntityComponent): """Fighters can engage in combat with other entities.""" def __init__(self, strength, team): """Create a fighter with strength on team. team is an arbitrary identifying string. ...
Python
zaydzuhri_stack_edu_python
string fam = ['David', 'Ann', 'Joe', 'Meg'] print('Test of equality:') for member in fam: if member == 'David': #checking for equality is case sensitive print(member.upper()) else: print(member.lower()) print(' Test of inequality:') for member in fam: if member != 'Joe': print(member.upper()) else: print(member.lower()...
"""fam = ['David', 'Ann', 'Joe', 'Meg'] print('Test of equality:') for member in fam: if member == 'David': #checking for equality is case sensitive print(member.upper()) else: print(member.lower()) print('\nTest of inequality:') for member in fam: if member != 'Joe': print(member.upper()) else: print(mem...
Python
zaydzuhri_stack_edu_python
for i in range N begin set ans = ans + s end print ans
for i in range(N): ans += s print(ans)
Python
zaydzuhri_stack_edu_python
function test_speccable self begin assert true call speccable method1 assert false call speccable __init__ assert false call speccable param end function
def test_speccable(self): self.assertTrue(ISpec.speccable(TestClass.method1)) self.assertFalse(ISpec.speccable(TestClass.__init__)) self.assertFalse(ISpec.speccable(TestClass.param))
Python
nomic_cornstack_python_v1
function profile_norm self name logemin=none logemax=none reoptimize=false xvals=none npts=none fix_shape=true savestate=true **kwargs begin string Profile the normalization of a source. Parameters ---------- name : str Source name. reoptimize : bool Re-optimize free parameters in the model at each point in the profile...
def profile_norm(self, name, logemin=None, logemax=None, reoptimize=False, xvals=None, npts=None, fix_shape=True, savestate=True, **kwargs): """Profile the normalization of a source. Parameters ---------- name : str Source name. ...
Python
jtatman_500k
function parse source no_location=false experimental_fragment_variables=false begin string Given a GraphQL source, parse it into a Document. Throws GraphQLError if a syntax error is encountered. By default, the parser creates AST nodes that know the location in the source that they correspond to. The `no_location` opti...
def parse( source: SourceType, no_location=False, experimental_fragment_variables=False ) -> DocumentNode: """Given a GraphQL source, parse it into a Document. Throws GraphQLError if a syntax error is encountered. By default, the parser creates AST nodes that know the location in the source that t...
Python
jtatman_500k
function dist_matrix x L begin comment Computation of the squared distances between the clusters # comment centroids and the lines # comment input ## comment x[:3*(o+1),:K] : float : centroids coordinates array comment L[:N,:1+2*3] : float : lines array comment L[:,0] --> times comment L[:,1:4]--> feature points commen...
def dist_matrix(x,L): ################################################################# # Computation of the squared distances between the clusters # # centroids and the lines # ################################################################# ## input ## # x[:3*(o+1),:K] : float : centroids coordinat...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment @Date : 2017年2月9日 13:03:11 comment @Author : Your Name (you@example.org) comment @Version : $id$ import sys import json call reload sys call setdefaultencoding string utf-8 set fr = open string result.txt string r set fw = open string result.json string w set address = list set na...
# -*- coding: utf-8 -*- # @Date : 2017年2月9日 13:03:11 # @Author : Your Name (you@example.org) # @Version : $id$ import sys import json reload(sys) sys.setdefaultencoding('utf-8') fr = open("result.txt",'r') fw = open("result.json",'w') address = [] name = [] longitude = [] latitude = [] count = 0 for line in fr:...
Python
zaydzuhri_stack_edu_python
function DecoratorMixin decorator begin string Converts a decorator written for a function view into a mixin for a class-based view. :: LoginRequiredMixin = DecoratorMixin(login_required) class MyView(LoginRequiredMixin): pass class SomeView(DecoratorMixin(some_decorator), DecoratorMixin(something_else)): pass class Mi...
def DecoratorMixin(decorator): """ Converts a decorator written for a function view into a mixin for a class-based view. :: LoginRequiredMixin = DecoratorMixin(login_required) class MyView(LoginRequiredMixin): pass class SomeView(DecoratorMixin(some_decorator), ...
Python
jtatman_500k
function StartNext self begin if not remainingFiles begin call Disable call Disable if endCallback begin call endCallback end return end set currentFile = pop remainingFiles set filename = pop remainingFiles set lowerFname = lower filename comment we don't want to clean morrowind.esm if lowerFname == string morrowind.e...
def StartNext(self): if not self.remainingFiles: self.mSkip.Disable() self.mStop.Disable() if self.endCallback: self.endCallback() return self.currentFile = filename = self.remainingFiles.pop() lowerFname = filename.lower() ...
Python
nomic_cornstack_python_v1
function shift_cities road_map begin set shifted_road_map = list comprehension road_map at i - 1 % length road_map for tuple i city in enumerate road_map return shifted_road_map end function
def shift_cities(road_map): shifted_road_map = [road_map[(i-1) % len(road_map)] for i, city in enumerate(road_map)] return shifted_road_map
Python
nomic_cornstack_python_v1
function remove_comments code begin set lines = split code string set in_comment = false set new_code = list for line in lines begin set i = 0 while i < length line begin if line at i == string # begin if not in_comment begin set line = line at slice : i : break end else begin set i = i + 1 end end else if line at s...
def remove_comments(code): lines = code.split('\n') in_comment = False new_code = [] for line in lines: i = 0 while i < len(line): if line[i] == '#': if not in_comment: line = line[:i] break else: ...
Python
jtatman_500k
function _trackInstanceAndCheckForConcurrencyViolation self begin string Check for concurrency violation and add self to _clsOutstandingInstances. ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is incremented global g_max_concurrency g_max_concurrency_raise_exception assert g_max_concurrency is not none ...
def _trackInstanceAndCheckForConcurrencyViolation(self): """ Check for concurrency violation and add self to _clsOutstandingInstances. ASSUMPTION: Called from constructor BEFORE _clsNumOutstanding is incremented """ global g_max_concurrency, g_max_concurrency_raise_exception assert g_max_c...
Python
jtatman_500k
function compute_revised_failures data decre_file compute_size begin set results = dict string total_methods data at string method_count try begin with open decre_file string r as file begin set decre = load json file end end except FileNotFoundError begin error string File { decre_file } had no decompilation results r...
def compute_revised_failures(data, decre_file, compute_size): results = {'total_methods': data['method_count']} try: with open(decre_file, 'r') as file: decre = json.load(file) except FileNotFoundError: LOGGER.error(f'File {decre_file} had no decompilation results') retur...
Python
nomic_cornstack_python_v1
function permute_axes self permutation begin assert all set permuted = call Cell self at permutation at tuple slice : : permutation return permuted end function
def permute_axes(self, permutation): assert (np.sort(permutation) == np.arange(3)).all() permuted = Cell(self[permutation][:, permutation]) return permuted
Python
nomic_cornstack_python_v1
function toglTF rows bgltf=false origin=list 0 0 0 begin set nodes = list set normals = list set bb = list for i in range 0 length rows begin set mp = parse bytes rows at i at 0 set triangles = list for poly in mp begin if length poly != 1 begin print string No support for inner polygon rings end else if length pol...
def toglTF(rows, bgltf = False, origin = [0,0,0]): nodes = [] normals = [] bb = [] for i in range(0, len(rows)): mp = parse(bytes(rows[i][0])) triangles = [] for poly in mp: if(len(poly) != 1): print("No support for inner polygon rings") el...
Python
nomic_cornstack_python_v1
comment 백준 11399번 set N = integer input set p_list = list map int split input set result_list = sorted p_list set sum = list 0 0 for i in result_list begin set sum at 0 = sum at 0 + i set sum at 1 = sum at 1 + sum at 0 end print sum at 1
# 백준 11399번 N = int(input()) p_list = list(map(int, input().split())) result_list = sorted(p_list) sum = [0, 0] for i in result_list: sum[0] += i sum[1] += sum[0] print(sum[1])
Python
zaydzuhri_stack_edu_python
comment various utils # comment like timer for function # from typing import Any import time import pandas as pd set nesting_level = 0 set is_start = none function data_sample X nrows=5000 begin comment -> (pd.DataFrame, pd.Series): string zypang change to one line :param X: :param nrows: :return: return if expression ...
############################################# # various utils # # like timer for function # ############################################# from typing import Any import time import pandas as pd nesting_level = 0 is_start = None def data_sample(X: pd.DataFrame, nrows: int...
Python
zaydzuhri_stack_edu_python
import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import Select , WebDriverWait function _assert result_bool msg=string begin string Gets a boolean if false, Throws a...
import time from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import Select, WebDriverWait def _assert(result_bool, msg=''): """Gets a boolean if false, Throws a except...
Python
zaydzuhri_stack_edu_python
from autoprotocol.unit import Unit from lib.test import foo function sample_protocol protocol params begin set dest_plate = params at string destination_plate set wells_to_measure = list for location in params at string dye_locations begin call transfer params at string dye call well location at string well_index loca...
from autoprotocol.unit import Unit from lib.test import foo def sample_protocol(protocol, params): dest_plate = params["destination_plate"] wells_to_measure = [] for location in params["dye_locations"]: protocol.transfer(params["dye"], dest_plate.well(location["well_index...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2 comment -*- coding: utf-8 -*- string Created on Thu Aug 3 10:51:15 2017 @author: datascience2 import requests import json import pandas as pd string import urllib2 import bs4 from BeautifulSoup import numpy as np import pandas as pd import json import pymongo from pandas import DataFrame G...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Aug 3 10:51:15 2017 @author: datascience2 """ import requests import json import pandas as pd """ import urllib2 import bs4 from BeautifulSoup import numpy as np import pandas as pd import json import pymongo from pandas import...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function twoSum self nums target begin set indices = dictionary for i in range 0 length nums begin set indices at nums at i = i end for i in range 0 length nums begin if target - nums at i in indices begin set i2 = indices at target - nums at i if i != i2 begin return list i i2 end e...
class Solution(object): def twoSum(self, nums, target): indices=dict() for i in range(0,len(nums)) : indices[nums[i]]=i for i in range(0,len(nums)) : if (target-nums[i]) in indices : i2=indices[target-nums[i]] if i!=i2 : ...
Python
zaydzuhri_stack_edu_python
function after_request response begin close db return response end function
def after_request(response): g.db.close() return response
Python
nomic_cornstack_python_v1
string To get client ID and client secret, go to https://developer.spotify.com/dashboard Then, log in with your Spotify Account and create an app You can see the Client ID of the app right from the dasboard. Copy the CLient ID and replace it with client_id_here To see the Client Secret, click on the app and then on "SH...
''' To get client ID and client secret, go to https://developer.spotify.com/dashboard Then, log in with your Spotify Account and create an app You can see the Client ID of the app right from the dasboard. Copy the CLient ID and replace it with client_id_here To see the Client Secret, click on the app and then on "S...
Python
zaydzuhri_stack_edu_python
function NSSolve dData dInit dCone begin comment constraint count, primal variable count set m = shape at 0 set n = shape at 1 set nplus = n + 1 comment create matrix for self dual LHS and vector for RHS set nA = call SelfDualNewtonSystem dData set nb = zeros shape at 0 comment init solution which will be updated set d...
def NSSolve(dData, dInit, dCone): # constraint count, primal variable count m = dData.A.shape[0] n = dData.A.shape[1] nplus = n + 1 # create matrix for self dual LHS and vector for RHS nA = SelfDualNewtonSystem(dData) nb = np.zeros(nA.shape[0]) # init solution which will b...
Python
nomic_cornstack_python_v1
function pony var wrapper message begin call send format messages at string pony_toss source comment 59/29/7/5 split set rnd = random if rnd < 0.59 begin set pony = get messages string pony_land 0 end else if rnd < 0.88 begin set pony = get messages string pony_land 1 end else if rnd < 0.95 begin set pony = get message...
def pony(var, wrapper, message): wrapper.send(messages["pony_toss"].format(wrapper.source)) # 59/29/7/5 split rnd = random.random() if rnd < 0.59: pony = messages.get("pony_land", 0) elif rnd < 0.88: pony = messages.get("pony_land", 1) elif rnd < 0.95: pony = messages.ge...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import argparse import pickle import dill import pickle import numpy as np import cv2 from modules.util import plot from modules.face_model import ShapeModel from modules.procrustes import root_mean_square , calculate_procrustes , find_theta , rotate from imutils import resize set parser = call...
#!/usr/bin/python import argparse import pickle import dill import pickle import numpy as np import cv2 from modules.util import plot from modules.face_model import ShapeModel from modules.procrustes import root_mean_square, calculate_procrustes, find_theta, rotate from imutils import resize parser = argparse.Argument...
Python
zaydzuhri_stack_edu_python
import psycopg2 from app import db from werkzeug.security import generate_password_hash comment create DB set connection = call connect database=string postgres user=string postgres password=string postgres host=string localhost set autocommit = true set cur = call cursor execute cur string CREATE DATABASE country_info...
import psycopg2 from app import db from werkzeug.security import generate_password_hash # create DB connection = psycopg2.connect( database='postgres', user='postgres', password='postgres', host='localhost', ) connection.autocommit = True cur = connection.cursor() cur.execute('CREATE DATABASE country_i...
Python
zaydzuhri_stack_edu_python
from tkinter import messagebox from tkinter import simpledialog from tkinter import * import math set root = call Tk call withdraw function is_float valor begin try begin decimal valor end except any begin return false end return true end function function is_int valor begin try begin integer valor end except any begin...
from tkinter import messagebox from tkinter import simpledialog from tkinter import * import math root = Tk() root.withdraw() def is_float(valor): try: float(valor) except: return False return True def is_int(valor): try: int(valor) except: ...
Python
zaydzuhri_stack_edu_python
function testPAMin self begin function do begin return call _main list string testPAMin end function set s = call StringIO write s string P7 WIDTH 3 HEIGHT 1 DEPTH 4 MAXVAL 255 TUPLTYPE RGB_ALPHA ENDHDR comment The pixels in flat row flat pixel format set flat = list 255 0 0 255 0 255 0 120 0 0 255 30 write s join stri...
def testPAMin(self): def do(): return _main(['testPAMin']) s = StringIO() s.write('P7\nWIDTH 3\nHEIGHT 1\nDEPTH 4\nMAXVAL 255\n' 'TUPLTYPE RGB_ALPHA\nENDHDR\n') # The pixels in flat row flat pixel format flat = [255, 0, 0, 255, 0, 255, 0, 120, 0...
Python
nomic_cornstack_python_v1
import sys function input begin return strip read line stdin end function function resolve begin set s = input set cnt = 0 set prev = string set ima = string for i in s begin set ima = ima + i if ima != prev begin set cnt = cnt + 1 set prev = ima set ima = string end end print cnt end function call resolve
import sys def input(): return sys.stdin.readline().strip() def resolve(): s=input() cnt=0 prev='' ima='' for i in s: ima+=i if ima!=prev: cnt+=1 prev=ima ima='' print(cnt) resolve()
Python
zaydzuhri_stack_edu_python
class Queue begin string 使用列表实现队列 function __init__ self begin set items = list end function function is_empty self begin string 是否为空 :return: return items == list end function function enqueue self item begin string 入队 :param item: :return: insert items 0 item end function function dequeue self begin string 出队 :retu...
class Queue: """ 使用列表实现队列 """ def __init__(self): self.items = [] def is_empty(self): """ 是否为空 :return: """ return self.items == [] def enqueue(self, item): """ 入队 :param item: :return: """ self.ite...
Python
zaydzuhri_stack_edu_python
from encoder_class import Encoder import datetime import math import numpy as np from angle_conversions import angle_conversions class Calculations begin function __init__ self begin set datetime = datetime set current_time = now set year = year set month = month set day = day set ut_current_time = call utcnow set ut_h...
from encoder_class import Encoder import datetime import math import numpy as np from angle_conversions import angle_conversions class Calculations(): def __init__(self): self.datetime = datetime self.current_time = datetime.datetime.now() self.year = self.current_time.year self.mon...
Python
zaydzuhri_stack_edu_python
import numpy as np import json import zipfile import sys import math with open string config.json as json_data_file begin set ConfigJsondata = load json json_data_file end comment ------------------------------------------------------------------------------------------## comment ------------------------------BUILDING ...
import numpy as np import json import zipfile import sys import math with open('config.json') as json_data_file: ConfigJsondata = json.load(json_data_file) #------------------------------------------------------------------------------------------## #------------------------------BUILDING THE VOCAB DICT start----...
Python
zaydzuhri_stack_edu_python
import random set modifier = 0 string difficulty is a two_dimensional vector measuring roughly how much damage the monster can do to hero in the early and later part of the section string for example, a mage with average attack and defense will have a balance difficulty of [10,10] string on the other hand, a skeleton w...
import random modifier=0 'difficulty is a two_dimensional vector measuring roughly how much damage the monster can do to hero in the early and later part of the section' 'for example, a mage with average attack and defense will have a balance difficulty of [10,10]' 'on the other hand, a skeleton with high attack and ...
Python
zaydzuhri_stack_edu_python
function Size self begin return call itkSparseFieldLayerNBNIF3_Size self end function
def Size(self) -> "unsigned int": return _itkSparseFieldFourthOrderLevelSetImageFilterPython.itkSparseFieldLayerNBNIF3_Size(self)
Python
nomic_cornstack_python_v1
function walk_gff gffFile mfDict begin set fout = open outputEmpty string w with open gffFile as f begin for line_with_coordinates in f begin set array_with_coordinates = split right strip line_with_coordinates string comment coordinates chr start end set key = string array_with_coordinates at 0 + string + string arra...
def walk_gff(gffFile, mfDict): fout = open(outputEmpty, 'w') with open(gffFile) as f: for line_with_coordinates in f: array_with_coordinates = line_with_coordinates.rstrip().split("\t") #coordinates chr start end key=str(array_with_coordinates[0])+" "+str(array_with_...
Python
nomic_cornstack_python_v1
function convert inputs output begin print string Started set count = 0 comment Skip headers. for input in inputs begin seek input NCS_HEADER_LEN end comment Combine chunks from the inputs and write to the output. while true begin set chunks = list comprehension call next_chunk input for input in inputs if not any chun...
def convert(inputs, output): print('Started') count = 0 # Skip headers. for input in inputs: input.seek(NCS_HEADER_LEN) # Combine chunks from the inputs and write to the output. while True: chunks = [next_chunk(input) for input in inputs] if not any(chunks): b...
Python
nomic_cornstack_python_v1
from django.core.management import BaseCommand from django.db import transaction from system.flights.models import Airplane , Airport , Flight , Passenger , Ticket , Crew from faker import Faker from random import randint , choice , shuffle , sample import pytz from datetime import timedelta class Command extends BaseC...
from django.core.management import BaseCommand from django.db import transaction from system.flights.models import Airplane, Airport, Flight, Passenger, Ticket, Crew from faker import Faker from random import randint, choice, shuffle, sample import pytz from datetime import timedelta class Command(BaseCommand): h...
Python
zaydzuhri_stack_edu_python
function is_unique string begin set char_count = dict for char in string begin if char in char_count begin return false end set char_count at char = 1 end return true end function set str = string I am so excited to learn GPT comment Output: False print call is_unique str
def is_unique(string): char_count = {} for char in string: if char in char_count: return False char_count[char] = 1 return True str = "I am so excited to learn GPT" print(is_unique(str)) # Output: False
Python
jtatman_500k
function index self begin return entry at string index end function
def index(self): return self.entry['index']
Python
nomic_cornstack_python_v1
function IAccessSelections2 self TopDoc=defaultNamedNotOptArg Component=defaultNamedNotOptArg begin return call InvokeTypes 20 LCID 1 tuple 11 0 tuple tuple 9 1 tuple 9 1 TopDoc Component end function
def IAccessSelections2(self, TopDoc=defaultNamedNotOptArg, Component=defaultNamedNotOptArg): return self._oleobj_.InvokeTypes(20, LCID, 1, (11, 0), ((9, 1), (9, 1)),TopDoc , Component)
Python
nomic_cornstack_python_v1
function mmGetMetricSequencesPredictedActiveCellsShared self begin string Metric for number of sequences each predicted => active cell appears in Note: This metric is flawed when it comes to high-order sequences. @return (Metric) metric call _mmComputeTransitionTraces set numSequencesForCell = default dictionary lambda...
def mmGetMetricSequencesPredictedActiveCellsShared(self): """ Metric for number of sequences each predicted => active cell appears in Note: This metric is flawed when it comes to high-order sequences. @return (Metric) metric """ self._mmComputeTransitionTraces() numSequencesForCell = defa...
Python
jtatman_500k
function matrix_multiply M1 M2 begin set M3 = list list 0 0 list 0 0 for i in range length M1 begin for j in range length M2 at 0 begin for k in range length M2 begin set M3 at i at j = M3 at i at j + M1 at i at k * M2 at k at j end end end return M3 end function
def matrix_multiply(M1, M2): M3 = [[0, 0], [0, 0]] for i in range(len(M1)): for j in range(len(M2[0])): for k in range(len(M2)): M3[i][j] += M1[i][k] * M2[k][j] return M3
Python
jtatman_500k
string 416. Partition Equal Subset Sum Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Example 1: Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] and...
''' 416. Partition Equal Subset Sum Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal. Example 1: Input: nums = [1,5,11,5] Output: true Explanation: The array can be partitioned as [1, 5, 5] ...
Python
zaydzuhri_stack_edu_python
function read_timestamp self begin if not call fetch_from_database database_name=database_name table_name=string analysisprofile to_fetch=string timestamp where=list list string table_name table_name list string type_name typename begin comment If no analysisprofile database exists then return the start timestamp retur...
def read_timestamp(self): if not self.fetch_from_database(database_name = self.database_name, table_name = 'analysisprofile', to_fetch = 'timestamp', where = [['table_name', se...
Python
nomic_cornstack_python_v1
function get_max_partition self spec=none skip_empty=true reverse=false begin if not partitions begin raise call ValueError string Table %r not partitioned % name end return call get_max_partition spec skip_empty=skip_empty reverse=reverse end function
def get_max_partition(self, spec=None, skip_empty=True, reverse=False): if not self.table_schema.partitions: raise ValueError("Table %r not partitioned" % self.name) return self.partitions.get_max_partition( spec, skip_empty=skip_empty, reverse=reverse )
Python
nomic_cornstack_python_v1
function build cls manager source name options comment begin set obj = call cls name set manager = manager set source = source set comment = comment for opdef in options begin set found = false if type == list begin if name in options begin set value = options at name if not is instance value list begin comment Sometim...
def build(cls, manager, source, name, options, comment): obj = cls(name) obj.manager = manager obj.source = source obj.comment = comment for opdef in cls.options: found = False if opdef.type == list: if opdef.name in options: ...
Python
nomic_cornstack_python_v1
import socket comment client = socket.socket() # 声明socket类型,同时生成socket连接对象 comment client.connect(('127.0.0.1', 9999)) comment # client.send('Hello World') # TypeError: a bytes-like object is required, not 'str' comment # python3中必须发送byte类型 comment client.send(b'Hello World') comment data = client.recv(1024) comment pr...
# import socket # client = socket.socket() # 声明socket类型,同时生成socket连接对象 # client.connect(('127.0.0.1', 9999)) # # client.send('Hello World') # TypeError: a bytes-like object is required, not 'str' # # python3中必须发送byte类型 # client.send(b'Hello World') # data = client.recv(1024) # print('recv:', data) client = socket.s...
Python
zaydzuhri_stack_edu_python
function create_user type handle name username begin call create_all engine set user_id = call _create_thingy call User name=name username=username uuid=handle handle=handle comment Add this user to a group if type begin call create_group_membership call _create_touch user_id none none type end return user_id end funct...
def create_user(type, handle, name, username): Base.metadata.create_all(engine) user_id = _create_thingy(User(name=name, username=username, uuid=handle, handle=handle)) #Add this user to a group if type: create_group_membership(_create_touch(user_id, None, None), type) return user_id
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Module: changePidginStatus.py comment Author: Pradnyesh Sawant string Change pidgin status automatically from ~/.signature file comment TODO: comment LOG: comment ########################## import dbus import os class ChangePidginStatus extends object begin function __init__ self be...
#!/usr/bin/env python ########################## # Module: changePidginStatus.py # Author: Pradnyesh Sawant ''' Change pidgin status automatically from ~/.signature file ''' # TODO: # LOG: # ########################## import dbus import os class ChangePidginStatus(object): def __init__(self): bus = dbus....
Python
zaydzuhri_stack_edu_python