code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function __init__ self training_path validation_path n_clusters=100 model_path=string begin set train_categories = glob glob training_path + string /* set val_categories = glob glob validation_path + string /* comment dictionary of training images set train_dict = dict comment dictionary of validation images set val_d...
def __init__(self, training_path, validation_path, n_clusters=100, model_path=''): train_categories = glob.glob(training_path + '/*') val_categories = glob.glob(validation_path + '/*') # dictionary of training images self.train_dict = {} # dictionary of validation images ...
Python
nomic_cornstack_python_v1
function __init__ self num_vars device lag hidden_size_1 hidden_size_2 num_outputs=1 dp=0.0 begin call __init__ comment Sub-networks set layer1_list = call ModuleList set layer2_list = call ModuleList for state in range num_vars begin set layer1 = linear lag hidden_size_1 set layer2 = linear hidden_size_1 hidden_size_1...
def __init__(self, num_vars, device, lag, hidden_size_1, hidden_size_2, num_outputs=1, dp=0.0): super(MLPgc, self).__init__() # Sub-networks self.layer1_list = nn.ModuleList() self.layer2_list = nn.ModuleList() for state in range(num_vars): layer1 = nn.Linear(lag, hi...
Python
nomic_cornstack_python_v1
function _get_generic_numbers_list self begin pass end function
def _get_generic_numbers_list(self): pass
Python
nomic_cornstack_python_v1
function two_of_three x y z begin comment My Solution # return min x ^ 2 + y ^ 2 x ^ 2 + z ^ 2 y ^ 2 + z ^ 2 end function
def two_of_three(x, y, z): ############### # My Solution # ############### return min(x**2+y**2, x**2+z**2, y**2+z**2)
Python
nomic_cornstack_python_v1
from flask import Flask , render_template set app = call Flask __name__ decorator call route string / function home begin return string hello end function decorator call route string /play function index begin comment notice the 2 new named arguments! return call render_template string index.html times=5 end function d...
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return 'hello' @app.route('/play') def index(): return render_template("index.html", times=5) # notice the 2 new named arguments! @app.route('/play/<int:times>') def times(times): return render_template("index.html"...
Python
zaydzuhri_stack_edu_python
from sympy import * import numpy as np set x = call Symbol string x set k1 = call Symbol string k1 set k2 = call Symbol string k2 set xg1 = call Symbol string xg1 set xg2 = call Symbol string xg2 set A0 = call Symbol string A0 set xn = call Symbol string xn set q1 = call Symbol string q1 set vt = call Symbol string vt ...
from sympy import * import numpy as np x = Symbol('x') k1 = Symbol('k1') k2 = Symbol('k2') xg1 = Symbol('xg1') xg2 = Symbol('xg2') A0 = Symbol('A0') xn = Symbol('xn') q1 = Symbol('q1') vt = Symbol('vt') qsqrt = k1**2*q1**2-A0*exp(-xn)*exp(xg1-q1) q = sqrt(qsqrt) qcoth = q*coth(q/2) q2 = xg2-xg1+q1+2*log(k1*q1...
Python
zaydzuhri_stack_edu_python
function login_action request begin if method == string POST begin set login_form = call LoginForm POST if call is_valid begin set username = cleaned_data at string username set password = cleaned_data at string password set user = call authenticate request username=username password=password if user is not none begin ...
def login_action(request): if request.method == 'POST': login_form = LoginForm(request.POST) if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] user = authenticate(request, username=username, pas...
Python
nomic_cornstack_python_v1
if x < 10 begin if y < 5 begin print string x is less than 10 and y is less than 5 end else if y == 5 begin print string x is less than 10 and y is equal to 5 end else begin print string x is less than 10 and y is greater than 5 end end else if y < 5 begin print string x is greater than or equal to 10 and y is less tha...
if x < 10: if y < 5: print("x is less than 10 and y is less than 5") elif y == 5: print("x is less than 10 and y is equal to 5") else: print("x is less than 10 and y is greater than 5") else: if y < 5: print("x is greater than or equal to 10 and y is less than 5") eli...
Python
zaydzuhri_stack_edu_python
function plt_imshow_tensor img one_channel=false begin if one_channel begin set img = mean img dim=0 end set npimg = call numpy comment change to values between 1 and 0 set npimg = npimg / 255.0 if one_channel begin image show npimg cmap=string Greys end else begin image show transpose np npimg tuple 1 2 0 end end func...
def plt_imshow_tensor(img, one_channel=False): if one_channel: img = img.mean(dim=0) npimg = img.numpy() npimg = npimg / 255.0 # change to values between 1 and 0 if one_channel: plt.imshow(npimg, cmap="Greys") else: plt.imshow(np.transpose(npimg, (1, 2, 0)))
Python
nomic_cornstack_python_v1
function configure_coord_names self member_name=default_member_name period_name=default_period_name initialistion_time_name=default_initialistion_time_name begin set realization = member_name set time_coord = period_name set forecast_ref_time = initialistion_time_name end function
def configure_coord_names(self, member_name=default_member_name, period_name=default_period_name, initialistion_time_name=default_initialistion_time_name): self.realization = member_name self.time_coord = period_name self.forecast_ref_time = initialist...
Python
nomic_cornstack_python_v1
function borrow_request_new request begin if call is_authenticated begin set has_new = false if count filter recipient=user status=PENDING > 0 begin set has_new = true end return dict string new_br has_new end else begin return dict end end function
def borrow_request_new(request): if request.user.is_authenticated(): has_new = False if BorrowRequest.objects.filter(recipient=request.user, status=rs.PENDING) .count() > 0: has_new = True return {'new_br': has_new} else: return {}
Python
nomic_cornstack_python_v1
string DictFS allows you to easily create read-only filesystems when the file tree is known in advance. To create your own DictFS descendent, simply override the files property, which can be created either using the property decorator, or just a simple assignment. A dictionary represents a directory, with keys correspo...
""" DictFS allows you to easily create read-only filesystems when the file tree is known in advance. To create your own DictFS descendent, simply override the files property, which can be created either using the property decorator, or just a simple assignment. A dictionary represents a directory, with keys correspon...
Python
zaydzuhri_stack_edu_python
function gotoPoint self x y z begin set x0 = x set y0 = y set z0 = z set dist = distance x0 y0 z0 x y z set step = 10 set i = 0 while i < dist begin call goDirectlyTo x0 + x - x0 * i / dist y0 + y - y0 * i / dist z0 + z - z0 * i / dist sleep 0.05 set i = i + step end call goDirectlyTo x y z sleep 0.05 end function
def gotoPoint(self, x, y, z): x0 = self.x y0 = self.y z0 = self.z dist = kinematics.distance(x0, y0, z0, x, y, z) step = 10 i = 0 while i < dist: self.goDirectlyTo(x0 + (x - x0) * i / dist, y0 + (y - y0) * i / dist, z0 + (z - z0) * i / dist) time.sleep(0.05) i += ste...
Python
nomic_cornstack_python_v1
function test_datasteal_success self begin set begin_assets_stealer = assets set additional_percents = 10 save call resolve assert equal assets begin_assets_stealer + 1 end function
def test_datasteal_success(self): begin_assets_stealer = self.dso.stealer_corporation.assets self.dso.additional_percents = 10 self.dso.save() self.dso.resolve() self.assertEqual(self.reload(self.dso.stealer_corporation).assets, begin_assets_stealer + 1)
Python
nomic_cornstack_python_v1
import pprint import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_recommenders as tfrs function get_mixer_data data_size=100000 random_seed=42 begin set rng = call RandomState random_seed ...
import pprint import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorflow_recommenders as tfrs def get_mixer_data(data_size=100_000, random_seed=42): rng = np.random.RandomState(random_seed...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import pandas as pd import load_dataset as load import preprocess from categorizing_model import CModel import plotting comment load dataset set FILENAME = string Dataset.txt set dataset = call load_dataset FILENAME comment tokenize titles set tuple tensor vocab_size = call tokenize call to_list...
import tensorflow as tf import pandas as pd import load_dataset as load import preprocess from categorizing_model import CModel import plotting # load dataset FILENAME = 'Dataset.txt' dataset = load.load_dataset(FILENAME) # tokenize titles tensor, vocab_size = preprocess.tokenize(dataset['titles'].to_list()) # spli...
Python
zaydzuhri_stack_edu_python
comment 有参装饰器 comment def auth(db_type): comment def deco(func): comment def wrapper(*args,**kwargs): comment name = input("请输入你的名字:").strip() comment pwd = input("请输入你的密码:").strip() comment if db_type == '1': comment if name == 'egon' and pwd == '123': comment res=func(*args,**kwargs) comment return res comment if db_...
# 有参装饰器 # def auth(db_type): # def deco(func): # def wrapper(*args,**kwargs): # name = input("请输入你的名字:").strip() # pwd = input("请输入你的密码:").strip() # if db_type == '1': # if name == 'egon' and pwd == '123': # res=func(*args,**kwargs) # ...
Python
zaydzuhri_stack_edu_python
from importlib import import_module function get_callable func_or_path begin string Receives a dotted path or a callable, Returns a callable or None if callable func_or_path begin return func_or_path end set module_name = join string . split func_or_path string . at slice : - 1 : set function_name = split func_or_path...
from importlib import import_module def get_callable(func_or_path): """ Receives a dotted path or a callable, Returns a callable or None """ if callable(func_or_path): return func_or_path module_name = '.'.join(func_or_path.split('.')[:-1]) function_name = func_or_path.split('.')[-1] ...
Python
zaydzuhri_stack_edu_python
function __init__ self arena_id begin comment Read walls image files set arena_id = arena_id set wall_images = load np string walls/arena%d.npz % arena_id set wall1 = wall_images at string arr_0 set wall2 = wall_images at string arr_1 set wall3 = wall_images at string arr_2 set wall4 = wall_images at string arr_3 set m...
def __init__(self, arena_id): # Read walls image files self.arena_id = arena_id self.wall_images = np.load('walls/arena%d.npz' % arena_id) self.wall1 = self.wall_images['arr_0'] self.wall2 = self.wall_images['arr_1'] self.wall3 = self.wall_images['arr_2'] self.wa...
Python
nomic_cornstack_python_v1
function push dim begin set dimObj = call get_dim_object dim if dimObj in values DIMS begin call _snapshot_status dimObj end else begin raise call DimensionError dim string Dimension does not exist end end function
def push(dim): dimObj = cubely.common.get_dim_object(dim) if dimObj in cubely.DIMS.values(): _snapshot_status(dimObj) else: raise DimensionError(dim, 'Dimension does not exist')
Python
nomic_cornstack_python_v1
import pandas as pd import random as rnd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import cross_val_score comment Read in data set trai...
import pandas as pd import random as rnd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import cross_val_score #Read in data trainingData...
Python
zaydzuhri_stack_edu_python
function Grundy x begin comment n taille bianire max des xi; m longeur de x comment Calcul de la longueur binaire utilisée comment Complexité en O(m) set n = 0 for val in x begin set t = call taille val if n < t begin set n = t end end comment Ecriture de la liste x en binaire comment Complexité en O(m*n) car binaire(x...
def Grundy(x): # n taille bianire max des xi; m longeur de x # Calcul de la longueur binaire utilisée # Complexité en O(m) n = 0 for val in x : t = taille(val) if n < t : n = t # Ecriture de la liste x en binaire # Complexité en O(m*n...
Python
nomic_cornstack_python_v1
comment Get unique items from list of lists? set uniq_animal_groups = set map tuple animal_groups
# Get unique items from list of lists? uniq_animal_groups = set(map(tuple, animal_groups))
Python
zaydzuhri_stack_edu_python
comment 빈 리스트 만들기 set numbers = list comment numbers에 자연수 1부터 10까지 추가 comment 코드를 입력하세요 set i = 1 while i <= 10 begin append numbers i set i = i + 1 end print numbers comment numbers에서 홀수 제거 comment 코드를 입력하세요 string j = 0 while j < len(numbers): if numbers[j] % 2 == 1 : del numbers[j] j = j + 1 set i = length numbers ...
# 빈 리스트 만들기 numbers = [] # numbers에 자연수 1부터 10까지 추가 # 코드를 입력하세요 i = 1 while i <= 10: numbers.append(i) i = i + 1 print(numbers) # numbers에서 홀수 제거 # 코드를 입력하세요 ''' j = 0 while j < len(numbers): if numbers[j] % 2 == 1 : del numbers[j] j = j + 1 ''' i = len(numbers) - 1 while i >= 0: if number...
Python
zaydzuhri_stack_edu_python
import os comment declarar variables set tuple cliente vendedor jeans pu = tuple string string 0.0 0.0 comment imput set cliente = argv at 1 set vendedor = argv at 2 set jeans = decimal argv at 3 set pu = decimal argv at 4 comment procesing set total = jeans * pu comment verificador set por_compras = total > 200 set ...
import os #declarar variables cliente,vendedor,jeans,pu="","",0.0,0.0 #imput cliente= os.sys.argv[1] vendedor=os.sys.argv[2] jeans=float(os.sys.argv[3]) pu=float (os.sys.argv[4]) #procesing total=(jeans*pu) #verificador por_compras=(total>200) comprador_compulsivo= (total>200) comprador_anual=(total>600) #ouput prin...
Python
zaydzuhri_stack_edu_python
import pandas as pd set ts = call Series randn 1000 index=call date_range string 1/1/2000 periods=1000 set ts = cumulative sum ts plot
import pandas as pd ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000)) ts = ts.cumsum() ts.plot();
Python
zaydzuhri_stack_edu_python
function compute_date_granularity ldf begin set date_fields = list string day string month string year if data_type at string temporal begin comment assumes only one temporal column, may need to change this function to recieve multiple temporal columns in the future set date_column = ldf at data_type at string temporal...
def compute_date_granularity(ldf): date_fields = ["day", "month", "year"] if ldf.data_type["temporal"]: date_column = ldf[ldf.data_type["temporal"][0]] # assumes only one temporal column, may need to change this function to recieve multiple temporal columns in the future date_index = pd.DatetimeIndex(date_column)...
Python
nomic_cornstack_python_v1
from typing import List string For O(log(min(m, n))) Use binary search and it is very tricky, see this video https://www.youtube.com/watch?v=LPFhl65R7ww class Solution begin comment def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: comment "Merge, Time: O(m+n), Space: O(m+n)" comment if len...
from typing import List ''' For O(log(min(m, n))) Use binary search and it is very tricky, see this video https://www.youtube.com/watch?v=LPFhl65R7ww ''' class Solution: # def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: # "Merge, Time: O(m+n), Space: O(m+n)" # if len...
Python
zaydzuhri_stack_edu_python
function even list1 begin set x = list comprehension i for i in list1 if i % 2 == 0 return x end function
def even(list1): x= [i for i in list1 if i%2==0] return x
Python
zaydzuhri_stack_edu_python
function append_conv self conv begin append conversions conv end function
def append_conv(self, conv): self.conversions.append(conv)
Python
nomic_cornstack_python_v1
function test_value_spaces self begin set match = call _parse_term string field:val u e assert match at string field == string field assert match at string value == string val u e end function
def test_value_spaces(self): match = query._parse_term("field:val u e") assert match["field"] == "field" assert match["value"] == "val u e"
Python
nomic_cornstack_python_v1
for i in range 0 r begin set k = k + u at i end print k
for i in range(0,r): k+=(u[i]) print(k)
Python
zaydzuhri_stack_edu_python
from car import ElectricCar set my_tesla = call ElectricCar string tesla string model S 2012 print call get_descriptive_name call describe_battery call get_range
from car import ElectricCar my_tesla = ElectricCar('tesla', 'model S', 2012) print(my_tesla.get_descriptive_name()) my_tesla.battery.describe_battery() my_tesla.battery.get_range()
Python
zaydzuhri_stack_edu_python
function gotChattingUsers self users begin pass end function
def gotChattingUsers(self, users): pass
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment -*- coding: utf-8 -*- string description: 常用的内建模块 comment # datetime comment from datetime import datetime comment print(datetime.now()) comment print(type(datetime.now())) comment print(datetime(2015, 4, 19, 12, 20)) comment # 相对 datetime 类型, timestamp comment # timestamp 不区分时区, d...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ description: 常用的内建模块 """ # # datetime # # from datetime import datetime # # print(datetime.now()) # print(type(datetime.now())) # # print(datetime(2015, 4, 19, 12, 20)) # # # 相对 datetime 类型, timestamp # # timestamp 不区分时区, datetime 记录时区相关属性 # print(datetime.now().times...
Python
zaydzuhri_stack_edu_python
import requests import urllib3 set site = string https://jpopsuki.eu/ set site_torrent_list = string torrents.php?page={}&order_by=s4&order_way=ASC&action=advanced set cookie_valid = false set number_of_pages = 5 set username = string set password = string function get_cookie username password begin set http = call S...
import requests import urllib3 site = 'https://jpopsuki.eu/' site_torrent_list = 'torrents.php?page={}&order_by=s4&order_way=ASC&action=advanced' cookie_valid = False number_of_pages = 5 username = '' password = '' def get_cookie(username, password): http = requests.Session() fields = {'username': username, ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment Copyright (C) 2019 Michele Scuttari, Marina Nikolic comment Usage: FFT_receive.py serial_port_name filename comment Example: ./FFT_receive.py COM1 fft.csv import sys , serial , os from serial import SerialException from subprocess import call comment bytes representing the expected siz...
#!/usr/bin/python3 # # Copyright (C) 2019 Michele Scuttari, Marina Nikolic # # Usage: FFT_receive.py serial_port_name filename # Example: ./FFT_receive.py COM1 fft.csv import sys, serial, os from serial import SerialException from subprocess import call # bytes representing the expected size of the audio data chunk ...
Python
zaydzuhri_stack_edu_python
function GetEntity self id_ attr begin return get attribute self attr at id_ end function
def GetEntity(self, id_, attr): return getattr(self, attr)[id_]
Python
nomic_cornstack_python_v1
function reverse_analysis ds classifier bilateral results_dir ds_type eventdir roi_pair annot_dir analysis niceplot normalize incl_regs=false store_sens=true plot_tc=true can_contrast=none begin comment step 0: transpose the data (i.e. now its non-transposed) because comment fit_event_hrf_model needs a non-transposed d...
def reverse_analysis(ds, classifier, bilateral, results_dir, ds_type, eventdir, roi_pair, annot_dir, analysis, niceplot, ...
Python
nomic_cornstack_python_v1
comment Euler Project - Problem 17 comment If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. comment If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? comment Do no...
# Euler Project - Problem 17 # If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? # Do not count spaces or hyp...
Python
zaydzuhri_stack_edu_python
function generate_ai begin set ais = list set tuple prices results = call generate set companies = list string AAPL string AMD string AMZN string INTC string MSFT string CSCO string GPRO string NVDA string FB string COKE string WIX string TSLA string NTES string MU string ROKU string YAHOY string UBSFF string NDAQ str...
def generate_ai(): ais = [] prices, results = generate() companies = ['AAPL', 'AMD', 'AMZN', "INTC", "MSFT", "CSCO", "GPRO", "NVDA", "FB", "COKE", "WIX", "TSLA", "NTES", "MU", "ROKU", "YAHOY", "UBSFF", "NDAQ", "NICE", "WMT", "BABA", "GOOG", "IBM", 'QCOM', ...
Python
nomic_cornstack_python_v1
import turtle as trt call shape string turtle set N = 100 set n = 4 for i in range N begin call forward n call left 360 / N end
import turtle as trt trt.shape('turtle') N = 100 n = 4 for i in range (N): trt.forward(n) trt.left(360 / N)
Python
zaydzuhri_stack_edu_python
string 396. 旋转函数 给定一个长度为 n 的整数数组 A 。 假设 Bk 是数组 A 顺时针旋转 k 个位置后的数组,我们定义 A 的“旋转函数” F 为: F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]。 计算F(0), F(1), ..., F(n-1)中的最大值。 注意: 可以认为 n 的值小于 105。 示例: A = [4, 3, 2, 6] F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 ...
""" 396. 旋转函数 给定一个长度为 n 的整数数组 A 。 假设 Bk 是数组 A 顺时针旋转 k 个位置后的数组,我们定义 A 的“旋转函数” F 为: F(k) = 0 * Bk[0] + 1 * Bk[1] + ... + (n-1) * Bk[n-1]。 计算F(0), F(1), ..., F(n-1)中的最大值。 注意: 可以认为 n 的值小于 105。 示例: A = [4, 3, 2, 6] F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25 F(1) = (0 * 6) + (1 * 4) + (2 * 3) ...
Python
zaydzuhri_stack_edu_python
function get_port_protocol_classification_hash self begin return call _get string /spPortal/portProtocolClassification/info end function
def get_port_protocol_classification_hash(self) -> dict: return self._get("/spPortal/portProtocolClassification/info")
Python
nomic_cornstack_python_v1
function teardown tmppath begin remove tree tmppath end function
def teardown(tmppath): shutil.rmtree(tmppath)
Python
nomic_cornstack_python_v1
function wallsAndGates self rooms begin if not rooms or not rooms at 0 begin return end set row = length rooms set col = length rooms at 0 set start = list comprehension list x y for x in range row for y in range col if rooms at x at y == 0 set count = length start set min = 0 while start begin set temp = list set dir...
def wallsAndGates(self, rooms: List[List[int]]) -> None: if not rooms or not rooms[0]: return row = len(rooms) col = len(rooms[0]) start = [[x, y] for x in range(row) for y in range(col) if rooms[x][y]==0] count = len(start) min = 0 while start: ...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model set df = call read_excel string indo_12_1.xls skiprows=3 skipfooter=2 na_values=list string - rename columns=dict string Unnamed: 0 string Provinsi inplace=true comment print(df) set df = set index df string Provinsi...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn import linear_model df = pd.read_excel('indo_12_1.xls',skiprows = 3, skipfooter = 2, na_values=['-']) df.rename(columns={'Unnamed: 0':'Provinsi'},inplace = True) # print(df) df = df.set_index('Provinsi') df = df.transpose() ...
Python
zaydzuhri_stack_edu_python
function get_name self begin return _name + string at + string _k end function
def get_name(self): return self._name + ' at ' + str(self._k)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 from collections import defaultdict import unittest from logic import Var , vars , run , unify , eq , call_goal , List string What about this syntax? append = match({ ([], var, var): True, (List[front_head:front_rest], back, List[front_head:appended_rest]): append(front_rest, back, appende...
#!/usr/bin/env python3 from collections import defaultdict import unittest from logic import Var, vars, run, unify, eq, call_goal, List ''' What about this syntax? append = match({ ([], var, var): True, (List[front_head:front_rest], back, List[front_head:appended_rest]): append(front_rest, back, app...
Python
zaydzuhri_stack_edu_python
function projectCodes self begin set codes = list for project in projects begin set code = split project string -- at 1 if not code in codes begin append codes code end end return codes end function
def projectCodes(self): codes = [] for project in self.projects: code = project.split('--')[1] if not code in codes: codes.append(code) return codes
Python
nomic_cornstack_python_v1
string model that combines syntactic features and word embeddings from SRL_utils import * comment data: set training = string data_splits/training.json set training_df = read json training lines=true set development = string data_splits/development.json set development_df = read json development lines=true set test = s...
""" model that combines syntactic features and word embeddings """ from SRL_utils import* #data: training = "data_splits/training.json" training_df = pd.read_json(training, lines=True) development = "data_splits/development.json" development_df = pd.read_json(development, lines=True) test = "data_splits/te...
Python
zaydzuhri_stack_edu_python
import math from decimal import Decimal
import math from decimal import Decimal
Python
zaydzuhri_stack_edu_python
function get_last_build_url self job_url begin return format string {!s}lastBuild/api/json job_url end function
def get_last_build_url(self, job_url): return "{!s}lastBuild/api/json".format(job_url)
Python
nomic_cornstack_python_v1
function get_trash_pickup_info mycity_request begin debug string Getting trash day information set response = call MyCityResponseDataModel call set_address_in_session mycity_request set current_address = get session_attributes CURRENT_ADDRESS_KEY if current_address is none begin comment Delegate to the Alexa interactio...
def get_trash_pickup_info(mycity_request): LOGGER.debug('Getting trash day information') response = MyCityResponseDataModel() set_address_in_session(mycity_request) current_address = \ mycity_request.session_attributes.get(intent_constants.CURRENT_ADDRESS_KEY) if current_address is None: ...
Python
nomic_cornstack_python_v1
function validate_inputs self begin set inputs = call AttributeDict dict string code code ; string parent_folder parent_folder if string parameters in inputs begin set parameters = call get_dict end else begin set parameters = dict string INPUT dict end if string settings in inputs begin set settings = call get_dict e...
def validate_inputs(self): self.ctx.inputs = AttributeDict({ 'code': self.inputs.code, 'parent_folder': self.inputs.parent_folder, }) if 'parameters' in self.inputs: self.ctx.inputs.parameters = self.inputs.parameters.get_dict() else: self...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Jul 30 08:33:33 2020 @author: ccraig comment Space Invaders comment Sound (MacOs Only) comment Set Up Screen comment Building using the Turtle Module comment the module used to create the objects in the game..is called from this Module im...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 30 08:33:33 2020 @author: ccraig """ # Space Invaders # Sound (MacOs Only) #Set Up Screen #Building using the Turtle Module import turtle # the module used to create the objects in the game..is called from this Module import os import math impor...
Python
zaydzuhri_stack_edu_python
string Unittests for all the validators in app/utils/validators.py import pytest from app.utils.validators import validate_integer class TestIntegerValidator begin string Tests for the validate_integer function function test_valid self begin string Test for a valid data passed to validate_integer call validate_integer ...
""" Unittests for all the validators in app/utils/validators.py """ import pytest from app.utils.validators import validate_integer class TestIntegerValidator: """ Tests for the validate_integer function """ def test_valid(self): """ Test for a valid data passed to validate_inte...
Python
zaydzuhri_stack_edu_python
function psdf_1 **kwargs begin comment fqlag parameters # set n = 2 ^ 8 set dt = 1.0 set fql = array list 1.0 / dt * n 0.5 / dt set tuple lc extra = call simulate_light_curves n=n dt=dt nsim=100 set model = list string pl list - 5 - 2 set inP = extra at string input_psd at 1 set inP at 0 = log inP at 0 call fit_psdf fq...
def psdf_1(**kwargs): # fqlag parameters # n = 2**8 dt = 1.0 fql = np.array([1./(dt*n), 0.5/dt]) lc, extra = simulate_light_curves(n=n, dt=dt, nsim=100) model = ['pl', [-5, -2]] inP = extra['input_psd'][1] inP[0] = np.log(inP[0]) fit_psdf(fql, model, lc, extra, '1'...
Python
nomic_cornstack_python_v1
function register class_ accepted_by=none accepts=none alias=none consists=none default_child=none denies=none name=none removes=none begin from abjad.ly import contexts assert name not in contexts set context_entry : Dict = dict set context_entry at string accepts = set set context_entry at string consists = set set ...
def register( class_, accepted_by: typing.List[str] = None, accepts=None, alias: typing.Union[str, 'LilyPondContext'] = None, consists=None, default_child=None, denies=None, name: str = None, removes: typing.List[str] = None, ) -> 'LilyPond...
Python
nomic_cornstack_python_v1
function cancel self begin if self in movable begin set exceptionValue = call CancelledError call _delete remove execQueue self return true end return false end function
def cancel(self): if self in scoop._control.execQueue.movable: self.exceptionValue = CancelledError() scoop._control.futureDict[self.id]._delete() scoop._control.execQueue.remove(self) return True return False
Python
nomic_cornstack_python_v1
comment ! /usr/bin/python comment Helper file ############################ from fifo import Fifo comment Overriding Parent class FIFO ########### comment Limits to given QUEUE DEPTH ## Rejects if QUEUE DEPTH is full ############ class fifoFull extends Fifo begin set queueDepth = 2 function __init__ self value begin set...
#! /usr/bin/python ##################### Helper file ############################ from fifo import Fifo ###########Overriding Parent class FIFO ########### ####### Limits to given QUEUE DEPTH ## Rejects if QUEUE DEPTH is full ############ class fifoFull(Fifo): queueDepth = 2 def __init__(self,value): self.value...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None comment Definition for singly-linked list. comment class ListNode: comment def __init__(self, x): comment self.val = x comment self.next = None class S...
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: #...
Python
zaydzuhri_stack_edu_python
function optimize_table_dice table players_number tables_number responsabilities begin set dice = list for table_dice in range 1 7 begin set cumulated_r = sum list comprehension responsabilities at player at table at player_dice - 1 at table_dice - 1 for player in range players_number for player_dice in range 1 7 appe...
def optimize_table_dice(table, players_number, tables_number, responsabilities): dice = [] for table_dice in range(1,7): cumulated_r = sum( [responsabilities[player][table][player_dice-1][table_dice-1] for player in range(players_number) for...
Python
nomic_cornstack_python_v1
function create_url_rules self begin function p prefix route begin string Prefix a route with the URL prefix. return string { prefix } { route } end function set routes = routes return list call route string GET call p routes at string communities-prefix routes at string list search call route string POST call p routes...
def create_url_rules(self): def p(prefix, route): """Prefix a route with the URL prefix.""" return f"{prefix}{route}" routes = self.config.routes return [ route( "GET", p(routes["communities-prefix"], routes["list"]), ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 string 2019 April 28th - Daily_Coding_Problem #103. comment <markdown> comment ## 2019 April 28th - Daily_Coding_Problem #103 comment Problem: Given a string and a set of characters, comment return the shortest substring containing all the characters in the set. commen...
#!/usr/bin/env python # coding: utf-8 """2019 April 28th - Daily_Coding_Problem #103.""" # <markdown> # ## 2019 April 28th - Daily_Coding_Problem #103 # # Problem: Given a string and a set of characters, # return the shortest substring containing all the characters in the set. # # For example, given the string "figehae...
Python
zaydzuhri_stack_edu_python
string CS 6140 Machine Learning - Assignment 04 Problem 1 - Perceptron and Dual Perceptron @author: Rajesh Sakhamuru @version: 7/20/2020 import numpy as np import pandas as pd import statistics as st import math function getColNames data begin string Returns list of column names of data given :param data: pandas datafr...
''' CS 6140 Machine Learning - Assignment 04 Problem 1 - Perceptron and Dual Perceptron @author: Rajesh Sakhamuru @version: 7/20/2020 ''' import numpy as np import pandas as pd import statistics as st import math def getColNames(data): ''' Returns list of column names of data given :param data: pandas d...
Python
zaydzuhri_stack_edu_python
from flask import Flask , request , render_template import numpy as np import pickle set app = call Flask __name__ set model = load pickle open string student_calc.pkl string rb decorator call route string / function home begin return call render_template string index.html end function decorator call route string /pred...
from flask import Flask, request, render_template import numpy as np import pickle app = Flask(__name__) model = pickle.load(open("student_calc.pkl","rb")) @app.route('/') def home(): return render_template('index.html') @app.route('/predict', methods = ['post','get']) def predict(): print(request.for...
Python
zaydzuhri_stack_edu_python
function permute data begin set samp = list comprehension call permutation row for row in data return call masked_array samp call isnan samp end function
def permute(data): samp=[np.random.permutation(row) for row in data] return np.ma.masked_array(samp,np.isnan(samp))
Python
nomic_cornstack_python_v1
if valor > 0 begin for n in range 2 valor + 1 begin set zipo = zipo + 1 / n print string Controle de valores acum= zipo string o valor de N é n input end print string O resultado é: zipo end else begin print string Valor inserido errado. end
if (valor>0): for n in range(2,(valor+1)): zipo =zipo+(1/n) print('Controle de valores\n acum=',zipo,'\no valor de N é',n) input() print('O resultado é: ', zipo) else: print ('Valor inserido errado.')
Python
zaydzuhri_stack_edu_python
function replace dictionary key function begin if dictionary is not none and key in dictionary begin set dictionary at key = call function dictionary at key end end function
def replace(dictionary: Dict, key: str, function): if dictionary is not None and key in dictionary: dictionary[key] = function(dictionary[key])
Python
nomic_cornstack_python_v1
function der fc x h=0.0001 degree=1 type=string centered accuracy=2 begin comment Use these lists to manage the different coefficient options. set A = array list list list 0.0 0.0 - 0.5 0.0 0.5 0.0 0.0 list 0.0 1 / 12.0 - 2 / 3.0 0.0 2 / 3.0 - 1 / 12.0 0.0 list - 1 / 60.0 3 / 20.0 - 3 / 4.0 0.0 3 / 4.0 - 3 / 20.0 1 / 6...
def der(fc, x, h=.0001, degree=1, type='centered', accuracy=2): # Use these lists to manage the different coefficient options. A = np.array([[[0., 0., -.5, 0., .5, 0., 0.], [0., 1/12., -2/3., 0., 2/3., -1/12., 0.], [-1/60., 3/20., -3/4., 0., 3/4., -3/20., 1/60.]], ...
Python
nomic_cornstack_python_v1
import os import codecs import re import pickle import numpy as np for cluster_id in range 13 begin comment basedir set data_dir = string data comment length of paths set lengthes = list comment all paths in a sequence set all_state = list comment los for each state in all_state set all_los = list with open join pat...
import os import codecs import re import pickle import numpy as np for cluster_id in range(13): data_dir = 'data' # basedir lengthes = [] # length of paths all_state = [] # all paths in a sequence all_los = [] # los for each state in all_state with codecs.open(os.path.join(data_dir, 'Clusters_w...
Python
zaydzuhri_stack_edu_python
function isLoaded self begin update self if call isLoaded begin set ctrl = ref at string Static2 if call Texts at 0 == string License Activation begin return true end else begin return false end end else begin return false end end function
def isLoaded(self): self.update() if super(LicenseActivation, self).isLoaded(): ctrl = self.ref['Static2'] if (ctrl.Texts())[0] == 'License Activation': return True else: return False else: return False
Python
nomic_cornstack_python_v1
function set_reprompt_ssml self ssml begin string Set response reprompt output speech as SSML type. Args: ssml: str. Response speech used when type is 'SSML', should be formatted with Speech Synthesis Markup Language. Cannot exceed 8,000 characters. set type = string SSML set ssml = ssml end function
def set_reprompt_ssml(self, ssml): """Set response reprompt output speech as SSML type. Args: ssml: str. Response speech used when type is 'SSML', should be formatted with Speech Synthesis Markup Language. Cannot exceed 8,000 characters. """ s...
Python
jtatman_500k
function area self begin return __size ^ 2 end function
def area(self): return self.__size ** 2
Python
nomic_cornstack_python_v1
function _ingest_test_format_dataframes partitioned_df pq_df with_partitions=false begin sort values partitioned_df by=list string dev_feature_float inplace=true sort values pq_df by=list string dev_feature_float inplace=true set pq_df = call reindex sorted columns axis=1 set partitioned_df = call reindex sorted column...
def _ingest_test_format_dataframes( partitioned_df: pd.DataFrame, pq_df: pd.DataFrame, with_partitions: bool = False ) -> Tuple[pd.DataFrame, pd.DataFrame]: partitioned_df.sort_values(by=["dev_feature_float"], inplace=True) pq_df.sort_values(by=["dev_feature_float"], inplace=True) pq_df = pq_df.reindex(...
Python
nomic_cornstack_python_v1
function __init__ self IO OK origin=none target=none begin print string Pathfinder started set origin = origin set target = target set IO = IO set OK = OK set obstacles = call obstacleAvoidance IO set driver = call Driver IO OK set sensors = call Sensors IO set location = call Localization end function
def __init__(self, IO, OK, origin=None, target=None): print("Pathfinder started") self.origin = origin self.target = target self.IO = IO self.OK = OK self.obstacles = obstacleAvoidance(IO) self.driver = Driver(IO, OK) self.sensors = Sensors(IO) self.location = Localization()
Python
nomic_cornstack_python_v1
function ruleitem_to_rule ruleitem data_list begin set rule = call Rule condset label data_list return rule end function
def ruleitem_to_rule(ruleitem, data_list): rule = Rule(ruleitem.condset, ruleitem.label, data_list) return rule
Python
nomic_cornstack_python_v1
function load_shape_data filename begin if not is file path filename begin raise call IOError string A file called + filename + string does not exist! end set resultLines = list set fileExtension = lower call splitext filename at 1 if fileExtension == string .cells begin set resultLines = call load_file_plaintext file...
def load_shape_data(filename: str) -> list[str]: if not os.path.isfile(filename): raise IOError('A file called ' + filename + ' does not exist!') resultLines = [] fileExtension = os.path.splitext(filename)[1].lower() if fileExtension == '.cells': resultLines = G...
Python
nomic_cornstack_python_v1
function delete_from_es self begin call on_commit _delete_from_es end function
def delete_from_es(self): transaction.on_commit(self._delete_from_es)
Python
nomic_cornstack_python_v1
class Line begin function __init__ self input begin set input = input end function decorator property function first self begin assert string Line in input at 0 set clean = split input at 0 return clean end function decorator property function identifier self begin return first at 1 end function decorator property func...
class Line(): def __init__(self, input): self.input = input @property def first(self): assert('Line' in self.input[0]) clean = self.input[0].split() return clean @property def identifier(self): return self.first[1] @property def NParameter(self): return int(self.first[2]) @property def index(se...
Python
zaydzuhri_stack_edu_python
function setup_QTIP_model self model_config begin comment print(zero) set model = model_config at string model set verbose = get model_config string verbose false comment implemented 'no', 'fid', 'close', 'perfect' set agg = get model_config string aggregate string no set agg = if expression agg == true then string fid...
def setup_QTIP_model(self, model_config): #print(zero) model = model_config['model'] verbose = model_config.get('verbose', False) agg = model_config.get('aggregate', 'no') #implemented 'no', 'fid', 'close', 'perfect' agg = 'fid' if(agg == True) else agg agg = 'no'...
Python
nomic_cornstack_python_v1
while true begin set n = integer input set c = n ^ 1 / 3 if c % 1 == 0 begin break end end
while True: n= int(input()) c=n**(1/3) if (c%1==0): break
Python
zaydzuhri_stack_edu_python
function id self id begin set _id = id end function
def id(self, id): self._id = id
Python
nomic_cornstack_python_v1
string Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] for i in range(len(matrix)): for j in rang...
""" Given a 2D integer array matrix, return the transpose of matrix. The transpose of a matrix is the matrix flipped over its main diagonal, switching the matrix's row and column indices. Example 1: Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] Output: [[1,4,7],[2,5,8],[3,6,9]] for i in range(len(matrix)): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Author : Rock Wayne comment @Created : 2021-02-23 02:50:56 comment @Last Modified : 2021-02-23 02:50:56 comment @Mail : lostlorder@gmail.com comment @Version : alpha-1.0 string # 给你一个由 n 个正整数组成的数组 nums 。 # # 你可以对数组的任意元素执行任意次数的两类操作: # # # 如果元素是 偶数 ,除以 2...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Rock Wayne # @Created : 2021-02-23 02:50:56 # @Last Modified : 2021-02-23 02:50:56 # @Mail : lostlorder@gmail.com # @Version : alpha-1.0 """ # 给你一个由 n 个正整数组成的数组 nums 。 # # 你可以对数组的任意元素执行任意次数的两类操作: # # # 如果元素是 偶数 ,除以 2 # # ...
Python
zaydzuhri_stack_edu_python
function bust_cache cache_type user_pk model_class=none begin set bust_keys = BUST_CACHES at cache_type if model_class begin set keys = list comprehension format CACHE_TYPES at k user_pk model_class for k in bust_keys end else begin set keys = list comprehension format CACHE_TYPES at k user_pk for k in bust_keys end ca...
def bust_cache(cache_type, user_pk, model_class=None): bust_keys = BUST_CACHES[cache_type] if model_class: keys = [CACHE_TYPES[k].format(user_pk, model_class) for k in bust_keys] else: keys = [CACHE_TYPES[k].format(user_pk) for k in bust_keys] cache.delete_many(keys)
Python
nomic_cornstack_python_v1
while n > 0 begin print n set n = n // 10 end
while n > 0: print(n) n=n//10
Python
zaydzuhri_stack_edu_python
function small_sample_data begin return call DataFrame data=dict string dpt list 1 2 3 4 5 6 7 8 9 ; string cyc list 1 1 1 1 1 1 2 2 2 ; string stp list 1 1 1 2 2 2 3 3 3 ; string cur list 1.0 1.0 1.0 0.0 0.0 0.0 - 1.0 - 1.0 - 1.0 ; string pot list 2.0 2.5 3.0 3.0 3.0 3.0 3.0 2.5 2.0 ; string time list 0.5 1.0 1.5 2.0 ...
def small_sample_data(): return pd.DataFrame(data={ "dpt": [1, 2, 3, 4, 5, 6, 7, 8, 9], "cyc": [1, 1, 1, 1, 1, 1, 2, 2, 2], "stp": [1, 1, 1, 2, 2, 2, 3, 3, 3], "cur": [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, -1.0, -1.0, -1.0], "pot": [2.0, 2.5, 3.0, 3.0, 3.0, 3.0, 3.0, 2.5, 2.0], ...
Python
nomic_cornstack_python_v1
comment Forms Example from tkinter import * comment define procedures function click char begin set char end function comment create the window set window = call Tk call resizable width=FALSE height=FALSE title window string window comment create main display label set display = call StringVar set label = grid row=0 co...
# Forms Example from tkinter import * # define procedures def click(char): display.set(char) # create the window window = Tk() window.resizable(width=FALSE, height=FALSE) window.title("window") # create main display label display = StringVar() label = Label(window, textvariable=display, fg="black...
Python
zaydzuhri_stack_edu_python
function lighter clr f=1 / 3 begin set gaps = list comprehension f * 1 - val for val in clr set new_clr = list comprehension val + gap for tuple gap val in zip gaps clr return new_clr end function
def lighter(clr, f=1/3): gaps = [f*(1 - val) for val in clr] new_clr = [val + gap for gap, val in zip(gaps, clr)] return new_clr
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment Almost equilateral triangles comment Problem 94 comment It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units. comment We shall define an almost equilateral...
# -*- coding: utf-8 -*- #Almost equilateral triangles #Problem 94 #It is easily proved that no equilateral triangle exists with integral length sides and integral area. However, the almost equilateral triangle 5-5-6 has an area of 12 square units. #We shall define an almost equilateral triangle to be a triangle for wh...
Python
zaydzuhri_stack_edu_python
import os import time while true begin try begin call system if expression name == string nt then string cls else string clear comment NIM: 2009106002 + 10 = 12 set angka = integer input string Masukkan angka: set z = 1 set a = 1 while z <= angka begin print a set a = a + 1 if a == 10 begin set a = a - 9 end set z = z ...
import os import time while True: try: os.system('cls' if os.name == 'nt' else 'clear') #NIM: 2009106002 + 10 = 12 angka = int(input("Masukkan angka: ")) z = 1 a = 1 while z <= angka: print (a) a += 1 if a == 10: a ...
Python
zaydzuhri_stack_edu_python
function _get_ntfs_resident_inode self offset filesystem mft_record_size begin set block_size = block_size set offset_block = integer offset / block_size set inode = call open_meta 0 set mft_entry = 0 for attr in inode begin for run in attr begin for block in range len begin if addr + block == offset_block begin set mf...
def _get_ntfs_resident_inode(self, offset, filesystem, mft_record_size): block_size = filesystem.info.block_size offset_block = int(offset / block_size) inode = filesystem.open_meta(0) mft_entry = 0 for attr in inode: for run in attr: for block in range(run.len): if run.addr...
Python
nomic_cornstack_python_v1
comment !/bin/bash/python import random import binascii import sys import operator import base64 from Crypto.Cipher import AES class cbc_oracle begin function __init__ self begin set iv = bytearray call rand_key_gen 16 set cipher = call new call rand_key_gen 16 end function function parse_data self data begin set data ...
#!/bin/bash/python import random import binascii import sys import operator import base64 from Crypto.Cipher import AES class cbc_oracle: def __init__(self): self.iv = bytearray(self.rand_key_gen(16)) self.cipher = AES.new(self.rand_key_gen(16),) def parse_data(self, data): data = str...
Python
zaydzuhri_stack_edu_python
string exceptions ========== A module that contains MCP9809 exception hierarchy. message (required!) (should be root message + caller message) info: (required!) path_to_error (required!) minimal_message (required!) - minimal_message is set inside this module, should not be set elsewhere - message is set inside this mod...
""" exceptions ========== A module that contains MCP9809 exception hierarchy. message (required!) (should be root message + caller message) info: (required!) path_to_error (required!) minimal_message (required!) - minimal_message is set inside this module, should not be set elsewhere - message is set inside...
Python
zaydzuhri_stack_edu_python
function nextImage self begin return call nextBatch 1 end function
def nextImage(self): return self.nextBatch(1)
Python
nomic_cornstack_python_v1
function wepbuy self begin set thismsg = string + ESC + string 14C + ESC + string 1;34m + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + A220 + ESC + string 0;34m + A220 ...
def wepbuy(self): thismsg = "\r\n"+self.ESC+"14C"+self.ESC+"1;34m"+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+self.A220+...
Python
nomic_cornstack_python_v1
comment 此示例用于示意用二进制方式读取一个内部存有文字信息的文件内容 try begin comment 用二进制打开 r就不能省 set fr = open string filetest.txt string rb set b = read fr comment 把字节串解码为文字 当然前提是你知道是个文件 set s = decode b string utf-8 comment 你在Windows运行 换行会打印\r\n print b print s print length b comment b2=fr.read(1) comment b3 = fr.readline() comment b3 = fr.rea...
# 此示例用于示意用二进制方式读取一个内部存有文字信息的文件内容 try: fr = open("filetest.txt", 'rb') # 用二进制打开 r就不能省 b = fr.read() s = b.decode("utf-8") # 把字节串解码为文字 当然前提是你知道是个文件 print(b) # 你在Windows运行 换行会打印\r\n print(s) print(len(b)) # b2=fr.read(1) # b3 = fr.readline() # b3 = fr.readline() # print(b3) ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 from twisted.internet import reactor , protocol from autobahn.twisted.websocket import WebSocketServerFactory , WebSocketServerProtocol , listenWS from twisted.python.log import startLogging , msg import sys class ProcessProtocol extends ProcessProtocol begin string I handle a child proces...
#!/usr/bin/env python3 from twisted.internet import reactor, protocol from autobahn.twisted.websocket import WebSocketServerFactory, \ WebSocketServerProtocol, \ listenWS from twisted.python.log import startLogging, msg import sys class ProcessProtocol(protocol.ProcessProtocol): """ I handle a child proces...
Python
zaydzuhri_stack_edu_python