code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function pc_output_buffers_full_avg self *args begin return call atsc_fs_checker_sptr_pc_output_buffers_full_avg self *args end function
def pc_output_buffers_full_avg(self, *args): return _atsc_swig.atsc_fs_checker_sptr_pc_output_buffers_full_avg(self, *args)
Python
nomic_cornstack_python_v1
import numpy as np set N = integer input set A = array list map int split input set tmp = sum print 3 ^ N - 2 ^ tmp
import numpy as np N = int(input()) A = np.array(list(map(int, input().split()))) tmp = (A%2==0).sum() print(3**N - 2**tmp)
Python
zaydzuhri_stack_edu_python
import math class Polygon begin function __init__ self nbrsides begin set nbr_sides = nbrsides end function function whoamI self begin if nbr_sides == 3 begin return string Triangle end else if nbr_sides == 4 begin return string Rectangle end else begin return string Polygon end end function function howmanysides self ...
import math class Polygon: def __init__(self,nbrsides): self.nbr_sides = nbrsides def whoamI(self): if self.nbr_sides == 3: return "Triangle" elif self.nbr_sides == 4: return "Rectangle" else: return "Polygon" def howmanysides(self): return...
Python
zaydzuhri_stack_edu_python
function get_scores_for_all_items self users=none begin set selected_emb_users = if expression users is not none then call emb_users users else weight set all_emb_items = weight set all_bias_items = weight comment (#users, #items) set scores = matrix multiply selected_emb_users t dist + view all_bias_items 1 - 1 return...
def get_scores_for_all_items(self, users = None): selected_emb_users = self.emb_users(users) if users is not None else self.emb_users.weight all_emb_items = self.emb_items.weight all_bias_items = self.bias_items.weight scores = torch.matmul(selected_emb_users, all_emb_items.t()) + all_bi...
Python
nomic_cornstack_python_v1
function is_prime n begin if n < 2 begin return false end for i in range 2 integer n ^ 0.5 + 1 begin if n % i == 0 begin return false end end return true end function function sum_primes start end begin if start > end begin return 0 end if call is_prime start begin return start + call sum_primes start + 1 end end retur...
def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def sum_primes(start, end): if start > end: return 0 if is_prime(start): return start + sum_primes(start + 1, end) return sum_primes(st...
Python
jtatman_500k
import sys , re , socket , traceback , threading , time from PyQt5.QtWidgets import QApplication , QDialog , QInputDialog , QHBoxLayout , QWidget , QSplitter , QPushButton , QLabel , QMainWindow , QVBoxLayout , QTextEdit , QLineEdit from PyQt5.QtCore import Qt , QThread , pyqtSignal class ListenThread extends QThread b...
import sys, re, socket, traceback, threading, time from PyQt5.QtWidgets import QApplication, QDialog, QInputDialog, QHBoxLayout, QWidget, QSplitter, QPushButton, QLabel, QMainWindow, QVBoxLayout, QTextEdit, QLineEdit from PyQt5.QtCore import Qt, QThread, pyqtSignal class ListenThread(QThread): sig = pyqtSignal(ob...
Python
zaydzuhri_stack_edu_python
import pygame as p from pygame.draw import * from random import randint call init set FPS = 1000 set c = 0 set points = 0 set screen = call set_mode tuple 1200 700 set font = call Font none 40 set m = 0 set n = 0 set RED = tuple 255 0 0 set white = tuple 255 255 255 set BLUE = tuple 0 0 255 set YELLOW = tuple 255 255 0...
import pygame as p from pygame.draw import * from random import randint p.init() FPS = 1000 c = 0 points = 0 screen = p.display.set_mode((1200, 700)) font = p.font.Font(None, 40) m = 0 n = 0 RED = (255, 0, 0) white = (255, 255, 255) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) GREEN = (0, 255, 0) MAGENTA = (255, 0, 255)...
Python
zaydzuhri_stack_edu_python
function download_url self begin return call create_download_url end function
def download_url(self): return self.create_download_url()
Python
nomic_cornstack_python_v1
comment Make spider body import turtle as trtl set spider = call Turtle call pensize 40 call circle 20 comment configure legs set n_legs = 8 set lengh = 70 set angle = 360 / n_legs call pensize 5 set n = 0 comment make legs while n < n_legs begin call goto 0 20 call setheading angle * n + 22.5 call forward lengh set n ...
#Make spider body import turtle as trtl spider = trtl.Turtle() spider.pensize(40) spider.circle(20) #configure legs n_legs = 8 lengh = 70 angle = 360 / n_legs spider.pensize(5) n = 0 #make legs while (n < n_legs ): spider.goto(0,20) spider.setheading(angle*n + 22.5) spider.forward(lengh) n = n +...
Python
zaydzuhri_stack_edu_python
comment printing the range of values and the boundry and step are user input set x = integer input string enter the lower bound: set y = integer input string enter the upper bound: set z = integer input string enter the step dunction values for i in range x y z begin print i end=string end print string
# printing the range of values and the boundry and step are user input x=int(input("enter the lower bound: ")) y=int(input("enter the upper bound: ")) z=int(input("enter the step dunction values ")) for i in range(x,y,z): print(i,end=" ") print("\n")
Python
zaydzuhri_stack_edu_python
comment Summation in Dual element Records List comment using list comprehension comment Initializing list set test_list = list tuple 6 7 tuple 2 4 tuple 8 9 tuple 6 2 comment printing original lists print string The original list is : + string test_list comment Summation in Dual element Records List comment using list ...
# Summation in Dual element Records List # using list comprehension # Initializing list test_list = [(6, 7), (2, 4), (8, 9), (6, 2)] # printing original lists print("The original list is : " + str(test_list)) # Summation in Dual element Records List # using list comprehension res = [ele[0] + ele[1] for...
Python
zaydzuhri_stack_edu_python
function prune_fs self oldest begin comment Define an error handler for deletion of entire directory tree. function on_rmtree_error func path excinfo begin string Error handler for shutil.rmtree -- simply log the error details. error format string rmtree error: func {} string func error format string path {} path error...
def prune_fs(self, oldest): # Define an error handler for deletion of entire directory tree. def on_rmtree_error(func, path, excinfo): """Error handler for shutil.rmtree -- simply log the error details.""" self.logger.error('rmtree error: func {}'.format(str(func))) ...
Python
nomic_cornstack_python_v1
string Реализовать метод __str__, позволяющий выводить все папки и файлы из данной, например так: > print(folder1) V folder1 |-> V folder2 | |-> V folder3 | | |-> file3 | |-> file2 |-> file1 А так же возможность проверить, находится ли файл или папка в другой папке: > print(file3 in folder2) True import shutil import o...
""" Реализовать метод __str__, позволяющий выводить все папки и файлы из данной, например так: > print(folder1) V folder1 |-> V folder2 | |-> V folder3 | | |-> file3 | |-> file2 |-> file1 А так же возможность проверить, находится ли файл или папка в другой папке: > print(file3 in folder2) True """ import sh...
Python
zaydzuhri_stack_edu_python
class Solution begin function isMatch self s p begin string :type s: str :type p: str :rtype: bool comment Base Case: if s == string and p == string begin return true end else if s == string begin if length p > 1 and p at 1 == string * begin return call isMatch s p at slice 2 : : end else begin return false end end...
class Solution: def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ # Base Case: if s == "" and p == "": return True elif s == "": if len(p) > 1 and p[1] == "*": return self.isMatch(s, p[2:])...
Python
zaydzuhri_stack_edu_python
function interaction_responses interaction i begin set agent_eid = agent_eid comment no agent, no response (REM: that's not right, but is given how we're creating interactions right now) if agent_eid is none begin return list end set end = end_clock for j in range i + 1 length interaction begin set next = interaction ...
def interaction_responses(interaction, i): agent_eid = interaction[i].agent_eid # no agent, no response (REM: that's not right, but is given how we're creating interactions right now) if agent_eid is None: return [] end = interaction[i].end_clock for j in range(i+1, len(interaction)): ne...
Python
nomic_cornstack_python_v1
class Solution extends object begin function plusOne self digits begin string :type digits: List[int] :rtype: List[int] set length = length digits set breakflag = false for i in range length - 1 - 1 - 1 begin if digits at i == 9 begin set digits at i = 0 end else begin set digits at i = digits at i + 1 set breakflag = ...
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ length = len(digits) breakflag = False for i in range(length-1,-1,-1): if digits[i] == 9: digits[i] = 0 else: ...
Python
zaydzuhri_stack_edu_python
function get_sent_entity_pairs sent begin set ent_pairs = list set dep = list comprehension dep_ for token in sent try begin if sum list comprehension count dep object for object in OBJECTS == 1 and sum list comprehension count dep object for object in SUBJECTS == 1 begin for token in sent begin comment identify objec...
def get_sent_entity_pairs(sent): ent_pairs = [] dep = [token.dep_ for token in sent] try: if sum([dep.count(object) for object in OBJECTS]) == 1 \ and sum([dep.count(object) for object in SUBJECTS]) == 1: for token in sent: if token.dep_ in ('obj', 'dobj')...
Python
nomic_cornstack_python_v1
comment Steps to install comment pip install -U \-f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 \clearwxPython comment Steps to build comment https://wxpython.org/blog/2017-08-17-builds-for-linux-with-pip/index.html comment !/usr/bin/python import wx function onButton event begin print string B...
# Steps to install #pip install -U \-f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-16.04 \clearwxPython # Steps to build #https://wxpython.org/blog/2017-08-17-builds-for-linux-with-pip/index.html #!/usr/bin/python import wx def onButton(event): print("Button pressed.") app = wx.App() frame =...
Python
zaydzuhri_stack_edu_python
function min_max_indexes seq begin set minimum = min enumerate seq key=lambda s -> s at 1 set maximum = max enumerate seq key=lambda s -> s at 1 return tuple minimum at 0 maximum at 0 end function set mylist = list 5 0 1 4 6 3 print call min_max_indexes mylist print mylist at 1 mylist at 4
def min_max_indexes(seq): minimum = min(enumerate(seq), key= lambda s: s[1]) maximum = max(enumerate(seq), key= lambda s: s[1]) return minimum[0], maximum[0] mylist = [5, 0, 1, 4, 6, 3] print(min_max_indexes(mylist)) print(mylist[1], mylist[4])
Python
zaydzuhri_stack_edu_python
function calc_effective_diffusivity self inlets=none outlets=none domain_area=none domain_length=none begin return call _calc_eff_prop inlets=inlets outlets=outlets domain_area=domain_area domain_length=domain_length end function
def calc_effective_diffusivity(self, inlets=None, outlets=None, domain_area=None, domain_length=None): return self._calc_eff_prop(inlets=inlets, outlets=outlets, domain_area=domain_area, domain_length=domain...
Python
nomic_cornstack_python_v1
function signalFilter_LPFButter signal LPF samplefreq NPole=8 begin set flpf = decimal LPF set sf = decimal samplefreq set wn = list flpf / sf / 2.0 set tuple b a = call butter NPole wn btype=string low output=string ba set zi = call lfilter_zi b a set tuple out zo = call lfilter b a signal zi=zi * signal at 0 return a...
def signalFilter_LPFButter(signal, LPF, samplefreq, NPole=8): flpf = float(LPF) sf = float(samplefreq) wn = [flpf/(sf/2.0)] b, a = scipy.signal.butter(NPole, wn, btype='low', output='ba') zi = scipy.signal.lfilter_zi(b,a) out, zo = scipy.signal.lfilter(b, a, signal, zi=zi*signal[0]) return(n...
Python
nomic_cornstack_python_v1
for i in a begin append t i end for i in t begin if index t i == integer b begin print i end end
for i in a: t.append(i) for i in t: if(t.index(i)==int(b)): print(i)
Python
zaydzuhri_stack_edu_python
for nu in new_users begin if lower nu in current_users begin print string reject end else begin print string pass end end
for nu in new_users: if nu.lower() in current_users: print("reject") else: print("pass")
Python
zaydzuhri_stack_edu_python
function wrapper *args **kwargs begin set detector = call NumericalErrorDetector error with call errstate divide=string call over=string call under=string ignore invalid=string call begin call seterrcall detector set returned = call decorated *args keyword kwargs end if detected is not none begin append returned at - 1...
def wrapper(*args: Any, **kwargs: Any) -> Any: detector = NumericalErrorDetector(self.error) with np.errstate(divide='call', over='call', under='ignore', invalid='call'): np.seterrcall(detector) returned = decorated(*args, **kwargs) if detector.detecte...
Python
nomic_cornstack_python_v1
import random set a = list for i in range 10 begin set n = random integer 1 100 append a n end print a set even = 0 set odd = 0 for i in a begin if i % 2 == 0 begin set even = even + 1 end else begin set odd = odd + 1 end end print string Even: even print string Odd: odd
import random a = [] for i in range(10): n = random.randint(1, 100) a.append(n) print(a) even = 0 odd = 0 for i in a: if i%2 == 0: even = even + 1 else: odd = odd + 1 print("Even:", even) print("Odd:", odd)
Python
zaydzuhri_stack_edu_python
function convertToEnumItemArray byte enumType begin Ellipsis end function
def convertToEnumItemArray(byte: int, enumType: cern.japc.value.EnumType) -> typing.List[cern.japc.value.EnumItem]: ...
Python
nomic_cornstack_python_v1
comment coding=utf-8 import cv2 import numpy as np from matplotlib import pyplot as plt set img = call imread string E:\TEST.jpg 0 comment 中值滤波 set img = call medianBlur img 5 set tuple ret th1 = call threshold img 127 255 THRESH_BINARY_INV set tuple image contours hierarchy = call findContours th1 RETR_TREE CHAIN_APPR...
# coding=utf-8 import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('E:\TEST.jpg', 0) # 中值滤波 img = cv2.medianBlur(img, 5) ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV) image, contours, hierarchy = cv2.findContours(th1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) img1 = cv2.dra...
Python
zaydzuhri_stack_edu_python
function includeInDump self begin pass end function
def includeInDump(self): pass
Python
nomic_cornstack_python_v1
string Write a Python program to get unique values from a list. set l = list split input print join string sorted set l
""" Write a Python program to get unique values from a list.""" l = list(input().split()) print(''.join(sorted(set(l))))
Python
zaydzuhri_stack_edu_python
function get self connect_app_sid begin string Constructs a AuthorizedConnectAppContext :param connect_app_sid: The SID of the Connect App to fetch :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectApp...
def get(self, connect_app_sid): """ Constructs a AuthorizedConnectAppContext :param connect_app_sid: The SID of the Connect App to fetch :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppContext :rtype: twilio.rest.api.v2010.account.authorized_c...
Python
jtatman_500k
string Задача 2.4 Вариант №7 Выполнил Петров Роман 1.1 import math function square v begin set s = v ^ 1 / 3 set s = integer s ^ 2 * 6 print string s = s return s end function if __name__ == string __main__ begin assert call square 8 == 24 msg string при V = 8 правильный ответ не получен assert call square 27 == 54 msg...
""" Задача 2.4 Вариант №7 Выполнил Петров Роман 1.1 """ import math def square(v): s = v**(1/3) s = int(s**2 * 6) print('s =',s) return s if __name__ == '__main__': assert square(8) == 24,'при V = 8 правильный ответ не получен' assert square(27) == 54,'при V = 27 правильный ответ не получен' ...
Python
zaydzuhri_stack_edu_python
comment playing with enumerate and zip to see how they work from numpy import linspace set emin = - 2.0 set emax = - emin set esteps = 11 set energy = linear space emin emax esteps set vector = linear space 1 12 12
#playing with enumerate and zip to see how they work from numpy import linspace emin=-2. emax=-emin esteps=11 energy=linspace(emin,emax,esteps) vector=linspace(1,12,12)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment CSCI 404 Project 1 comment Cameron Little comment A tokenizer that produces statistics about a corpus's words, word types, comment sentences, and bigrams. comment The biggest current issue is that there is no determinationbetween posessive comment and contractitive "'s"'s import co...
# -*- coding: utf-8 -*- # CSCI 404 Project 1 # Cameron Little # # A tokenizer that produces statistics about a corpus's words, word types, # sentences, and bigrams. # # The biggest current issue is that there is no determinationbetween posessive # and contractitive "'s"'s import copy import re import sys # the follo...
Python
zaydzuhri_stack_edu_python
from typing import Sequence import numpy as np from tezromach.layers import Activation , Linear , Sigmoid from tezromach.network import NeuralNet function create_nn_one_hidden input_size output_size activation=sigmoid begin return call NeuralNet list linear input_size=input_size output_size=input_size activation linear...
from typing import Sequence import numpy as np from tezromach.layers import Activation, Linear, Sigmoid from tezromach.network import NeuralNet def create_nn_one_hidden( input_size: int, output_size: int, activation: Activation = Sigmoid() ) -> NeuralNet: return NeuralNet([ Linear...
Python
zaydzuhri_stack_edu_python
function extract_features wav_path deltas=2 begin with catch warnings begin simple filter string ignore set signal = read wav wav_path at 1 end set frames = call mfcc signal numcep=26 comment Cepstral Mean Subtraction set frames = frames - mean frames axis=0 if deltas begin set differential = call get_deltas frames set...
def extract_features(wav_path, deltas = 2): with warnings.catch_warnings(): warnings.simplefilter("ignore") signal = wav.read(wav_path)[1] frames = features.mfcc(signal, numcep = 26) frames -= frames.mean(axis = 0) # Cepstral Mean Subtraction if deltas: differential = ge...
Python
nomic_cornstack_python_v1
from tkinter import * from tkinter import ttk , messagebox import csv import sqlite3 function coursescreen coursebutton tb_course begin set window = call Tk call minsize 500 400 title window string Student Information System call resizable false false call after 1 lambda -> call focus_force set varcode = call IntVar w...
from tkinter import * from tkinter import ttk, messagebox import csv import sqlite3 def coursescreen(coursebutton, tb_course): window = Tk() window.minsize(500, 400) window.title("Student Information System") window.resizable(False, False) window.after(1, lambda: window.focus_force()) varcode =...
Python
zaydzuhri_stack_edu_python
function expand self user expand expanded=set begin if self in expanded or type self in expanded or not expand begin return call unexpanded end add expanded self return to json self user false expanded end function
def expand(self, user: Optional["User"], expand: bool, expanded: Set[Union["IJsonableModel", type]] = set() ) -> JSONType: if self in expanded or type(self) in expanded or not expand: return self.unexpanded() expanded.add(self) return self.to_json(user, ...
Python
nomic_cornstack_python_v1
function gnss_position dset begin set file_path = call path string output_dilution_of_precision file_vars=vars comment Add date and DOPs fields to dataset if string date not in fields begin call add_text string date val=list comprehension string format time d string %Y/%m/%d %H:%M:%S for d in datetime unit=string YYYY/...
def gnss_position(dset: "Dataset") -> None: file_path = config.files.path("output_dilution_of_precision", file_vars=dset.vars) # Add date and DOPs fields to dataset if "date" not in dset.fields: dset.add_text( "date", val=[d.strftime("%Y/%m/%d %H:%M:%S") for d in dset.time.datetime], un...
Python
nomic_cornstack_python_v1
function hidden_tag self *fields begin if not fields begin set fields = list comprehension f for f in self if is instance f HiddenField end set rv = list string <div style="display:none;"> for field in fields begin if is instance field basestring begin set field = get attribute self field end append rv call unicode fie...
def hidden_tag(self, *fields): if not fields: fields = [f for f in self if isinstance(f, HiddenField)] rv = [u'<div style="display:none;">'] for field in fields: if isinstance(field, basestring): field = getattr(self, field) rv.append(unicode...
Python
nomic_cornstack_python_v1
comment 정수의 list를 생성했고 리스트의 이름을 list로 했다 set list = list 1 2 3 4 5 6 7 8 9 10 print list comment 변경할 위치를 변수a로 설정하고 숫자로 전환시켰다 set a = integer input string 변경할 위치(0~9): comment 변경할 값을 b라는 변수로 설정하고 숫자로 전환시켰다 set b = integer input string 새로운 값: comment 리스트의 a위치에 있는 값을 b로 변경시킴 set list at a = b print list comment 리스트에 추가할 값...
list=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #정수의 list를 생성했고 리스트의 이름을 list로 했다 print(list) a=int(input("변경할 위치(0~9):")) #변경할 위치를 변수a로 설정하고 숫자로 전환시켰다 b=int(input("새로운 값:")) #변경할 값을 b라는 변수로 설정하고 숫자로 전환시켰다 list[a]=b #리스트의 a위치에 있는 값을 b로 변경시킴 print(list) c=int(input("추가할 값:")) #리스트에 추가할...
Python
zaydzuhri_stack_edu_python
function unfinished finished_status update_interval table status_column edit_at_column begin string Create text sql statement query for sqlalchemy that getting all unfinished task. :param finished_status: int, status code that less than this will be considered as unfinished. :param update_interval: int, the record will...
def unfinished(finished_status, update_interval, table, status_column, edit_at_column): """ Create text sql statement query for sqlalchemy that getting all unfinished task. :param finished_status: int, status code that less than this will ...
Python
jtatman_500k
from pygame import Rect , display , draw from Consts import * from math import cos , sin , radians class Ball extends object begin set position = list integer 0.5 * SCREEN_WIDTH integer 0.7 * SCREEN_HEIGHT set radius = 10 set step = 10 comment degrees set angleOfDirection = - 45 function __init__ self begin set Rectang...
from pygame import Rect, display, draw from Consts import * from math import cos, sin, radians class Ball(object): position = [int(0.5 * SCREEN_WIDTH), int(0.7 * SCREEN_HEIGHT)] radius = 10 step = 10 angleOfDirection = -45 # degrees def __init__(self) -> None: self.Rectangle = Rect(self....
Python
zaydzuhri_stack_edu_python
function has_syncopation s begin return any generator expression i % 2 for tuple i v in enumerate s if v == string # end function
def has_syncopation(s): return any(i%2 for i,v in enumerate(s) if v=="#")
Python
zaydzuhri_stack_edu_python
function setup begin size 640 480 end function function draw begin global x if x >= 640 begin set x = 0 end set x = x + 3 comment sky blue call background 135 206 250 comment cloud call noStroke call ellipse x height / 2 50 50 call ellipse x + 30 height / 2 50 50 call ellipse x + 10 height / 2 - 20 50 50 end function
def setup(): size(640, 480) def draw(): global x if x >= 640: x = 0 x += 3 background(135, 206, 250) # sky blue # cloud noStroke() ellipse(x, height/2, 50, 50) ellipse(x+30, height/2, 50, 50) ellipse(x+10, height/2-20, 50, 50)
Python
zaydzuhri_stack_edu_python
function mul_interval x y begin set p1 = call lower_bound x * call lower_bound y set p2 = call lower_bound x * call upper_bound y set p3 = call upper_bound x * call lower_bound y set p4 = call upper_bound x * call upper_bound y return call interval min p1 p2 p3 p4 max p1 p2 p3 p4 end function
def mul_interval(x, y): p1 = lower_bound(x) * lower_bound(y) p2 = lower_bound(x) * upper_bound(y) p3 = upper_bound(x) * lower_bound(y) p4 = upper_bound(x) * upper_bound(y) return interval(min(p1, p2, p3, p4), max(p1, p2, p3, p4))
Python
nomic_cornstack_python_v1
function sackReceived self sack begin comment No need to pretend any more, because we just got a comment likely-up-to-date SACK from the client. set wasPretending = _pretendAcked set _pretendAcked = none set lastSackSeenByServer = sack if call handleSACK sack begin return true end if wasPretending is not none begin com...
def sackReceived(self, sack): # No need to pretend any more, because we just got a # likely-up-to-date SACK from the client. wasPretending = self._pretendAcked self._pretendAcked = None self.lastSackSeenByServer = sack if self.queue.handleSACK(sack): return True if wasPretending is not None: # Tr...
Python
nomic_cornstack_python_v1
function get_lan_cursor_parameters noc_name begin set search_string = noc_name set query = string SELECT DISTINCT athletes.full_name FROM athletes, linking_table, national_olympic_committees WHERE linking_table.national_olympic_committee_id = national_olympic_committees.id AND national_olympic_committees.abbreviation =...
def get_lan_cursor_parameters(noc_name): search_string = noc_name query = '''SELECT DISTINCT athletes.full_name FROM athletes, linking_table, national_olympic_committees WHERE linking_table.national_olympic_committee_id = national_olympic_committees.id AND ...
Python
nomic_cornstack_python_v1
comment Sofia Sackett comment XOR Cipher function main begin set question = print string Enter 'e' to encipher or 'd' to decipher. set mode = input string Choose mode: if mode == string e or mode == string E begin set text = lower input string Enter the text that you would like enciphered: set key = lower input string ...
# Sofia Sackett # XOR Cipher def main(): question = print("Enter 'e' to encipher or 'd' to decipher.") mode = input("Choose mode: ") if mode == 'e' or mode == 'E': text = input("Enter the text that you would like enciphered: ").lower() key = input("Enter the keyword: ").lower() pri...
Python
zaydzuhri_stack_edu_python
function __init__ self begin set _ll = call LowLevelLibs set _lib = ratchet end function
def __init__(self): self._ll = LowLevelLibs() self._lib = self._ll.ratchet
Python
nomic_cornstack_python_v1
comment Parent class class Animal begin function eat self begin print string Eating... end function function sleep self begin print string Sleeping... end function function sound self begin print string Making a sound... end function end class comment Child class inheriting from Animal class Dog extends Animal begin fu...
# Parent class class Animal: def eat(self): print("Eating...") def sleep(self): print("Sleeping...") def sound(self): print("Making a sound...") # Child class inheriting from Animal class Dog(Animal): def sleep(self): print("Dog is sleeping...zzz") def sound(self)...
Python
greatdarklord_python_dataset
string for line in file: print(line) set lines = list comprehension line for line in open string google_stock_data.csv print strip lines at 0 set csv = split strip lines at 0 string , print csv
"""for line in file: print(line) """ lines = [line for line in open("google_stock_data.csv")] print(lines[0].strip()) csv = lines[0].strip().split(",") print(csv)
Python
zaydzuhri_stack_edu_python
function configure_context_authentication self context context_id begin set authentication = context at string authentication set auth_type = authentication at string type if auth_type == string script-based and string script-based in authentication begin call _configure_context_authentication_script authentication at ...
def configure_context_authentication( self, context: collections.OrderedDict, context_id: int ): authentication = context["authentication"] auth_type = authentication["type"] if auth_type == "script-based" and "script-based" in authentication: self._configure_context_au...
Python
nomic_cornstack_python_v1
from threading import Thread import requests from threading import Thread from bs4 import BeautifulSoup from entities.anime import Anime from repositories.animes_repository import AnimesRepository from helpers import cleaner from entities.season import Season from entities.episode import Episode from manager_animes imp...
from threading import Thread import requests from threading import Thread from bs4 import BeautifulSoup from ..entities.anime import Anime from ..repositories.animes_repository import AnimesRepository from ..helpers import cleaner from ..entities.season import Season from ..entities.episode import Episode from .manag...
Python
zaydzuhri_stack_edu_python
from Tkinter import * import tkMessageBox import tkFileDialog set data = list comment root the name given to the entire window set root = call Tk call configure background=string light sea green set label1 = call Label root text=string Automated Algorithm to Source Code Conversion fg=string white bg=string light sea gr...
from Tkinter import * import tkMessageBox import tkFileDialog data = list() root = Tk() #root the name given to the entire window root.configure(background = 'light sea green') label1 = Label(root,text="Automated Algorithm to Source Code Conversion",fg = "white",bg = 'light sea green',font=("Helvetica", 35)) label1.p...
Python
zaydzuhri_stack_edu_python
function add_jobs_from_file self filename priority=false begin if _shutdown begin raise call RuntimeError string Dispatcher is shutting down. end set n = 0 with e_lock begin for job in call read_job_file filename begin if priority begin set priority = true end put job set n = n + 1 end end info string %i jobs requested...
def add_jobs_from_file(self, filename, priority=False): if self._shutdown: raise RuntimeError("Dispatcher is shutting down.") n = 0 with self.e_lock: for job in read_job_file(filename): if priority: job.priority = True s...
Python
nomic_cornstack_python_v1
function add_alert_notifier self aid nid begin return call _request format string /shodan/alert/{}/notifier/{} aid nid dict method=string put end function
def add_alert_notifier(self, aid, nid): return self._request('/shodan/alert/{}/notifier/{}'.format(aid, nid), {}, method='put')
Python
nomic_cornstack_python_v1
function get_decoders_names self begin if replay_source is none begin return list string P + string parameters_common_index + string . + string parameters_fs_index + string _E + string call get_encoder_number end if helper_decoders_one_class begin set decoders_names = list comprehension string P + string parameters_com...
def get_decoders_names(self): if self.replay_source is None: return ["P" + str(self.parameters_common_index) + "." + str(self.parameters_fs_index) + "_E" \ + str(self.get_encoder_number())] if self.helper_decoders_one_class: decoders_names = ["P" + st...
Python
nomic_cornstack_python_v1
string Testing the Binary Tree module Roman Yasinovskyy, 2018 import pytest from exercises.heaps import BinaryTree class TestBinaryTreeMethods begin string Testing the Binary Tree module decorator fixture scope=string function autouse=true function setup_class self begin string Setting up set b_movie_tree = call Binary...
""" Testing the Binary Tree module Roman Yasinovskyy, 2018 """ import pytest from exercises.heaps import BinaryTree class TestBinaryTreeMethods: """Testing the Binary Tree module""" @pytest.fixture(scope="function", autouse=True) def setup_class(self): """Setting up""" self.b_movie_tree ...
Python
zaydzuhri_stack_edu_python
function source_md5 self source_md5 begin set _source_md5 = source_md5 end function
def source_md5(self, source_md5): self._source_md5 = source_md5
Python
nomic_cornstack_python_v1
function timeofday data_frame column begin set data_frame_copy = copy data_frame set column_data = data_frame_copy at column set column_data = apply column_data lambda a -> hour print column_data set entries = call tolist set res_data_frame = call DataFrame entries columns=list string sentiment return res_data_frame en...
def timeofday(data_frame: pd.DataFrame, column: str) -> pd.DataFrame: data_frame_copy = data_frame.copy() column_data = data_frame_copy[column] column_data = column_data.apply(lambda a: datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S").hour) print(column_data) entries = column_data.values.tolist...
Python
nomic_cornstack_python_v1
set x = integer input print x // 500 * 1000 + x - 500 * x // 500 // 5 * 5
x = int(input()) print((x//500)*1000+((x-500*(x//500))//5)*5)
Python
zaydzuhri_stack_edu_python
function apply_activation_derivative self r begin comment We use 'r' directly here because its already activated, the only values that comment are used in this function are the last activations that were saved. if activation is none begin return r end if activation == string tanh begin return 1 - r ^ 2 end if activatio...
def apply_activation_derivative(self, r): # We use 'r' directly here because its already activated, the only values that # are used in this function are the last activations that were saved. if self.activation is None: return r if self.activation == 'tanh': ret...
Python
nomic_cornstack_python_v1
comment Your First Program comment Write a program to print "Python is fun". comment Note that the sentence starts with a capital letter. comment Hint comment Use print() function. print string Python is fun
#Your First Program # # #Write a program to print "Python is fun". #Note that the sentence starts with a capital letter. # #Hint #Use print() function. print("Python is fun")
Python
zaydzuhri_stack_edu_python
function merge_sort_descending arr begin if length arr <= 1 begin return arr end set mid = length arr // 2 set left_half = arr at slice : mid : set right_half = arr at slice mid : : set left_half = call merge_sort_descending left_half set right_half = call merge_sort_descending right_half return merge left_half rig...
def merge_sort_descending(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = arr[:mid] right_half = arr[mid:] left_half = merge_sort_descending(left_half) right_half = merge_sort_descending(right_half) return merge(left_half, right_half) def merge(left, right): ...
Python
jtatman_500k
function get_data filename begin set data = load pickle open filename string rb set tuple skeletons labels = tuple data at slice 0 : 5 : data at 5 return tuple skeletons labels end function
def get_data(filename): data = pickle.load(open(filename, 'rb')) skeletons, labels = data[0:5], data[5] return skeletons, labels
Python
nomic_cornstack_python_v1
for i in range length birlesik begin set birlesik at i = birlesik at i * 2 end print string birlestirilmis * 2: birlesik print string veri tipi: type birlesik
for i in range (len(birlesik)): birlesik[i]*=2 print("birlestirilmis * 2: ", birlesik) print("veri tipi: ",type(birlesik))
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Intel Aero Version of the Backyard Flyer Project. On GitHub rev3 import time from enum import Enum import numpy as np from udacidrone import Drone comment noqa: F401 from udacidrone.connection import MavlinkConnection , WebSocketConnection from udacidrone.messaging import MsgID clas...
# -*- coding: utf-8 -*- """ Intel Aero Version of the Backyard Flyer Project. On GitHub rev3 """ import time from enum import Enum import numpy as np from udacidrone import Drone from udacidrone.connection import MavlinkConnection, WebSocketConnection # noqa: F401 from udacidrone.messaging import MsgID ...
Python
zaydzuhri_stack_edu_python
comment !env/bin/python from datetime import datetime from app import db from app.models import Record , User comment Prepare the statement to create the database call create_all comment Create an admin for our application set admin = call User string admin string <insert-a-secret-password-here> add session admin comme...
#!env/bin/python from datetime import datetime from app import db from app.models import Record, User # Prepare the statement to create the database db.create_all() # Create an admin for our application admin = User('admin', '<insert-a-secret-password-here>') db.session.add(admin) # Note: user_id for Alice is 2 ali...
Python
zaydzuhri_stack_edu_python
function _check_if_validation_is_needed self run_specs_set begin set validation_is_needed = false for run_specs in run_specs_set begin set validation_is_needed = validation_is_needed or not run_specs at string train_specs at string no_validation end return validation_is_needed end function
def _check_if_validation_is_needed(self, run_specs_set): validation_is_needed = False for run_specs in run_specs_set: validation_is_needed = validation_is_needed or \ not run_specs['train_specs']['no_validation'] return validation_is_needed
Python
nomic_cornstack_python_v1
function convert_from_cls_format self cls_boxes cls_segms cls_keyps begin set box_list = list comprehension b for b in cls_boxes if length b > 0 if length box_list > 0 begin set boxes = concatenate box_list end else begin set boxes = none end if cls_segms is not none begin set segms = list comprehension s for slist in ...
def convert_from_cls_format(self,cls_boxes, cls_segms, cls_keyps): box_list = [b for b in cls_boxes if len(b) > 0] if len(box_list) > 0: boxes = np.concatenate(box_list) else: boxes = None if cls_segms is not None: segms = [s for slist in cls_segms for...
Python
nomic_cornstack_python_v1
function subscribe self event callback begin string Subscribes to an event, so when it's emitted all the callbacks subscribed, will be executed. We are not allowing double registration. Args event (string): The event to subscribed in the form of: "terra.<component>.<method>.<action>" callback (callable): The callback t...
def subscribe(self, event, callback): """Subscribes to an event, so when it's emitted all the callbacks subscribed, will be executed. We are not allowing double registration. Args event (string): The event to subscribed in the form of: "terra.<component>....
Python
jtatman_500k
function get_fitted_grid_object model_obj params feat_train target_train cv=5 begin call cprint string [Running Gridsearch] color=string blue set grid_pipeline = call create_model_pipeline model_obj is_grid=true set grid = grid search cv grid_pipeline params cv=cv fit grid feat_train target_train return grid end functi...
def get_fitted_grid_object( model_obj, params: List[Dict[str, List]], feat_train: pd.DataFrame, target_train: pd.Series, cv: int = 5 ) -> Any: cprint('[Running Gridsearch]', color = 'blue') grid_pipeline = create_model_pipeline(model_obj, is_grid=True) grid = GridSearchCV( ...
Python
nomic_cornstack_python_v1
function first_request begin comment If there is at least 1 request, return the first one if latest_requests begin return latest_requests at 0 end end function
def first_request(): # If there is at least 1 request, return the first one if HTTPretty.latest_requests: return HTTPretty.latest_requests[0]
Python
nomic_cornstack_python_v1
string displays a snowman on the UnicornHat import unicornhat as uh comment define the parts set snowman = list list 0 3 list 0 4 list 0 5 list 1 2 list 1 3 list 1 4 list 1 5 list 1 6 list 2 2 list 2 3 list 2 4 list 2 5 list 2 6 list 3 3 list 3 4 list 3 5 list 4 2 list 4 3 list 4 4 list 4 5 list 4 6 list 5 1 list 5 2 l...
""" displays a snowman on the UnicornHat """ import unicornhat as uh #define the parts snowman = [ [0, 3], [0, 4], [0, 5], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [3, 3], [3, 4], [3, 5], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5], [5, 6], [5,...
Python
zaydzuhri_stack_edu_python
from mcpi import minecraft from mcpi.vec3 import Vec3 from mcpi import block import time
from mcpi import minecraft from mcpi.vec3 import Vec3 from mcpi import block import time
Python
zaydzuhri_stack_edu_python
function build_executable source dest begin print string -> Building { source } ... end=string set home = expand user path string ~ run list string /usr/bin/g++ source string -std=c++17 string -isystem home + string /etl-18.1.3/include string -o dest stdout=DEVNULL stderr=DEVNULL call chmod path=dest mode=365 print str...
def build_executable(source: str, dest: str): print(f"-> Building {source}...", end='') home = os.path.expanduser('~') subprocess.run( ["/usr/bin/g++", source, "-std=c++17", "-isystem", home + "/etl-18.1.3/include", "-o", dest], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL ...
Python
nomic_cornstack_python_v1
string 1. Using default arguments we can give default value to the parameter. 2. Default arguments should follow the positional argument. function add a b c=9 begin print string A value is : a print string B value is : b print string C value is : c end function add 7 8
''' 1. Using default arguments we can give default value to the parameter. 2. Default arguments should follow the positional argument. ''' def add(a, b, c=9): print(' A value is : ', a) print(' B value is : ', b) print(' C value is : ', c) add(7, 8)
Python
zaydzuhri_stack_edu_python
import time comment import gspread import gdata.spreadsheet.service set g = call login string mohit.khatri1987@gmail.com string pod@+_)( set wID = string 1 set row1 = string 1 set column1 = string 1 set value1 = string value comment worksheet = g.open('DataSheet').get_worksheet(int(wID)) comment Say, you need A2 commen...
import time #import gspread import gdata.spreadsheet.service g = gspread.login('mohit.khatri1987@gmail.com', 'pod@+_)(') wID = '1' row1 ='1' column1 = '1' value1 = 'value' #worksheet = g.open('DataSheet').get_worksheet(int(wID)) # Say, you need A2 #val = worksheet.cell(2, 1).value #print val # And then update localti...
Python
zaydzuhri_stack_edu_python
function read_morph_map subject_from subject_to subjects_dir=none begin if subjects_dir is none begin if string SUBJECTS_DIR in environ begin set subjects_dir = environ at string SUBJECTS_DIR end else begin raise call ValueError string SUBJECTS_DIR environment variable not set end end comment Does the file exist set na...
def read_morph_map(subject_from, subject_to, subjects_dir=None): if subjects_dir is None: if 'SUBJECTS_DIR' in os.environ: subjects_dir = os.environ['SUBJECTS_DIR'] else: raise ValueError('SUBJECTS_DIR environment variable not set') # Does the file exist name = '%s/...
Python
nomic_cornstack_python_v1
comment coding:utf-8 string simple demo of extracting apk permission list the result will be saved in the "permission_list.csv" please put all apk file in the "source_apk" folder from androguard.core.bytecodes.apk import APK import os function file_name file_dir begin set file_list = list for tuple root dirs files in ...
#coding:utf-8 ''' simple demo of extracting apk permission list the result will be saved in the "permission_list.csv" please put all apk file in the "source_apk" folder ''' from androguard.core.bytecodes.apk import APK import os def file_name(file_dir): file_list = [] for root, dirs, files in os.walk(file_dir)...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment -*- coding:utf-8 -*- from typing import List from sortedcontainers import SortedList class Solution begin function longestSubarray self nums limit begin comment n = len(nums) comment ans = 0 comment left = 0 comment right = 0 comment s = [] comment while right < n: comment s.append(num...
#!/usr/bin/python3 # -*- coding:utf-8 -*- from typing import List from sortedcontainers import SortedList class Solution: def longestSubarray(self, nums: List[int], limit: int) -> int: # n = len(nums) # ans = 0 # left = 0 # right = 0 # s = [] # while right < n: ...
Python
zaydzuhri_stack_edu_python
function plot_assignment spec_df assignments_df col=string Intensity begin comment Get a list of unique molecules set molecules = unique comment The ttal number of traces are the number of unique molecules, the traces comment in the experimental data minus the frequency column set nitems = length molecules + 1 set colo...
def plot_assignment(spec_df, assignments_df, col="Intensity"): # Get a list of unique molecules molecules = assignments_df["Chemical Name"].unique() # The ttal number of traces are the number of unique molecules, the traces # in the experimental data minus the frequency column nitems = len(mole...
Python
nomic_cornstack_python_v1
from typing import List , Optional from discord.ext import commands from fastapi import APIRouter from pydantic import BaseModel from bot.utils import ConnectionUtil , get_conn class PartialAnswer extends BaseModel begin string Represents the model for an incomplete 8ball answer. set response : Optional at str set weig...
from typing import List, Optional from discord.ext import commands from fastapi import APIRouter from pydantic import BaseModel from bot.utils import ConnectionUtil, get_conn class PartialAnswer(BaseModel): """Represents the model for an incomplete 8ball answer.""" response: Optional[str] weight: Option...
Python
jtatman_500k
function run_anatomical_reorient anatomical_scan out_dir=none run=true begin import os import glob import nipype.interfaces.io as nio import nipype.pipeline.engine as pe set output = string anatomical_reorient set workflow = call Workflow name=string anatomical_reorient_workflow if not out_dir begin set out_dir = get c...
def run_anatomical_reorient(anatomical_scan, out_dir=None, run=True): import os import glob import nipype.interfaces.io as nio import nipype.pipeline.engine as pe output = "anatomical_reorient" workflow = pe.Workflow(name='anatomical_reorient_workflow') if not out_dir: out_dir =...
Python
nomic_cornstack_python_v1
import string import random function random_password begin set letters = ascii_letters set numbers = digits set password_characters = letters + numbers set password = join string generator expression random choice password_characters for i in range 6 return password end function print call random_password
import string import random def random_password(): letters = string.ascii_letters numbers = string.digits password_characters = letters + numbers password = ''.join(random.choice(password_characters) for i in range(6)) return password print(random_password())
Python
flytech_python_25k
function hours value begin if value in tuple none string begin return string end try begin return call integer call timedelta_to_hours value end except Exception begin return value end end function
def hours(value): if value in (None, u''): return u'' try: return integer(timedelta_to_hours(value)) except Exception: return value
Python
nomic_cornstack_python_v1
function create_dashboard_prefetch_with_http_info self dashboard_id **kwargs begin set all_params = list string dashboard_id string body append all_params string callback append all_params string _return_http_data_only append all_params string _preload_content append all_params string _request_timeout set params = loca...
def create_dashboard_prefetch_with_http_info(self, dashboard_id, **kwargs): all_params = ['dashboard_id', 'body'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params...
Python
nomic_cornstack_python_v1
import os import django set default environ string DJANGO_SETTINGS_MODULE string courseWebsite.settings setup django from courses.models import Course , Content , Section , SubSection function parse_variable line begin set colon = find line string : if colon == - 1 begin return list string end return list strip line a...
import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "courseWebsite.settings") django.setup() from courses.models import Course, Content, Section, SubSection def parse_variable(line): colon = line.find(':') if colon == -1: return [''] return [line[:colon].strip(), line[colon+1...
Python
zaydzuhri_stack_edu_python
function createCertificate req issuerCertKey serial validityPeriod digest=string sha256 begin set tuple issuerCert issuerKey = issuerCertKey set tuple notBefore notAfter = validityPeriod set cert = call X509 call set_serial_number serial call gmtime_adj_notBefore notBefore call gmtime_adj_notAfter notAfter call set_iss...
def createCertificate(req, issuerCertKey, serial, validityPeriod, digest="sha256"): issuerCert, issuerKey = issuerCertKey notBefore, notAfter = validityPeriod cert = crypto.X509() cert.set_serial_number(serial) cert.gmtime_adj_notBefore(notBefore) cert.gmtime_adj_notAfter(n...
Python
nomic_cornstack_python_v1
import os import shutil import random import glob import numpy as np import re change directory string /Volumes/Data/ML_Datasets/dogs-vs-cats/xtest set c = 0 set d = 0 for i in list directory begin if match string cat i begin set c = c + 1 end end for i in list directory begin if match string dog i begin set d = d + 1 ...
import os import shutil import random import glob import numpy as np import re os.chdir('/Volumes/Data/ML_Datasets/dogs-vs-cats/xtest') c =0 d =0 for i in os.listdir(): if re.match('cat',i): c +=1 for i in os.listdir(): if re.match('dog',i): d +=1 print(d,c) if os.path.isdir('dog') is Fals...
Python
zaydzuhri_stack_edu_python
comment Jens lösning för dag 1. Lite mindre kod, lite snyggare, (men färre for-loopar :(( ) comment Set istället för list i lösning två, och mycket mindre kladd. comment Så mycket lättare att använda ints som ints och inte som strings #genombrott #prohacker set mainList = list with open string ./inputsE/input01.txt st...
#Jens lösning för dag 1. Lite mindre kod, lite snyggare, (men färre for-loopar :(( ) #Set istället för list i lösning två, och mycket mindre kladd. #Så mycket lättare att använda ints som ints och inte som strings #genombrott #prohacker mainList =[] with open("./inputsE/input01.txt", "rt") as readFile: for line in...
Python
zaydzuhri_stack_edu_python
function getMacSystemSpec self data begin set data at string Operating System = strip decode check output string sw_vers -productName stderr=open devnull string w shell=true string utf-8 string set data at string OS Version = strip decode check output string sw_vers -productVersion stderr=open devnull string w shell=tr...
def getMacSystemSpec(self, data): data["Operating System"] = subprocess.check_output("sw_vers -productName",stderr=open(os.devnull, 'w'), shell=True).decode('utf-8').strip('\n') data["OS Version"] = subprocess.check_output("sw_vers -productVersion",stderr=open(os.devnull, 'w'), shell=True).decode('utf-...
Python
nomic_cornstack_python_v1
from collections import defaultdict , namedtuple from functools import reduce comment Generalnie zadanie to nic innego jak zaimplementowanie acyklicznego grafu comment skierowanego. Ze wzgledu na brak wiekszej ilosci czasu, ponizej prezentuje comment bardzo zubozona mozliwosc rozwiazania tego zadania. comment W przyszl...
from collections import defaultdict, namedtuple from functools import reduce # Generalnie zadanie to nic innego jak zaimplementowanie acyklicznego grafu # skierowanego. Ze wzgledu na brak wiekszej ilosci czasu, ponizej prezentuje # bardzo zubozona mozliwosc rozwiazania tego zadania. # W przyszlosci nalezaloby dodac w...
Python
zaydzuhri_stack_edu_python
import numpy as np set data = call rand 10 comment print(data) comment サイコロがとりうる値を配列に格納 set dice_data = array list 1 2 3 4 5 6 comment サイコロを1000回振る set calc_steps = 1000 comment 1〜6のデータの中から、1000回の抽出を実施 set dice_rolls = random choice dice_data calc_steps comment それぞれの数字がどれくらいの割合で抽出されたか計算 for i in range 1 7 begin set pi ...
import numpy as np data = np.random.rand(10) # print(data) # サイコロがとりうる値を配列に格納 dice_data = np.array([1, 2, 3, 4, 5, 6]) # サイコロを1000回振る calc_steps = 1000 # 1〜6のデータの中から、1000回の抽出を実施 dice_rolls = np.random.choice(dice_data, calc_steps) # それぞれの数字がどれくらいの割合で抽出されたか計算 for i in range(1, 7): pi = len(dice_rolls[dice_rolls==i]...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- comment 题目: 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList comment 解法: 其实这道题本质上是反转链表,不过没有限制说不能开辟新的内存空间,可以用头插法 class ListNode begin function __init__ self x begin set val = x set next = none end function end class class Solution begin comment 返回从尾部到头部的列表值序列,例如[1,2,3] function printListFromTailToHead self l...
# -*- coding:utf-8 -*- # 题目: 输入一个链表,按链表值从尾到头的顺序返回一个ArrayList # 解法: 其实这道题本质上是反转链表,不过没有限制说不能开辟新的内存空间,可以用头插法 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 返回从尾部到头部的列表值序列,例如[1,2,3] def printListFromTailToHead(self, listNode): if not listNode:...
Python
zaydzuhri_stack_edu_python
string Helpers to manage lines A line is a numpy array of points (2 float array) import numpy as np set BASIS_SEGMENT = array list list 0 0 list 1 0 comment --------------------------------------------------------------------------- # comment Lines function assert_is_line line begin string Check whether line is well de...
"""Helpers to manage lines A line is a numpy array of points (2 float array) """ import numpy as np BASIS_SEGMENT = np.array([[0, 0], [1, 0]]) # --------------------------------------------------------------------------- # # Lines def assert_is_line(line): """Check whether line is well defined""" assert is...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 set __author__ = string zice from UserTag import get_lsi , get_lda , LSI import re from model import Fan set pat = compile string "(.*)" set pat_lda = compile string \* function _get_topic_words_in_str_lsi topic_str begin set dict_of_a_topic = list set items = split topic_str string + for word in ...
# coding:utf-8 __author__ = 'zice' from UserTag import get_lsi,get_lda, LSI import re from model import Fan pat = re.compile(r'"(.*)"') pat_lda = re.compile(r'\*') def _get_topic_words_in_str_lsi(topic_str): dict_of_a_topic = [] items = topic_str.split('+') for word in items: result = pat.search(...
Python
zaydzuhri_stack_edu_python
import cv2 import time import numpy as np set filename = string rain.jpg set image = call imread filename if image is none begin raise exception string Not a valid picture end comment A standard for docstrings is to have it as the first thing in the function, comment and include information about argument(s) and return...
import cv2 import time import numpy as np filename = "rain.jpg" image = cv2.imread(filename) if image is None: raise Exception("Not a valid picture") # A standard for docstrings is to have it as the first thing in the function, # and include information about argument(s) and return value(s) if there are any def ...
Python
zaydzuhri_stack_edu_python
from django.utils import timezone from datetime import datetime from message.models import get_total_new_messages import random function log_sql sql begin set f = open string log.sql string a encoding=string utf-8 write f string + sql close f end function function add_user_information request context begin string Add ...
from django.utils import timezone from datetime import datetime from message.models import get_total_new_messages import random def log_sql(sql): f = open('log.sql', 'a', encoding='utf-8') f.write('\n' + sql) f.close() def add_user_information(request, context): """ Add total_new_messages to...
Python
zaydzuhri_stack_edu_python
from requests_oauthlib import OAuth1 from time import sleep , strftime import requests import logging set TIMEOUT = 60 set MAX_TWEETS_IN_FILE = 100000 set APP_KEY = string your-twitter-app-key set APP_SECRET = string your-twitter-app-secret set OAUTH_TOKEN = string your-twitter-oauth-token set OAUTH_TOKEN_SECRET = stri...
from requests_oauthlib import OAuth1 from time import sleep, strftime import requests import logging TIMEOUT = 60 MAX_TWEETS_IN_FILE = 100000 APP_KEY = "your-twitter-app-key" APP_SECRET = "your-twitter-app-secret" OAUTH_TOKEN = "your-twitter-oauth-token" OAUTH_TOKEN_SECRET = "your-twitter-oauth-secret" class Twitter...
Python
zaydzuhri_stack_edu_python