code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import struct from scapy.main import interact from scapy.packet import Packet , bind_layers from scapy.layers.inet import TCP from scapy.fields import ShortField , ByteField , ByteEnumField , XByteField , XShortField , FieldLenField , StrLenField class ModbusMBAP extends Packet begin string Modbus TCP base packet layer...
import struct from scapy.main import interact from scapy.packet import Packet, bind_layers from scapy.layers.inet import TCP from scapy.fields import ShortField, ByteField, ByteEnumField, XByteField, XShortField, FieldLenField, StrLenField class ModbusMBAP(Packet): """Modbus TCP base packet layer. This represent...
Python
zaydzuhri_stack_edu_python
function searchForEvent file begin set MatchRunEvent = compile string Run: [0-9]+ Event: [0-9]+$ comment I'm just grabbing the last twenty lines for the hell of it set lines = call tailNLinesFromFile file 20 set lastMatch = none for line in lines begin if search strip line begin set matches = find all strip line set la...
def searchForEvent(file): MatchRunEvent = re.compile("Run: [0-9]+ Event: [0-9]+$") # I'm just grabbing the last twenty lines for the hell of it lines = tailNLinesFromFile(file, 20) lastMatch = None for line in lines: if MatchRunEvent.search(line.strip()): matches = MatchRunEve...
Python
nomic_cornstack_python_v1
import numpy as np comment model building functions function build_layercake begin string Build a layercake model 2d section comment Generate 10 random value layers in a single trace set rdm = call rand 10 1 set a = ones tuple 10 1 for i in range 10 begin set a = horizontal stack tuple a rdm end set a = a at tuple slic...
import numpy as np ############################################################################# #model building functions def build_layercake(): '''Build a layercake model 2d section''' #Generate 10 random value layers in a single trace rdm = np.random.rand(10,1) a = np.ones((10,1)) fo...
Python
zaydzuhri_stack_edu_python
function test_filter_function_all self begin call register_filter lambda x -> true assert true call streamfilter data call register_filter lambda x -> false assert false call streamfilter data end function
def test_filter_function_all(self): self.es.register_filter(lambda x: True) self.assertTrue(self.es.streamfilter(self.data)) self.es.register_filter(lambda x: False) self.assertFalse(self.es.streamfilter(self.data))
Python
nomic_cornstack_python_v1
function reset self begin set hand = list end function
def reset(self): self.hand = []
Python
nomic_cornstack_python_v1
function spiketimes2stim pos section spiketimes begin set spiketimes_vec = call Vector comment convert spiketimes to neuron vector call from_python spiketimes comment make stimulus set stim = call VecStim pos sec=section call play spiketimes_vec return tuple stim spiketimes_vec end function
def spiketimes2stim(pos, section, spiketimes): spiketimes_vec = h.Vector() spiketimes_vec.from_python(spiketimes) # convert spiketimes to neuron vector # make stimulus stim = h.VecStim(pos, sec=section) stim.play(spiketimes_vec) return stim, spiketimes_vec
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue May 8 13:40:28 2018 @author: ikira comment -*- coding: utf-8 -*- string Created on Wed May 2 13:36:35 2018 @author: ikira from pandas import DataFrame from pandas import Series from pandas import concat from pandas import read_csv from pandas import datetime from skle...
# -*- coding: utf-8 -*- """ Created on Tue May 8 13:40:28 2018 @author: ikira """ # -*- coding: utf-8 -*- """ Created on Wed May 2 13:36:35 2018 @author: ikira """ from pandas import DataFrame from pandas import Series from pandas import concat from pandas import read_csv from pandas import datetime from sklearn....
Python
zaydzuhri_stack_edu_python
comment !/bin/python3 import math import os import random import re import sys from heapq import heappop , heappush , heapify comment Complete the 'kruskals' function below. comment The function is expected to return an INTEGER. comment The function accepts WEIGHTED_INTEGER_GRAPH g as parameter. comment For the weighte...
#!/bin/python3 import math import os import random import re import sys from heapq import heappop, heappush, heapify # # Complete the 'kruskals' function below. # # The function is expected to return an INTEGER. # The function accepts WEIGHTED_INTEGER_GRAPH g as parameter. # # # For the weighted graph, <name>: # # 1...
Python
zaydzuhri_stack_edu_python
import requests from datetime import datetime , timedelta function get_trending_repositories top_size begin set week_ago = string format time call utcnow - time delta days=7 string %Y-%m-%d set request_headers = dict string Accept string application/vnd.github.v3+json ; string User-Agent string wwarne set request_param...
import requests from datetime import datetime, timedelta def get_trending_repositories(top_size): week_ago = (datetime.utcnow() - timedelta(days=7)).strftime('%Y-%m-%d') request_headers = { 'Accept': 'application/vnd.github.v3+json', 'User-Agent': 'wwarne' } request_params = { ...
Python
zaydzuhri_stack_edu_python
import random import math import numpy as np import matplotlib.pyplot as plt import pandas as pd comment def process_data(train): comment train = train.iloc[:, [0, 2, 4, 10, 11, 12, 14]] comment # train.iloc[:, 6] = list(map(lambda x: 1 if x == " >50K" else -1, train.iloc[:, 6])) comment train.iloc[:, 6] = train.iloc[:...
import random import math import numpy as np import matplotlib.pyplot as plt import pandas as pd # def process_data(train): # train = train.iloc[:, [0, 2, 4, 10, 11, 12, 14]] # # train.iloc[:, 6] = list(map(lambda x: 1 if x == " >50K" else -1, train.iloc[:, 6])) # train.iloc[:, 6] = train.iloc[:, 6].apply(...
Python
zaydzuhri_stack_edu_python
comment 59_nicknames_length: function nicknames_len names begin string Input is a list set dict_nicknames = dict for i in names begin set dict_nicknames at capitalize i = length i end print dict_nicknames for i in keys dict_nicknames begin print format string {}, your nickname is: {}{}. i i at 0 dict_nicknames at i en...
# 59_nicknames_length: def nicknames_len(names): """ Input is a list """ dict_nicknames = {} for i in names: dict_nicknames[i.capitalize()] = len(i) print(dict_nicknames) for i in dict_nicknames.keys(): print("{}, your nickname is: {}{}.".format(i,i[0],dict_nicknames[i])) ...
Python
zaydzuhri_stack_edu_python
function search_for_data begin set p1s = list 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 61 67 71 set best = none set best_tuple = none for p1 in p1s begin for p2 in p1s begin set data = call sample_search p1 p2 if data begin if best is none begin set best = data set best_tuple = tuple p1 p2 end else if length data < ...
def search_for_data(): p1s = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 61, 67, 71] best = None best_tuple = None for p1 in p1s: for p2 in p1s: data = sample_search(p1, p2) if data: if best is None: best = data ...
Python
nomic_cornstack_python_v1
function create_venue_submission begin comment TODO: insert form data as a new Venue record in the db, instead (DONE) comment TODO: modify data to be the data object returned from db insertion try begin set name = get form string name set city = get form string city set state = get form string state set address = get f...
def create_venue_submission(): # TODO: insert form data as a new Venue record in the db, instead (DONE) # TODO: modify data to be the data object returned from db insertion try: name = request.form.get("name") city = request.form.get("city") state = r...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- comment @Author Bain.Bai comment For implementing basic function of CCIC code scripts import os , io , functools from shutil import copyfile set dir_dict = dict string 墨尔本 string \\192.168.5.201\MelNormal\04 物控部\口岸材料 ; string 悉尼 string \\192.168.5.214\Warehous...
# !/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author Bain.Bai # For implementing basic function of CCIC code scripts import os,io,functools from shutil import copyfile dir_dict ={"墨尔本":"\\\\192.168.5.201\MelNormal\\04 物控部\口岸材料","悉尼":"\\\\192.168.5.214\Warehouse\ANDY新发货文件","布里斯班":"\\\\192.168.5.214\Warehouse\布里斯班发...
Python
zaydzuhri_stack_edu_python
comment List set Internet = list string Microsoft string Google string Apple string Linux comment mengambil nilai list print Internet at 1 comment Mengganti nilai list set Internet at 2 = string Raspberry pi print Internet comment Menampilkan jumlah list print length Internet comment Menambah nilai List comment dari be...
#List Internet = ['Microsoft', 'Google', 'Apple', 'Linux'] #mengambil nilai list print (Internet[1]) #Mengganti nilai list Internet[2] = 'Raspberry pi' print (Internet) #Menampilkan jumlah list print (len(Internet)) #Menambah nilai List #dari belakang Internet.append('Phyton') #menggunakan indeks Internet.insert(...
Python
zaydzuhri_stack_edu_python
with open string referat.txt string r encoding=string utf-8 as f begin set content = string read f set l = length content print l set content_list = split content string set wordcount = length content_list print wordcount set content_new = replace content string . string ! with open string referat2.txt string w encodin...
with open('referat.txt', 'r', encoding='utf-8') as f: content=str(f.read()) l=len(content) print(l) content_list=content.split(' ') wordcount=len(content_list) print(wordcount) content_new=content.replace('.', '!') with open('referat2.txt', 'w', encoding='utf-8') as f2: f2.write(...
Python
zaydzuhri_stack_edu_python
function get_columns self table begin if table not in columns begin set columns at table = list comprehension row at 0 for row in iterate string describe + table end return columns at table end function
def get_columns(self, table): if table not in self.columns: self.columns[table] = [ row[0] for row in self.db.iter('describe ' + table)] return self.columns[table]
Python
nomic_cornstack_python_v1
import os import matplotlib.pyplot as plt import seaborn as sns from spend import YEARS , get_value set dir_images = string images string CODES Presidency Republic: 20000 Science and Technology: 24000 Education: 26000 Social Security: 33000 Health: 36000 Environment: 44000 Sport: 51000 set v_presidency = call get_value...
import os import matplotlib.pyplot as plt import seaborn as sns from spend import YEARS, get_value dir_images = "images" """ CODES Presidency Republic: 20000 Science and Technology: 24000 Education: 26000 Social Security: 33000 Health: 36000 Environment: 44000 Sport: 51000 """ v_presi...
Python
zaydzuhri_stack_edu_python
string Created on Feb 19, 2017 @author: MT class Solution extends object begin function shortestPalindrome self s begin string :type s: str :rtype: str set tuple i j = tuple 0 length s - 1 while j >= 0 begin if s at i == s at j begin set i = i + 1 end set j = j - 1 end if i == length s begin return s end set mid = s at...
''' Created on Feb 19, 2017 @author: MT ''' class Solution(object): def shortestPalindrome(self, s): """ :type s: str :rtype: str """ i, j = 0, len(s)-1 while j >= 0: if s[i] == s[j]: i += 1 j -= 1 if i == len(s): ...
Python
zaydzuhri_stack_edu_python
import os.path , subprocess from subprocess import STDOUT , PIPE function compile_java CLASSPATH java_file begin comment subprocess.check_call(['javac', java_file]) check call list CLASSPATH java_file end function function execute_java CLASSPATH2 java_file stdin begin set tuple java_class ext = call splitext java_file ...
import os.path,subprocess from subprocess import STDOUT,PIPE def compile_java(CLASSPATH,java_file): #subprocess.check_call(['javac', java_file]) subprocess.check_call([CLASSPATH, java_file]) def execute_java(CLASSPATH2,java_file, stdin): java_class,ext = os.path.splitext(java_file) cmd = [CLASSPATH2...
Python
zaydzuhri_stack_edu_python
import sys import re set T = integer read line stdin set results = list function dfs x begin global bimap global matched global visited if visited at x begin return false end set visited at x = true for tuple y link in enumerate bimap at x begin if link begin if y not in matched or call dfs matched at y begin set matc...
import sys import re T = int(sys.stdin.readline()) results = [] def dfs(x): global bimap global matched global visited if visited[x]: return False visited[x] = True for y, link in enumerate(bimap[x]): if link: if y not in matched or dfs(matched[y]): m...
Python
zaydzuhri_stack_edu_python
from socket import * set port = 5001
from socket import * port=5001
Python
zaydzuhri_stack_edu_python
comment Calculate the required number of renewable energy sources set solar_panels = 50 / 5 set wind_turbines = 50 / 12 set hydro_sources = 50 / 7 set geo_sources = 50 / 10 print string Number of solar panels required: round solar_panels print string Number of wind turbines required: round wind_turbines print string Nu...
# Calculate the required number of renewable energy sources solar_panels = 50 / 5 wind_turbines = 50 / 12 hydro_sources = 50 / 7 geo_sources = 50 / 10 print("Number of solar panels required:", round(solar_panels)) print("Number of wind turbines required:", round(wind_turbines)) print("Number of hydroelectric sources re...
Python
jtatman_500k
from telebot.types import InlineKeyboardMarkup , InlineKeyboardButton import string import random function daynumber year month begin from calendar import monthrange return call monthrange year month at 1 end function function days monthDays begin set markup = call InlineKeyboardMarkup set row_width = 5 set day2 = mont...
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton import string import random def daynumber(year,month): from calendar import monthrange return monthrange(year, month)[1] def days(monthDays): markup = InlineKeyboardMarkup() markup.row_width = 5 day2 = monthDays - 28 ...
Python
zaydzuhri_stack_edu_python
class MyException extends Exception begin pass end class
class MyException(Exception): pass
Python
jtatman_500k
import torch import torch.nn as nn import torch.nn.functional as F class Network extends Module begin function __init__ self begin call __init__ set conv1 = sequential conv 2d in_channels=3 out_channels=32 kernel_size=7 call BatchNorm2d 32 dropout 0.5 relu call MaxPool2d 2 set conv2 = sequential conv 2d in_channels=32 ...
import torch import torch.nn as nn import torch.nn.functional as F class Network(nn.Module): def __init__(self): super(Network,self).__init__() self.conv1=nn.Sequential( nn.Conv2d(in_channels=3,out_channels=32,kernel_size=7), nn.BatchNorm2d(32), nn.Drop...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment 进行原始的SQL查询¶ comment 在模型查询API不够用的情况下,你可以使用原始的SQL语句。 comment Django 提供两种方法使用原始SQL进行查询: comment 一种是使用Manager.raw()方法,进行原始查询并返回模型实例; comment 另一种是完全避开模型层,直接执行自定义的SQL语句。 string 进行原始查询¶ raw() 管理器方法用于原始的SQL查询,并返回模型的实例: Manager.raw(raw_query, params=None, translations=None)¶ 这个方法执行原始的SQL查询,...
# -*- coding: utf-8 -*- # 进行原始的SQL查询¶ # 在模型查询API不够用的情况下,你可以使用原始的SQL语句。 # Django 提供两种方法使用原始SQL进行查询: # 一种是使用Manager.raw()方法,进行原始查询并返回模型实例; # 另一种是完全避开模型层,直接执行自定义的SQL语句。 ''' 进行原始查询¶ raw() 管理器方法用于原始的SQL查询,并返回模型的实例: Manager.raw(raw_query, params=None, translations=None)¶ 这个方法执行原始的SQL查询,并返回一个django.db.models.query.RawQue...
Python
zaydzuhri_stack_edu_python
function max_import_size self begin return get pulumi self string max_import_size end function
def max_import_size(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "max_import_size")
Python
nomic_cornstack_python_v1
function plotresults plot1 lambda_val plottitle=string label1=string label2=string plot_2=false plot2=none begin plot plot1 color=string blue label=label1 + string λ= + string lambda_val if plot_2 == true begin plot plot2 color=string red label=label2 + string λ= + string lambda_val end title plt plottitle legend lo...
def plotresults(plot1, lambda_val, plottitle = '', label1 = '', label2 = '', plot_2 = False, plot2 = None): plt.plot(plot1, color = 'blue', label = label1 + ' λ=' + str(lambda_val)) if plot_2 == True: plt.plot(plot2, color = 'red', label = label2 + ' λ=' + str(lambda_val)) plt.title(plottitle) ...
Python
nomic_cornstack_python_v1
function b sample begin return list comprehension x for x in sample at string B if x end function
def b(sample: Dict[str, List[Optional[float]]]) -> List[float]: return [x for x in sample["B"] if x]
Python
nomic_cornstack_python_v1
string This module creates three generator expressions and uses itertools.product to get every combination of values. import itertools function main begin set genx1 = generator expression x ^ 2 for x in range 3 set genx2 = generator expression i for i in range 21 if i % 2 == 0 set genx3 = generator expression i for i i...
''' This module creates three generator expressions and uses itertools.product to get every combination of values. ''' import itertools def main(): genx1 = (x ** 2 for x in range(3)) genx2 = (i for i in range(21) if i % 2 == 0) genx3 = (i for i in range(20) if i % 2 != 0) # This prints out all com...
Python
zaydzuhri_stack_edu_python
comment vector.py from visual import * import math function make_grid unit n begin set nunit = unit * n set f = call frame for i in call xrange n + 1 begin if i % 5 == 0 begin set color = tuple 1 1 1 end else begin set color = tuple 0.5 0.5 0.5 end call curve pos=list tuple 0 i * unit 0 tuple nunit i * unit 0 color=col...
#vector.py from visual import * import math def make_grid(unit, n): nunit = unit * n f = frame() for i in xrange(n+1): if i%5==0: color = (1,1,1) else: color = (0.5, 0.5, 0.5) curve(pos=[(0,i*unit,0), (nunit, i*unit, 0)],color=color,frame=f) curve(p...
Python
zaydzuhri_stack_edu_python
function loopUnroling text data templateLoopRegex templateEndLoopHeadRegex templateRegexHead templateRegexTail endTag templateId begin while search templateLoopRegex text begin set match1 = search templateLoopRegex text set s1 = start match1 0 set e1 = call end 0 set match1 = text at slice s1 : e1 : set var = match1 a...
def loopUnroling(text, data, templateLoopRegex, templateEndLoopHeadRegex, templateRegexHead, templateRegexTail, endTag, templateId): while re.search(templateLoopRegex,text): match1 = re.search(templateLoopRegex,text) s1 = match1.start(0) ...
Python
nomic_cornstack_python_v1
function predict cls tweets return_dict=false begin if length tweets == 0 begin return list end set tweets_tokenize = list comprehension call tokenizer_tweet tweet for tweet in tweets set preprocess_for_model = call pad tweets_tokenize set preprocess_for_model_tensor = call numericalize preprocess_for_model device=dev...
def predict(cls, tweets, return_dict=False): if len(tweets) == 0: return [] tweets_tokenize = [cls.tokenizer_tweet(tweet) for tweet in tweets] preprocess_for_model = cls.TEXT.pad(tweets_tokenize) preprocess_for_model_tensor = cls.TEXT.numericalize(preprocess_for_model, device=cls.device) re...
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[1]: print string hello world comment In[6]: import turtle call fd 100 call right 144 call fd 100 comment In[9]: set s = string hello,world. string s comment In[ ]: comment In[ ]:
# coding: utf-8 # In[1]: print ('hello world') # In[6]: import turtle turtle.fd(100) turtle.right(144) turtle.fd(100) # In[9]: s='hello,world.' str(s) # In[ ]: # In[ ]:
Python
zaydzuhri_stack_edu_python
function to_projectlink self begin set thumb_image_url = reverse string project_serve_file args=list short_name logo set args = dict string abreviation short_name ; string title short_name ; string description description ; string URL reverse string comicsite.views.site args=list short_name ; string download URL string...
def to_projectlink(self): thumb_image_url = reverse('project_serve_file', args=[self.short_name,self.logo]) args = {"abreviation":self.short_name, "title":self.short_name, "description":self.description, "URL":reverse('comicsite.views.site', args=[self.s...
Python
nomic_cornstack_python_v1
import os import pickle import numpy as np from numpy.random import seed seed 1111 from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Embedding , SpatialDropout1D , LSTM , Dense from sklearn.model_selection i...
import os import pickle import numpy as np from numpy.random import seed seed(1111) from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Embedding, SpatialDropout1D, LSTM, Dense from sklearn.model_sele...
Python
zaydzuhri_stack_edu_python
function uniqueString self begin comment this is the informal UUID algorithm of comment http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213761 comment by Carl Free Jr set t = call long time * 1000 end function
def uniqueString(self): # this is the informal UUID algorithm of # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/213761 # by Carl Free Jr t = long( time.time() * 1000 )
Python
nomic_cornstack_python_v1
import unittest function get_products_of_all_ints_except_at_index int_list begin comment Take a list of integers and return a list of the products comment e.g. given [1, 7, 3, 4] comment produce [84, 12, 28, 21] comment Rule: you cannot use division in your solution set n = length int_list set product_list = list compr...
import unittest def get_products_of_all_ints_except_at_index(int_list): # Take a list of integers and return a list of the products # e.g. given [1, 7, 3, 4] # produce [84, 12, 28, 21] # Rule: you cannot use division in your solution n = len(int_list) product_list = [1 for x in int_list...
Python
zaydzuhri_stack_edu_python
function output_salesforce_to self writer remove_date=string begin if owner begin set parent_account = call civic_no_city end else begin set parent_account = string end set record = list string System Admin call account_name parent_account work_phone_1 license_type license_number string string string string busine...
def output_salesforce_to(self, writer, remove_date=''): if self.owner: parent_account = self.owner.civic_no_city() else: parent_account = '' record = [ 'System Admin', # Record Owner self.account_name(), # Account Name ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import numpy as np import pandas as pd import xgboost as xgb import csv function swap_column data col1 col2 begin string Swap two columns of a matrix set tmp = call tolist set data at tuple slice : : col1 = data at tuple slice : : col2 set data at tuple slice : : col2 = tmp return data...
#!/usr/bin/python import numpy as np import pandas as pd import xgboost as xgb import csv def swap_column(data, col1, col2): """ Swap two columns of a matrix """ tmp = data[:,col1].tolist() data[:,col1] = data[:,col2] data[:,col2] = tmp return data def extract_data(filename): """ Extract data from file "...
Python
zaydzuhri_stack_edu_python
string Tallene i opgaven er ligeligt fordelt i intervallet import matplotlib.pyplot as plt function make_list_from_data begin set fh = open string million_integers.txt set data = read fh set data_lines = split data string set data_lines = data_lines at slice : - 1 : return list comprehension integer num for num in da...
""" Tallene i opgaven er ligeligt fordelt i intervallet """ import matplotlib.pyplot as plt def make_list_from_data(): fh = open('million_integers.txt') data = fh.read() data_lines = data.split('\n') data_lines = data_lines[:-1] return [int(num) for num in data_lines] integers = make_list_from_dat...
Python
zaydzuhri_stack_edu_python
function get_identity_notification_attributes self Identities begin pass end function
def get_identity_notification_attributes(self, Identities: List) -> Dict: pass
Python
nomic_cornstack_python_v1
function build_numbers_list top_num bottom_num=0 step=1 begin string Builds a list out of a given range of numbers (which is silly because you can assign it) and prints it out and returns the value. Takes an argument of the top of the list, an optional argument of the bottom of the list, and an optional argument of the...
def build_numbers_list(top_num, bottom_num=0,step=1): """ Builds a list out of a given range of numbers (which is silly because you can assign it) and prints it out and returns the value. Takes an argument of the top of the list, an optional argument of the bottom of the list, and an optional argument of th...
Python
zaydzuhri_stack_edu_python
import numpy as np set arr = array list 1 2 3 4 5 6 7 8 for i in arr begin print i pass end for i in arr begin print i if i == 5 begin break end pass end set arr = array list list 1 2 3 list 4 5 6 list 7 8 9 for i in arr begin print i pass end for i in arr begin for j in i begin print j pass end pass end comment 使用ndit...
import numpy as np arr = np.array([1,2,3,4,5,6,7,8]) for i in arr: print(i) pass for i in arr: print(i) if i == 5: break pass arr = np.array([[1,2,3],[4,5,6],[7,8,9]]) for i in arr: print(i) pass for i in arr: for j in i: print(j) pass pass for i in np...
Python
zaydzuhri_stack_edu_python
function __deepcopy__ self memo begin set obj = call __class__ model for tuple k v in items __dict__ begin if k in tuple string _iter string _result_cache begin set __dict__ at k = none end else begin set __dict__ at k = deep copy v memo return obj end end end function
def __deepcopy__(self, memo): obj = self.__class__(self.model) for k, v in self.__dict__.items(): if k in ('_iter', '_result_cache'): obj.__dict__[k] = None else: obj.__dict__[k] = copy.deepcopy(v, memo) return obj
Python
nomic_cornstack_python_v1
comment encoding:utf-8 import json import wiki_crawler from lxml import etree import urllib import urllib.request import requests class Test extends object begin string test func function code2char self url begin set code_dict = dict string %26 string & ; string %27 string ' for tuple code char in items code_dict begin...
# encoding:utf-8 import json import wiki_crawler from lxml import etree import urllib import urllib.request import requests class Test(object): """ test func """ def code2char(self, url): code_dict = {"%26": "&", "%27": "'"} for code, char in code_dict.items(): if url.__c...
Python
zaydzuhri_stack_edu_python
function __str__ self begin return title end function
def __str__(self): return self.title
Python
nomic_cornstack_python_v1
function isSuperRelation self rhs begin return call issuperset call iteritems end function
def isSuperRelation(self, rhs): return set(self.iteritems()).issuperset(rhs.iteritems())
Python
nomic_cornstack_python_v1
function evaluate_addition self evaluationContext=none originalCaller=none objectsPassed=none charForUnknown=none method_call_depth=0 begin try begin set leftEvaluationValues = list set rightEvaluationValues = list if call get_left_expression begin if evaluationContext begin comment if left operand has the same defin...
def evaluate_addition(self, evaluationContext = None, originalCaller = None, objectsPassed = None, charForUnknown = None, method_call_depth = 0): try: leftEvaluationValues = [] rightEvaluationValues = [] if self.get_left_expression(): if evaluationContext: # if l...
Python
nomic_cornstack_python_v1
import sys function buildList L begin set L = sorted L at 0 for tuple idx ele in enumerate L begin call printTopPart L at slice idx : : call printBottomPart L idx end end function function printTopPart L begin set topPart = list L at 0 set topI = 1 while topI < length L begin append topPart string topPart at length to...
import sys def buildList(L): L = sorted(L[0]) for idx, ele in enumerate(L): printTopPart(L[idx:]) printBottomPart(L, idx) def printTopPart(L): topPart = [L[0]] topI = 1 while topI < len(L): topPart.append(str(topPart[len(topPart)...
Python
zaydzuhri_stack_edu_python
function get_html self begin raise call NotImplementedError end function
def get_html(self) -> Tuple[str, str]: raise NotImplementedError()
Python
nomic_cornstack_python_v1
class Node extends object begin function __init__ self x begin set val = x set left = none set right = none end function end class function construct_tree vals begin set root = call Node vals at 0 for val in vals at slice 1 : : begin set node = call Node val set tmp_node = root while true begin if val > val begin if ...
class Node(object): def __init__(self, x): self.val = x self.left = None self.right = None def construct_tree(vals): root = Node(vals[0]) for val in vals[1:]: node = Node(val) tmp_node = root while True: if node.val > tmp_node.val: ...
Python
jtatman_500k
function set_recording_vectors self i begin comment soma_v_vec = h.Vector() # Membrane potential vector at soma set attribute self string soma_v_vec_ + string i call Vector comment dend_v_vec = h.Vector() # Membrane potential vector at dendrite set attribute self string dend_v_vec_ + string i call Vector call record _r...
def set_recording_vectors(self, i): #soma_v_vec = h.Vector() # Membrane potential vector at soma setattr(self, 'soma_v_vec_' + str(i), h.Vector() ) #dend_v_vec = h.Vector() # Membrane potential vector at dendrite setattr(self, 'dend_v_vec_' + str(i), h.Vector() ) get...
Python
nomic_cornstack_python_v1
function TrainModel self features classes begin set root = call __build_tree__ features classes end function
def TrainModel(self, features, classes): self.root = self.__build_tree__(features, classes)
Python
nomic_cornstack_python_v1
class Student extends object begin set name = string Student end class set s = call Student comment 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性 print name comment 打印类的name属性 print name comment 给实例绑定name属性 set name = string Michael comment 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性 print name comment 但是类属性并未消失,用Student.name仍然可以访问 p...
class Student(object): name = "Student" s = Student() print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性 print(Student.name) # 打印类的name属性 s.name = 'Michael' # 给实例绑定name属性 print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性 print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问 del s.name # 如果删除实例的name属性 prin...
Python
zaydzuhri_stack_edu_python
string Arrays extend, append, insert, pop, del, clear comment l1 = [1, 2, 3] comment l2 = [4, 5, 6] comment l1.extend(l2) comment l1.extend('l2') # extende comment l2.append('l2') # insert no fim comment l2.insert(0, 'first') # insert no inicio comment print(l1) comment print(l2) comment l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9...
""" Arrays extend, append, insert, pop, del, clear """ # l1 = [1, 2, 3] # l2 = [4, 5, 6] # # l1.extend(l2) # l1.extend('l2') # extende # l2.append('l2') # insert no fim # l2.insert(0, 'first') # insert no inicio # # print(l1) # print(l2) # l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9] # # del(l1[2:5]) # print(l1) l2 = list(r...
Python
zaydzuhri_stack_edu_python
from django.db import models class Pet extends Model begin set SEX_CHOICES = list tuple string M string Male tuple string F string Female set name = call CharField max_length=100 set submitter = call CharField max_length=50 set species = call CharField max_length=50 set breed = call CharField max_length=50 blank=true s...
from django.db import models class Pet(models.Model): SEX_CHOICES = [('M', 'Male'), ('F', 'Female')] name = models.CharField(max_length=100) submitter = models.CharField(max_length=50) species = models.CharField(max_length=50) breed = models.CharField(max_length=50, blank=True) description = m...
Python
zaydzuhri_stack_edu_python
function next_rotation q_1 q_2 begin call check_representations q_2 if not call isclose t t begin raise call ValueError string Oops, to be a rotation, the first values must be the same: { t } != { t } end if not call isclose t t begin raise call ValueError string Oops, the norm squared of these two are not equal: { t }...
def next_rotation(q_1: Q, q_2: Q) -> Q: q_1.check_representations(q_2) if not math.isclose(q_1.t, q_2.t): raise ValueError(f"Oops, to be a rotation, the first values must be the same: {q_1.t} != {q_2.t}") if not math.isclose(norm_squared(q_1).t, norm_squared(q_2).t): raise ValueError(f"Oop...
Python
nomic_cornstack_python_v1
function whofaved_deviation self deviationid offset=0 limit=10 begin string Fetch a list of users who faved the deviation :param deviationid: The deviationid you want to fetch :param offset: the pagination offset :param limit: the pagination limit set response = call _req string /deviation/whofaved get_data=dict string...
def whofaved_deviation(self, deviationid, offset=0, limit=10): """Fetch a list of users who faved the deviation :param deviationid: The deviationid you want to fetch :param offset: the pagination offset :param limit: the pagination limit """ response = self._req('/devi...
Python
jtatman_500k
comment global import ivy import abc import importlib from typing import List comment local from ivy_builder.specs.spec import Spec from ivy_builder.specs import DatasetSpec from ivy_builder.specs.spec import locals_to_kwargs comment ToDo: fix cyclic imports, so this method can be imported from the builder module funct...
# global import ivy import abc import importlib from typing import List # local from ivy_builder.specs.spec import Spec from ivy_builder.specs import DatasetSpec from ivy_builder.specs.spec import locals_to_kwargs # ToDo: fix cyclic imports, so this method can be imported from the builder module def load_class_from_...
Python
jtatman_500k
function prepSimulation self nDays p_infect begin set p_infect = p_infect set nSus = zeros nDays + 1 comment initial susceptible set nSus at 0 = size set nInf = zeros nDays + 1 comment initial number of infected in population set nInf at 0 = I0 set nRec = zeros nDays + 1 set nRec at 0 = 0 set nDead = zeros nDays + 1 se...
def prepSimulation(self,nDays,p_infect): self.p_infect = p_infect self.nSus = np.zeros(nDays+1) self.nSus[0] = self.size # initial susceptible self.nInf = np.zeros(nDays+1) self.nInf[0] = self.I0 # initial number of infected in population self.nRec = np.zeros(nDays+1) ...
Python
nomic_cornstack_python_v1
function update_plot self i begin from oscillodsp.utils import modified_ylim from matplotlib.ticker import EngFormatter import time set app = oscillo_app comment When requested by UI, clear triggered flag synchronously if clear_trig begin set triggered = false comment Reset the request set clear_trig = false end commen...
def update_plot(self, i): from oscillodsp.utils import modified_ylim from matplotlib.ticker import EngFormatter import time app = self.oscillo_app # When requested by UI, clear triggered flag synchronously if self.clear_trig: self.triggered = False ...
Python
nomic_cornstack_python_v1
function get_solposAM location datetimes weather begin set count = length datetimes comment load the DLL set solposAM_dll = call LoadLibrary SOLPOSAMDLL set _get_solposAM = get_solposAM comment cast Python types as ctypes set _location = call *location set _datetime = call *datetimes set _weather = call *weather commen...
def get_solposAM(location, datetimes, weather): count = len(datetimes) # load the DLL solposAM_dll = ctypes.cdll.LoadLibrary(SOLPOSAMDLL) _get_solposAM = solposAM_dll.get_solposAM # cast Python types as ctypes _location = (ctypes.c_float * 3)(*location) _datetime = ((ctypes.c_int * 6) * coun...
Python
nomic_cornstack_python_v1
import abc class INotification begin decorator classmethod function __subclasshook__ cls subclass begin return has attribute subclass string send and callable send or NotImplemented end function decorator abstractmethod function send self begin raise NotImplementedError end function end class
import abc class INotification(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, subclass): return (hasattr(subclass, 'send') and callable(subclass.send) or NotImplemented) @abc.abstractmethod def send(self): raise NotImplementedError
Python
zaydzuhri_stack_edu_python
function keyboard_state self begin set keyboard_state_ptr = call addressof keyboard_state set _weakkeydict at keyboard_state_ptr = _ptr return call SeatKeyboardState keyboard_state_ptr end function
def keyboard_state(self) -> SeatKeyboardState: keyboard_state_ptr = ffi.addressof(self._ptr.keyboard_state) _weakkeydict[keyboard_state_ptr] = self._ptr return SeatKeyboardState(keyboard_state_ptr)
Python
nomic_cornstack_python_v1
string 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。 示例 1: 输入:root = [3,9,20,null,null,15,7] 输出:2 示例 2: 输入:root = [2,null,3,null,4,null,5,null,6] 输出:5 提示: 树中节点数的范围在 [0, 105] 内 -1000 <= Node.val <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree 著作权归领扣网络所有。商业转载请联系...
""" 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。 说明:叶子节点是指没有子节点的节点。 示例 1: 输入:root = [3,9,20,null,null,15,7] 输出:2 示例 2: 输入:root = [2,null,3,null,4,null,5,null,6] 输出:5 提示: 树中节点数的范围在 [0, 105] 内 -1000 <= Node.val <= 1000 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree 著作权归领扣网络所有。商业...
Python
zaydzuhri_stack_edu_python
import sys set input = readline set n = integer input set arr = list map int split input set new_arr = list sorted set arr set answer = list set dic = dictionary comprehension val : idx for tuple idx val in enumerate new_arr for i in arr begin print dic at i end=string end
import sys input = sys.stdin.readline n = int(input()) arr = list(map(int, input().split())) new_arr = list(sorted(set(arr))) answer = [] dic = {val: idx for idx, val in enumerate(new_arr)} for i in arr: print(dic[i], end=" ")
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment by Alejandro Rojo Gualix 2021-06 import re string por ver 'Pagué religiosamente lo que marcaba el taxímetro al taxista', 'Pagué religiosamente al taxista lo que marcaba el taxímetro', 'El superintendente, extraordinariamente disminuido por el susto, es hallado en el atolón de Murur...
# -*- coding: utf-8 -*- # by Alejandro Rojo Gualix 2021-06 import re """ por ver 'Pagué religiosamente lo que marcaba el taxímetro al taxista', 'Pagué religiosamente al taxista lo que marcaba el taxímetro', 'El superintendente, extraordinariamente disminuido por el susto, es hallado en el atolón de Murur...
Python
zaydzuhri_stack_edu_python
function setdefault self key def_val=none begin string Update key usage if found and return value, else set and return default. if key in self begin return self at key end set self at key = def_val return def_val end function
def setdefault (self, key, def_val=None): """Update key usage if found and return value, else set and return default.""" if key in self: return self[key] self[key] = def_val return def_val
Python
jtatman_500k
function anyarg symbol fact expr begin return call Or *[fact.subs(symbol, arg) for arg in expr.args] end function
def anyarg(symbol, fact, expr): return Or(*[fact.subs(symbol, arg) for arg in expr.args])
Python
nomic_cornstack_python_v1
from time import sleep from asciimatics.screen import Screen import re import itertools from collections import namedtuple , defaultdict from pprint import pprint from config import DEFAULT_BOARD from operator import itemgetter set token_board = string +------------+------------+------------+------------+ | | | | | | |...
from time import sleep from asciimatics.screen import Screen import re import itertools from collections import namedtuple, defaultdict from pprint import pprint from config import DEFAULT_BOARD from operator import itemgetter token_board = """+------------+------------+------------+------------+ | | ...
Python
zaydzuhri_stack_edu_python
function _rename_columns_step self op data_map begin if node_name != string RenameColumnsNode begin raise call TypeError string op was supposed to be a data_algebra.data_ops.RenameColumnsNode end set res = call _compose_polars_ops sources at 0 data_map=data_map if is instance res LazyFrame begin comment work around htt...
def _rename_columns_step(self, op: data_algebra.data_ops_types.OperatorPlatform, *, data_map: Dict[str, Any]): if op.node_name != "RenameColumnsNode": raise TypeError( "op was supposed to be a data_algebra.data_ops.RenameColumnsNode" ) res = self._compose_polars_o...
Python
nomic_cornstack_python_v1
function test_3_2_2_1 begin set c = counter function check v c begin call assert_equals v 5 call tick end function set p1 = call Promise set p2 = call then lambda v -> call check v c call fulfill 5 call assert_equals 1 call value end function
def test_3_2_2_1(): c = Counter() def check(v, c): assert_equals(v, 5) c.tick() p1 = Promise() p2 = p1.then(lambda v: check(v, c)) p1.fulfill(5) assert_equals(1, c.value())
Python
nomic_cornstack_python_v1
function forward self prot_x comp_x begin comment apply convolution for kernel in lin_kernels begin set prot_x = call activation call kernel prot_x end comment Attention set h_comp = unsqueeze relu call W_attention comp_x 1 set h_prot = relu call W_attention prot_x set wts = call bmm permute h_prot 0 2 1 set attn_weigh...
def forward(self, prot_x, comp_x): # apply convolution for kernel in self.lin_kernels: prot_x = self.activation(kernel(prot_x)) # Attention h_comp = torch.relu(self.W_attention(comp_x)).unsqueeze(1) h_prot = torch.relu(self.W_attention(prot_x)) wts = h_comp....
Python
nomic_cornstack_python_v1
function get_iconname self node_type name options=dict begin if node_type != string Vnf begin return node_type end set iconname = name + string .png set db = call get_db set vnf_name = get options string function name set vnf = get db vnf_name dict set iconname = get vnf string icon iconname if iconname in images begin...
def get_iconname(self, node_type, name, options={}): if node_type != 'Vnf': return node_type iconname = name + '.png' db = Catalog().get_db() vnf_name = options.get('function', name) vnf = db.get(vnf_name, {}) iconname = vnf.get('icon', iconname) if ...
Python
nomic_cornstack_python_v1
if price < 40 begin print string wow, what a deal! end else begin print string lil pricey end
if price < 40: print('wow, what a deal!') else: print('lil pricey')
Python
zaydzuhri_stack_edu_python
from collections import defaultdict from itertools import product import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy import sparse from scipy.linalg import inv from scipy.spatial import Delaunay from scipy.special import factorial comment TODO Add documentation cl...
from collections import defaultdict from itertools import product import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy import sparse from scipy.linalg import inv from scipy.spatial import Delaunay from scipy.special import factorial # TODO Add documentation class...
Python
zaydzuhri_stack_edu_python
import re from collections import Counter class Make_data begin set urls = list set error = list set error_5xx = list set line_count = 0 set get_count = 0 set post_count = 0 set head_count = 0 set put_count = 0 set top5 = list set top10 = list function print_5xx self begin set result = list for i in range 5 begin...
import re from collections import Counter class Make_data: urls = [] error = [] error_5xx = [] line_count = 0 get_count = 0 post_count = 0 head_count = 0 put_count = 0 top5 = [] top10 = [] def print_5xx(self): result = [] for i in range(5): resu...
Python
zaydzuhri_stack_edu_python
comment Penn State Abington comment IST 440W comment Fall 2016 comment Team Pump Your Brakes comment Members: Abu Sakif, David Austin, Qili Jian, Abu Chowdhury, Gary Martorana, Chakman Fung import os import RPi.GPIO as GPIO call setmode BOARD call setwarnings false setup GPIO 11 OUT comment PWM'Pulse-width Modulation' ...
#Penn State Abington #IST 440W #Fall 2016 #Team Pump Your Brakes #Members: Abu Sakif, David Austin, Qili Jian, Abu Chowdhury, Gary Martorana, Chakman Fung import os import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(11,GPIO.OUT) p = GPIO.PWM(11,50)#PWM'Pulse-width Modulation' puts pin...
Python
zaydzuhri_stack_edu_python
import requests import time from tqdm import tqdm from sys import argv , exit from colorama import Fore , Style function art begin return string _///_, . / ` ' '> ) o' __/_'> ( / _/ )_'> Welcome to Hodor ' "__/ /_/\_> ____/_/_/_/ /,---, _/ / "" /_/_/_/ /_(_(_(_ \ ( \_\_\_ )\ '__\_\_\_\__ ).\ //____|___\__) )_/ | _ '___...
import requests import time from tqdm import tqdm from sys import argv, exit from colorama import Fore, Style def art(): return """ _///_, . / ` ' '> ) o' __/_'> ( / _/ )_\'> Welcome to Hodor ...
Python
zaydzuhri_stack_edu_python
function _arg_pop cmdlist begin if length cmdlist == 0 begin return tuple none none end set level = pop cmdlist 0 if length cmdlist == 0 or cmdlist at 0 in _level_choice_list begin return tuple level none end set category = pop cmdlist 0 return tuple level category end function
def _arg_pop(cmdlist): if len(cmdlist) == 0: return (None, None) level = cmdlist.pop(0) if len(cmdlist) == 0 or cmdlist[0] in _level_choice_list: return (level, None) category = cmdlist.pop(0) return (level, category)
Python
nomic_cornstack_python_v1
function query self expr **kwargs begin function gen_table_expr table expr begin set resolver = dictionary comprehension name : call FakeSeries call to_pandas_dtype for tuple name dtype in zip names types set scope = call Scope level=0 resolvers=tuple resolver return call Expr expr=expr env=scope end function import py...
def query(self, expr, **kwargs): def gen_table_expr(table, expr): resolver = { name: FakeSeries(dtype.to_pandas_dtype()) for name, dtype in zip(table.schema.names, table.schema.types) } scope = Scope(level=0, resolvers=(resolver,)) ...
Python
nomic_cornstack_python_v1
comment Chris Hicks 2020 comment Uses Breadth-First Search (BFS) on a graph to efficiently compute the shortest path. from queue import Queue comment Stores graph using adjacency lists, input a list of edge tuples [('u', 'v'),...] class Graph begin function __init__ self edge_tuples=none begin comment High-level pass t...
# Chris Hicks 2020 # # Uses Breadth-First Search (BFS) on a graph to efficiently compute the shortest path. from queue import Queue # Stores graph using adjacency lists, input a list of edge tuples [('u', 'v'),...] class Graph: def __init__(self, edge_tuples=None): # High-level pass the edges to build a set of v...
Python
zaydzuhri_stack_edu_python
function test_calculate_kmer_diff self begin set result = call calculate_kmer_diff list 3 4 list string all string clip_analysis_test_peak_results.bed join path call test_dir string test call assertListEqual keys result list string all call assertListEqual keys result at string all list 3 4 end function
def test_calculate_kmer_diff(self): result = calculate_kmer_diff([3,4], ['all'], "clip_analysis_test_peak_results.bed", os.path.join(clipper.test_dir(), "test")) self.assertListEqual(result.keys(), ["all"]) self.assertListEqual(result['all'].keys(), [3,4])
Python
nomic_cornstack_python_v1
comment Calculate top 4 closest passwords in rockyou using the text similarity library comment Scramble these 4 along with the original passwords comment Output n strings (depending on the user input) import sys , random import jellyfish as jf from sets import Set from a import * import random function load_pws_in_memo...
## Calculate top 4 closest passwords in rockyou using the text similarity library ## Scramble these 4 along with the original passwords ## Output n strings (depending on the user input) import sys, random import jellyfish as jf from sets import Set from a import * import random def load_pws_in_memory(txt_file_path): ...
Python
zaydzuhri_stack_edu_python
class faith_ascii begin function __init__ self n begin set n = n print string __init__ n end function function __del__ self begin print string __del__ end function function num self begin set l = list for i in range 0 127 begin append l character i end comment print(chr(i)) return l end function end class class faith_...
class faith_ascii(): def __init__(self, n): self.n = n print('__init__', self.n) def __del__(self): print('__del__') def num(self): l = [] for i in range(0, 127): l.append(chr(i)) # print(chr(i)) return l class faith_add(): def __i...
Python
zaydzuhri_stack_edu_python
function main begin set P = call HCR while length P > 22 begin call reiniciar_sistema print string Buscando una mejor solución, Longitud del Path length P set P = call HCR end print P print length P end function
def main(): P = HCR() while len(P) > 22: reiniciar_sistema() print('\nBuscando una mejor solución, Longitud del Path', len(P)) P = HCR() print(P) print(len(P))
Python
nomic_cornstack_python_v1
function convertType self dbType dataType begin set typeCode = STRING if dataType in NUMBER_TYPES begin set typeCode = NUMBER if useFloat and dataType in FLOAT_TYPES begin set typeCode = float end end else if dataType in BINARY_TYPES begin set typeCode = BINARY end else if starts with dataType string DATE begin set typ...
def convertType(self, dbType, dataType): typeCode = STRING if dataType in NUMBER_TYPES: typeCode = NUMBER if self.useFloat and dataType in FLOAT_TYPES: typeCode = float elif dataType in BINARY_TYPES: typeCode = BINARY elif dataType.star...
Python
nomic_cornstack_python_v1
from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr , formataddr import smtplib function _format_sender_receiver s begin set tuple name addr = call parseaddr s return call formataddr tuple encode call Header name string utf-8 addr end function function main begin set s...
from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr import smtplib def _format_sender_receiver(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr)) def main(): smtp_server = 'smtp.163.com' smtp_server_por...
Python
zaydzuhri_stack_edu_python
import csv import time from Queue import Queue import os import threading from zipfile import ZipFile from lxml import etree function get_csv_writer csv_file attr_name begin set xml_writer_level = writer csv_file delimiter=string write row xml_writer_level list string ID attr_name return xml_writer_level end function c...
import csv import time from Queue import Queue import os import threading from zipfile import ZipFile from lxml import etree def get_csv_writer(csv_file, attr_name): xml_writer_level = csv.writer(csv_file, delimiter=' ') xml_writer_level.writerow(['ID', attr_name]) return xml_writer_level ...
Python
zaydzuhri_stack_edu_python
comment Heap Sort Implementation function heapify array i length begin string This function builds a max heap. Arguments: array -- list, containing integer values. i -- int, position in the array. set largest = i set left_child = 2 * i + 1 set right_child = 2 * i + 2 if left_child < length and array at left_child > arr...
## Heap Sort Implementation def heapify(array, i, length): ''' This function builds a max heap. Arguments: array -- list, containing integer values. i -- int, position in the array. ''' largest = i left_child = 2 * i + 1 right_child = 2 * i + 2 if left_child < length and array...
Python
zaydzuhri_stack_edu_python
string Priority Queue Queue priorities are from 0 to 10 from typing import Any set d = dict function enqueue elem priority=0 begin string Operation that add element to the end of the queue :param elem: element to be added :return: Nothing global d set v = list elem set k = priority if k in d begin append d at k elem e...
""" Priority Queue Queue priorities are from 0 to 10 """ from typing import Any d={} def enqueue(elem: Any, priority: int = 0) -> None: """ Operation that add element to the end of the queue :param elem: element to be added :return: Nothing """ global d v = [elem] k = priority if ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 from sys import stdin , stderr
#!/usr/bin/python3 from sys import stdin, stderr
Python
zaydzuhri_stack_edu_python
class Student begin function __init__ self name age gender college begin set name = name set age = age set gender = gender set college = college end function end class
class Student: def __init__(self, name, age, gender, college): self.name = name self.age = age self.gender = gender self.college = college
Python
iamtarun_python_18k_alpaca
string Problem 60 import itertools import math set MAX_ELEM = 500 function is_prime n begin for i in range 2 integer square root n + 1 begin if n % i == 0 begin return false end end return true end function if __name__ == string __main__ begin set primes = list comprehension i for i in range 1 MAX_ELEM if call is_prime...
""" Problem 60 """ import itertools import math MAX_ELEM = 500 def is_prime(n): for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True if __name__ == '__main__': primes = [i for i in range(1, MAX_ELEM) if is_prime(i)] groups = itertools.combinations(primes, 5)
Python
zaydzuhri_stack_edu_python
function stop_read_thread self begin if _serial_thread is not none begin set _reading = false join _serial_thread end end function
def stop_read_thread(self): if self._serial_thread is not None: self._reading = False self._serial_thread.join()
Python
nomic_cornstack_python_v1
comment tanpa filter set tempList = list for item in listItem begin if item % 2 == 0 begin append tempList item end end print tempList comment Dengan Filter set tempList2 = list filter lambda x -> x % 2 == 0 listItem print tempList2
#tanpa filter tempList=[] for item in listItem: if (item % 2==0): tempList.append(item) print(tempList) #Dengan Filter tempList2= list(filter(lambda x:x % 2==0,listItem)) print(tempList2)
Python
zaydzuhri_stack_edu_python
comment Name: Isaiah Mora comment Period: 2 comment Dice Rolling Simulator import random set r1 = 0 set r2 = 0 set r3 = 0 set r4 = 0 set r5 = 0 set r6 = 0 set rolls = 1 set number = integer input string How many rolls? while rolls <= number begin set roll = random integer 1 6 if roll == 1 begin set r1 = r1 + 1 end if r...
# Name: Isaiah Mora # Period: 2 # Dice Rolling Simulator import random r1 = 0 r2 = 0 r3 = 0 r4 = 0 r5 = 0 r6 = 0 rolls = 1 number = int(input("How many rolls? ")) while rolls <= number: roll = random.randint(1, 6) if roll == 1: r1 += 1 if roll == 2: r2 += 1 ...
Python
zaydzuhri_stack_edu_python
from os import listdir , path , remove import datetime import shutil function cleanup folder cutoffdays removeFiles begin set filenames = list directory folder for file in filenames begin set filePath = folder + string \ + file set fileTime = call fromtimestamp call getmtime filePath set now = now - time delta days=cut...
from os import listdir, path, remove import datetime import shutil def cleanup(folder,cutoffdays, removeFiles): filenames = listdir(folder) for file in filenames: filePath = folder + "\\" + file fileTime = datetime.datetime.fromtimestamp(path.getmtime(filePath)) now = datetime.datetime....
Python
zaydzuhri_stack_edu_python