code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function load_and_convert_msg txt begin set bin_code = list with open txt as msg begin for line in msg begin for c in line begin append bin_code call dec_to_bin ordinal c end end end return bin_code end function
def load_and_convert_msg(txt): bin_code = [] with open(txt) as msg: for line in msg: for c in line: bin_code.append(dec_to_bin(ord(c))) return bin_code
Python
nomic_cornstack_python_v1
comment !/user/bin/env python3 comment coding=utf8 string 模拟网站后端应用处理程序 httpserver v3.0 from socket import * import select import json comment 导入配置文件 from settings import * from views import * comment 创建应用类, 用于具体处理请求 class Application extends object begin function __init__ self begin set ip = frame_address at 0 set port...
#!/user/bin/env python3 # coding=utf8 """ 模拟网站后端应用处理程序 httpserver v3.0 """ from socket import * import select import json # 导入配置文件 from settings import * from views import * # 创建应用类, 用于具体处理请求 class Application(object): def __init__(self): self.ip = frame_address[0] self.port = frame_address[1] ...
Python
zaydzuhri_stack_edu_python
function _zero_outside_coi wavelet_matrix freqs rate=200 begin for i in range 0 shape at 0 begin set coi = integer 1.0 / freqs at i * rate set wavelet_matrix at tuple i slice 0 : coi : = 0.0 set wavelet_matrix at tuple i slice - coi : : = 0.0 end return wavelet_matrix end function
def _zero_outside_coi(wavelet_matrix,freqs, rate = 200): for i in range(0,wavelet_matrix.shape[0]): coi =int(1./freqs[i]*rate) wavelet_matrix[i,0:coi] = 0. wavelet_matrix[i,-coi:] = 0. return wavelet_matrix
Python
nomic_cornstack_python_v1
function _bind_arguments callable_ args=none kwargs=none instance=none begin set wrapped_signature = signature callable_ comment We should keep the warning about "z_mean" for perhaps ∼2 comment releases following the last pull request that removes a "z_mean" comment parameter from a callable decorated with @particle_in...
def _bind_arguments( callable_: Callable, args: Optional[tuple] = None, kwargs: Optional[dict[str, Any]] = None, instance=None, ) -> dict: wrapped_signature = inspect.signature(callable_) # We should keep the warning about "z_mean" for perhaps ∼2 # releases following the last pull request t...
Python
nomic_cornstack_python_v1
import argparse import inspect comment Maximum length of the short names (one-dash arguments) set MAXSHORT = 3 class Parsable extends object begin string Mixin to make as parsable. set _is_parsable = true end class class Attrib extends object begin string Container object for command line attributes. function __init__ ...
import argparse import inspect # Maximum length of the short names (one-dash arguments) MAXSHORT = 3 class Parsable(object): """Mixin to make as parsable.""" _is_parsable = True class Attrib(object): """Container object for command line attributes.""" def __init__(self): self.varname = Non...
Python
zaydzuhri_stack_edu_python
comment 水仙花数 comment 153 = 1³ + 5³ + 3³。 comment 370 = 3³ + 7³ + 0³。 comment 371 = 3³ + 7³ + 1³。 comment 407 = 4³ + 0³ + 7³。 comment (1)水仙花数 comment 所谓水仙花数:指一个3位数,其个位数字的立方和等于改数本身,例如153=1³+5³+3³ comment 求出100~999之间的水仙花数。 comment 算法:比如i comment 百位 a (1)a=i//100 (Python //整除 其它语言/整除)a = int(i/100) Python comment 十位 b (2)b...
# 水仙花数 # 153 = 1³ + 5³ + 3³。 # 370 = 3³ + 7³ + 0³。 # 371 = 3³ + 7³ + 1³。 # 407 = 4³ + 0³ + 7³。 # (1)水仙花数 # 所谓水仙花数:指一个3位数,其个位数字的立方和等于改数本身,例如153=1³+5³+3³ # 求出100~999之间的水仙花数。 # 算法:比如i # 百位 a (1)a=i//100 (Python //整除 其它语言/整除)a = int(i/100) Python # 十位 b (2)b= (i%100) //100 b = int( (i-100*a)/10) # ...
Python
zaydzuhri_stack_edu_python
import copy import functools import queue class parse extends object begin comment 保存数据的数据结构 function __init__ self text norm lemma_ pos_ tag_ dep_ head id child left right ancestor begin set text = text set norm = norm set lemma_ = lemma_ set pos_ = pos_ set tag_ = tag_ set dep_ = dep_ set head = head set id = id set ...
import copy import functools import queue class parse(object): # 保存数据的数据结构 def __init__(self, text, norm, lemma_, pos_, tag_, dep_, head, id, child, left, right, ancestor): self.text = text self.norm = norm self.lemma_ = lemma_ self.pos_ = pos_ self.tag_ = tag_ ...
Python
zaydzuhri_stack_edu_python
function timer_set_groups request timer_id begin if method == string POST begin set form_data = call TimerGroupNamesForm POST set dummy_view = call PADSTimerEditView request timer_id call prepare_context if call user_present begin set timer = call get_timer if timer begin comment Valid Form Data if call is_valid begin ...
def timer_set_groups(request, timer_id): if request.method == "POST": form_data = TimerGroupNamesForm(request.POST) dummy_view = PADSTimerEditView(request, timer_id) dummy_view.prepare_context() if dummy_view.user_present(): timer = dummy_view.get_timer() if ...
Python
nomic_cornstack_python_v1
function rho_spaxel_scale spaxel_scale=4.0 wavelength=1.0 begin set scale_rad = spaxel_scale / MILIARCSECS_IN_A_RAD set rho = scale_rad * ELT_DIAM / wavelength * 1e-06 return rho end function
def rho_spaxel_scale(spaxel_scale=4.0, wavelength=1.0): scale_rad = spaxel_scale / MILIARCSECS_IN_A_RAD rho = scale_rad * ELT_DIAM / (wavelength * 1e-6) return rho
Python
nomic_cornstack_python_v1
function find_smallest arr begin comment Initialize the smallest number as the first element in the array set smallest = arr at 0 comment Iterate through the rest of the elements in the array for num in arr at slice 1 : : begin comment If the current number is smaller than the smallest number, comment update the smal...
def find_smallest(arr): # Initialize the smallest number as the first element in the array smallest = arr[0] # Iterate through the rest of the elements in the array for num in arr[1:]: # If the current number is smaller than the smallest number, # update the smallest number ...
Python
jtatman_500k
from django.utils import timezone import datetime from models import Brews import operator set days = list string Monday string Tuesday string Wednesday string Thursday string Friday string Saturday string Sunday function get_monthly_alltime begin set monthly = call get_monthly_highscore set alltime = call get_alltime_...
from django.utils import timezone import datetime from .models import Brews import operator days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] def get_monthly_alltime(): monthly = get_monthly_highscore() alltime = get_alltime_highscore() return monthly, alltime de...
Python
zaydzuhri_stack_edu_python
function areaFromRadius begin set radius = input string What is the circle's radius? set area = decimal radius * decimal radius * 3.1416 print string The area of the circle is: + string format area string .2f print string This was calculated with this formula: (radius^2) * 3.1416 end function
def areaFromRadius(): radius = input("What is the circle's radius?\n") area = (float(radius) * float(radius)) * 3.1416 print("The area of the circle is: " + str(format(area, '.2f'))) print("This was calculated with this formula: (radius^2) * 3.1416")
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import time from Adafruit_PWM_Servo_Driver import PWM comment Initialise the PWM device using the default address comment bmp = PWM(0x40, debug=True) class RobotBase begin set pwm = call PWM 64 debug=true set servoMin = 175 set servoMax = 625 function setServoPulse self channel pulse begin comm...
#!/usr/bin/python import time from Adafruit_PWM_Servo_Driver import PWM # Initialise the PWM device using the default address # bmp = PWM(0x40, debug=True) class RobotBase(): pwm = PWM(0x40, debug=True) servoMin = 175 servoMax = 625 def setServoPulse(self, channel, pulse): pulseLength = 1000000 ...
Python
zaydzuhri_stack_edu_python
function test_allowed_result_sizes fxc endpoint size begin set fn_uuid = call register_function large_result_producer endpoint description=string LargeResultProducer set task_id = run size endpoint_id=endpoint function_id=fn_uuid comment This is the current result size limit set x = call wait_for_task fxc task_id wallt...
def test_allowed_result_sizes(fxc, endpoint, size): fn_uuid = fxc.register_function( large_result_producer, endpoint, description="LargeResultProducer" ) task_id = fxc.run( size, # This is the current result size limit endpoint_id=endpoint, function_id=fn_uuid, ) x ...
Python
nomic_cornstack_python_v1
class Matrix extends object begin function __init__ self matrix begin string Matrix can take string and list type in the following formats: string: '9 8 7 5 3 2 6 6 7' list : [[9, 8, 7], [5, 3, 2], [6, 6, 7]] set rows = if expression matrix then call getRows matrix else list set num_rows = if expression matrix then le...
class Matrix(object): def __init__(self,matrix): """Matrix can take string and list type in the following formats: string: '9 8 7\n5 3 2\n6 6 7' list : [[9, 8, 7], [5, 3, 2], [6, 6, 7]] """ self.rows = self.getRows(matrix) if matrix else [] self.num_rows...
Python
zaydzuhri_stack_edu_python
import math import numpy as np from src.line.Line import Line from src.util.common import N function halflowpass n=128 dt=0.001 fCut=50 begin return call Line string Half Low Pass Filter y=call half_low_pass_filter n dt fCut end function set SMOOTH_WINDOW_P310 = list 0.35577019 0.2436983 0.07211497 0.00630165 function ...
import math import numpy as np from src.line.Line import Line from src.util.common import N def halflowpass(n=128, dt=0.001, fCut=50): return Line("Half Low Pass Filter", y=half_low_pass_filter(n, dt, fCut)) SMOOTH_WINDOW_P310 = [0.35577019, 0.24369830, 0.07211497, 0.00630165] def half_low_pass_filter(n, dt, fC...
Python
zaydzuhri_stack_edu_python
function __init__ self width=800 height=400 begin set width = width set height = height end function
def __init__(self, width = 800, height = 400): self.width = width self.height = height
Python
nomic_cornstack_python_v1
from collections import deque class ShuntingYardAlgorithm begin comment also known as Reverse Polish notation (RPN) function tokenize self s begin set number_str = list for c in s begin if is digit c begin append number_str c end else if c != string begin if number_str begin yield join string number_str set number_s...
from collections import deque class ShuntingYardAlgorithm: # also known as Reverse Polish notation (RPN) def tokenize(self, s): number_str = [] for c in s: if c.isdigit(): number_str.append(c) elif c != ' ': if number_str: ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Wed Sep 16 10:57:37 2020 @author: elliebear set decimals = list 0.02 0.3 0.456 comment Convert to precentages set percents = list for i in decimals begin append percents i * 100 end print percents comment List Comprehension set percents = li...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Sep 16 10:57:37 2020 @author: elliebear """ decimals = [0.02, 0.3, 0.456] # Convert to precentages percents = [] for i in decimals: percents.append(i * 100) print(percents) # List Comprehension percents = [i * 100 for i in decimals] import num...
Python
zaydzuhri_stack_edu_python
if is lower str1 at x begin set xval = upper str1 at x end else begin set xval = lower str1 at x end if is lower str1 at y begin set yval = upper str1 at y end else begin set yval = lower str1 at y end set str1 = str1 at slice 0 : x : + xval + str1 at slice x + 1 : y : + yval + str1 at slice y + 1 : : print str1
if str1[x].islower(): xval=str1[x].upper() else: xval=str1[x].lower() if str1[y].islower(): yval=str1[y].upper() else: yval=str1[y].lower() str1=str1[0:x]+xval+str1[x+1:y]+yval+str1[y+1:] print(str1)
Python
zaydzuhri_stack_edu_python
function __init__ __self__ assignment_state principal_type resource_id role_definition_id exclude_resource_id=none exclude_role_definition_id=none expand_nested_memberships=none inactive_duration=none include_access_below_resource=none include_inherited_access=none begin set __self__ string assignment_state assignment_...
def __init__(__self__, *, assignment_state: str, principal_type: str, resource_id: str, role_definition_id: str, exclude_resource_id: Optional[str] = None, exclude_role_definition_id: Optional[str] = None, ...
Python
nomic_cornstack_python_v1
function test_reconcile_02 self begin set group = list list call LengthField name=string 1 mm x1=0 y1=0 x2=0 y2=0 list call LengthField name=string 1 mm x1=10 y1=40 x2=40 y2=80 list call LengthField name=string 1 mm x1=20 y1=80 x2=80 y2=160 set expect = list call LengthField name=string 1 mm note=string There are 3 of ...
def test_reconcile_02(self): group = [ [LengthField(name="1 mm", x1=0, y1=0, x2=0, y2=0)], [LengthField(name="1 mm", x1=10, y1=40, x2=40, y2=80)], [LengthField(name="1 mm", x1=20, y1=80, x2=80, y2=160)], ] expect = [ LengthField( na...
Python
nomic_cornstack_python_v1
function top_token_set_ratio group begin set scores = list for tuple c0 c1 in call combinations group 2 begin set score = call token_set_ratio value value set tokens_0 = length split value set tokens_1 = length split value if tokens_0 > tokens_1 begin set field = c0 set tokens = tokens_0 end else if tokens_0 < tokens_...
def top_token_set_ratio(group): scores = [] for c0, c1 in combinations(group, 2): score = fuzz.token_set_ratio(c0.value, c1.value) tokens_0 = len(c0.value.split()) tokens_1 = len(c1.value.split()) if tokens_0 > tokens_1: field = c0 tokens = tokens_0 ...
Python
nomic_cornstack_python_v1
function test_createsuperuser_command_with_database_option self begin set new_io = call StringIO call call_command string createsuperuser interactive=false username=string joe email=string joe@somewhere.org database=string other stdout=new_io set command_output = strip call getvalue assert equal command_output string S...
def test_createsuperuser_command_with_database_option(self): new_io = StringIO() call_command( 'createsuperuser', interactive=False, username='joe', email='joe@somewhere.org', database='other', stdout=new_io, ) comma...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- string 乘法表 for实现 print string Which multiplication table would you like? set number = integer call raw_input print string Here's your table: for i in range 1 11 begin print string number + string * + string i + string = + string number * i end
# !/usr/bin/python # -*- coding: utf-8 -*- ''' 乘法表 for实现 ''' print("Which multiplication table would you like?") number = int(raw_input()) print("Here's your table:") for i in range(1, 11): print(str(number) + " * " + str(i) + " = " + str(number * i))
Python
zaydzuhri_stack_edu_python
comment EXERCÍCIO Nº 12 - LISTA 03 - ESTRUTURA DE REPETIÇÃO print string Gerador de tabuada print string ################## set tabuada = integer input string Insira o número da tabuada (entre 1 e 10): while tabuada > 10 or tabuada < 1 begin set tabuada = integer input string Insira o número da tabuada (entre 1 e 10): ...
#EXERCÍCIO Nº 12 - LISTA 03 - ESTRUTURA DE REPETIÇÃO print('\nGerador de tabuada') print('##################\n') tabuada=int(input("Insira o número da tabuada (entre 1 e 10): ")) while tabuada>10 or tabuada<1: tabuada = int(input("Insira o número da tabuada (entre 1 e 10): ")) print('\nTabuada do ',ta...
Python
zaydzuhri_stack_edu_python
class triangle begin function __init__ self s1 s2 s3 begin set s1 = s1 set s2 = s2 set s3 = s3 end function function perimeter self begin set perimeter = s1 + s2 + s3 print string Perimeter: perimeter end function function area self begin set s = perimeter / 2 set area = s * s - s1 * s - s2 * s - s3 ^ 0.5 print string ...
class triangle: def __init__(self,s1,s2,s3): self.s1 = s1 self.s2 = s2 self.s3 = s3 def perimeter(self): self.perimeter = self.s1+self.s2+self.s3 print('Perimeter: ',self.perimeter) def area(self): s = self.perimeter/2 self.area =...
Python
zaydzuhri_stack_edu_python
function __init__ self sample_size *args scale=0.1 alpha=0.001 **kwargs begin comment type: ignore call __init__ *args keyword kwargs set sample_size = sample_size set scale = scale set alpha = alpha end function
def __init__(self, sample_size: int, *args, scale: float = 0.1, alpha: float = 0.001, **kwargs,) -> None: super().__init__(*args, **kwargs) # type: ignore self.sample_size = sample_size self.scale = scale self.alpha = alpha
Python
nomic_cornstack_python_v1
import iota_wallet as iw import os from typing import List class AccountInterface extends object begin function __init__ self name password begin set __password = password set __name = name set __account_manager = call AccountManager storage_path=format string ./{}-database __name call set_stronghold_password password ...
import iota_wallet as iw import os from typing import List class AccountInterface(object): def __init__(self, name, password): self.__password = password self.__name = name self.__account_manager = iw.AccountManager( storage_path='./{}-database'.format(self.__name) ...
Python
zaydzuhri_stack_edu_python
function duplicateZeros self arr begin comment find number of zeros, to determine the displacement, i.e. how comment many places to move (the last element) set zero_count = 0 for num in arr begin if num == 0 begin set zero_count = zero_count + 1 end end set displacement = zero_count for i in range length arr - 1 - 1 - ...
def duplicateZeros(self, arr) -> None: # find number of zeros, to determine the displacement, i.e. how # many places to move (the last element) zero_count = 0 for num in arr: if num == 0: zero_count += 1 displacement = zero_count for i in ra...
Python
nomic_cornstack_python_v1
import scrapy class MySpider extends Spider begin set name = string myspider set start_urls = list string https://example.com/page1 string https://example.com/page2 end class
import scrapy class MySpider(scrapy.Spider): name = 'myspider' start_urls = [ 'https://example.com/page1', 'https://example.com/page2', ]
Python
flytech_python_25k
function standard_aggregation C begin if not call isspmatrix_csr C begin raise call TypeError string expected csr_matrix end if shape at 0 != shape at 1 begin raise call ValueError string expected square matrix end set index_type = dtype set num_rows = shape at 0 comment stores the aggregate #s set Tj = call empty num_...
def standard_aggregation(C): if not sparse.isspmatrix_csr(C): raise TypeError('expected csr_matrix') if C.shape[0] != C.shape[1]: raise ValueError('expected square matrix') index_type = C.indptr.dtype num_rows = C.shape[0] Tj = np.empty(num_rows, dtype=index_type) # stores the ag...
Python
nomic_cornstack_python_v1
function _wait_for_finish self return_value begin while not finished begin sleep WAIT_FOR_SLEEP_TIME end info string { __name__ } task finished set value = completed end function
def _wait_for_finish(self, return_value: Value) -> bool: while not self.finished: sleep(self.WAIT_FOR_SLEEP_TIME) self._logger.info(f"{self.__class__.__name__} task finished") return_value.value = self.completed
Python
nomic_cornstack_python_v1
comment Lab 10-1-1 comment By Julan Ray Avila Gutierrez, jra0108@arastudent.ac.nz import os function create_dir begin string Create a directory. Return resulting message. set dir_name = call get_dir_name CREATE_ACTION comment Let's try to create it try begin make directory os dir_name end except any begin return string...
# Lab 10-1-1 # By Julan Ray Avila Gutierrez, jra0108@arastudent.ac.nz import os def create_dir(): """Create a directory. Return resulting message.""" dir_name = get_dir_name(CREATE_ACTION) # Let's try to create it try: os.mkdir(dir_name) except: return "An err...
Python
zaydzuhri_stack_edu_python
import math import time set count = 12 set sum = 17 set max = 2000000 function isPrime n begin if n % 2 == 0 or n % 5 == 0 or n % 3 == 0 or n % 7 == 0 begin return false end set top = square root n set ne = 5 while ne <= top begin if n % ne == 0 begin return false end if n % ne + 2 == 0 begin return false end set ne = ...
import math import time count = 12 sum = 17 max = 2000000 def isPrime(n): if n%2==0 or n % 5 == 0 or n%3==0 or n%7==0: return False top = math.sqrt(n) ne = 5 while ne <= top: if n % ne ==0: return False if n %(ne+2) == 0: return False ne += 6 return True start_time = time.time() for i in range(11,...
Python
zaydzuhri_stack_edu_python
function New *args **kargs begin set obj = call __New_orig__ import itkTemplate call New obj *args keyword kargs return obj end function
def New(*args, **kargs): obj = itkRegistrationParameterScalesFromPhysicalShiftEBPSTPSMPSUC3_Superclass.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
Python
nomic_cornstack_python_v1
function calculate_difference_image_zero_point science reference begin set denominator = background_std ^ 2 * zero_point ^ 2 set denominator = denominator + background_std ^ 2 * zero_point ^ 2 set difference_image_zero_point = zero_point * zero_point / square root denominator info format string Global difference image ...
def calculate_difference_image_zero_point(science, reference): denominator = science.background_std ** 2 * reference.zero_point ** 2 denominator += reference.background_std ** 2 * science.zero_point ** 2 difference_image_zero_point = science.zero_point * reference.zero_point / np.sqrt(denominator) log...
Python
nomic_cornstack_python_v1
function _hist_setup self begin set h = call hm phases set nbins = 25 if h > 100 begin set nbins = 50 end if h > 1000 begin set nbins = 100 end set tuple ph0 ph1 = tuple 0 + phase_shift 1 + phase_shift set hist = call histogram phases bins=linear space ph0 ph1 nbins if length hist at 0 == nbins begin raise call ValueEr...
def _hist_setup(self): h = hm(self.phases) nbins = 25 if h > 100: nbins = 50 if h > 1000: nbins = 100 ph0,ph1 = 0+self.phase_shift,1+self.phase_shift hist = np.histogram(self.phases,bins=np.linspace(ph0,ph1,nbins)) if len(hist[0])==nbins: raise ValueError('Histogr...
Python
nomic_cornstack_python_v1
function process_event self event begin set options = dict Spawned process_spawned_event ; Walked process_walked_event ; Ate none ; Eaten process_died_event ; Mitosed none ; Died process_died_event ; Expired process_died_event ; NoAction none if options at action is not none begin print event print string - * 32 call e...
def process_event(self, event): options = { Actions.Spawned: self.process_spawned_event, Actions.Walked: self.process_walked_event, Actions.Ate: None, Actions.Eaten: self.process_died_event, Actions.Mitosed: None, Actions.Died: self.process...
Python
nomic_cornstack_python_v1
import time function validate function_value begin set t1 = time call function_value set t2 = time print string Time taken is : t2 - t1 end function decorator validate function display begin for i in range 5 begin sleep 0.2 end end function
import time def validate(function_value): t1 = time.time() function_value() t2 = time.time() print("Time taken is :", t2 - t1) @validate def display(): for i in range(5): time.sleep(0.2)
Python
zaydzuhri_stack_edu_python
string Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update statement and no intermediate temp table. Note that you must write a single update statement, DO NOT write any select statement for this p...
''' Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update statement and no intermediate temp table. Note that you must write a single update statement, DO NOT write any select statement for this pro...
Python
zaydzuhri_stack_edu_python
function auto_hatch_eggs self begin pass end function
def auto_hatch_eggs(self): pass
Python
nomic_cornstack_python_v1
function asodict self handlepoints=true reportpoints=true begin set out = call odict if handlepoints begin for hp in handlepoints begin set out at hpoint = trace end end if reportpoints begin for rp in reportpoints begin if not rpoint in out begin set out at rpoint = call odict end set out at rpoint at attribute = dict...
def asodict(self, handlepoints=True, reportpoints=True): out = odict() if handlepoints: for hp in self.handlepoints: out[hp.hpoint] = hp.trace if reportpoints: for rp in self.reportpoints: if not (rp.rpoint in out): out[...
Python
nomic_cornstack_python_v1
from sklearn.datasets import load_iris import pandas as pd import seaborn as sns comment a.) set iris = call load_iris set df = call DataFrame data columns=feature_names set df at string species = call from_codes target target_names comment df.head() comment b.) comment Sepal Length Boxplot in pandas set sepallength = ...
from sklearn.datasets import load_iris import pandas as pd import seaborn as sns #a.) iris = load_iris() df = pd.DataFrame(iris.data, columns= iris.feature_names) df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names) #df.head() #b.) #Sepal Length Boxplot in pandas sepallength = df.boxplot(column =...
Python
zaydzuhri_stack_edu_python
from Problems import * from Algorithms import * import math import random class ItalyBFSAgent extends BFS begin function __init__ self initial_state=string Torino goal_state=string Roma begin set graph = graph call __init__ initial_state=initial_state goal_state=goal_state end function function getAdjacents self node b...
from Problems import * from Algorithms import * import math import random class ItalyBFSAgent(BFS): def __init__(self,initial_state='Torino',goal_state='Roma'): self.graph = ItalyProblems.graph super().__init__(initial_state=initial_state,goal_state=goal_state) def ge...
Python
zaydzuhri_stack_edu_python
function __contains__ self rname begin return rname in keys self end function
def __contains__(self, rname): return rname in self.keys()
Python
nomic_cornstack_python_v1
function isPrime num begin comment even number if num % 2 == 0 begin return false end comment odd nums from 3 to num-1 set odds = set list comprehension i for i in range 3 num 2 for odd in odds begin if num % odd == 0 begin return false end end return true end function function solution nums begin set count = 0 for i i...
def isPrime(num): # even number if num % 2 == 0 : return False odds = set([i for i in range(3, num, 2)]) # odd nums from 3 to num-1 for odd in odds: if num%odd == 0: return False return True def solution(nums): count = 0 for i in range(len(nums)-2): ...
Python
zaydzuhri_stack_edu_python
function StateOne self axis begin set springfield = springfield set state = call getState axis if state == 1 begin return tuple On string Motor is stopped end else if state == 2 begin return tuple Moving string Motor is moving end else if state == 3 begin return tuple Fault string Motor has an error end end function
def StateOne(self, axis): springfield = self.springfield state = springfield.getState(axis) if state == 1: return State.On, "Motor is stopped" elif state == 2: return State.Moving, "Motor is moving" elif state == 3: return State.Fault, "Motor h...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: UTF-8 -* import time import pymongo import requests from bs4 import BeautifulSoup class Arctle extends object begin string docstring for Arctle function __init__ self begin set myclient = call MongoClient string mongodb://localhost:27017/ set articledb = myclient at string a...
#!/usr/bin/python # -*- coding: UTF-8 -* import time import pymongo import requests from bs4 import BeautifulSoup class Arctle(object): """docstring for Arctle""" def __init__(self): self.myclient = pymongo.MongoClient('mongodb://localhost:27017/') self.articledb = self.myclient["article"] ...
Python
zaydzuhri_stack_edu_python
function scrape_descriptions_sync begin make directory YAHOO_HTMLS parents=true exist_ok=true for symbol in call tqdm call read_symbols begin with url open call Request string https://finance.yahoo.com/quote/ { symbol } /profile?p= { symbol } headers=HEADERS as response begin with open string wb as f begin write f read...
def scrape_descriptions_sync(): YAHOO_HTMLS.mkdir(parents=True, exist_ok=True) for symbol in tqdm(read_symbols()): with urlopen(Request(f'https://finance.yahoo.com/quote/{symbol}/profile?p={symbol}', headers=HEADERS)) as response: with (YAHOO_HTMLS / f'{symbol}.html').open('wb') as f: ...
Python
nomic_cornstack_python_v1
comment https://blog.csdn.net/qq_41518277/article/details/85101240 comment http://www.360doc.com/content/16/0906/01/20558639_588703140.shtml comment https://machinelearningmastery.com/sensitivity-analysis-history-size-forecast-skill-arima-python/ import warnings filter warnings string ignore from math import sqrt from ...
# https://blog.csdn.net/qq_41518277/article/details/85101240 # http://www.360doc.com/content/16/0906/01/20558639_588703140.shtml # https://machinelearningmastery.com/sensitivity-analysis-history-size-forecast-skill-arima-python/ import warnings warnings.filterwarnings("ignore") from math import sqrt from sklearn.met...
Python
zaydzuhri_stack_edu_python
function list self detailed=false return_raw=false begin return call _list string /licenses?detailed= + string detailed string licenses return_raw=return_raw end function
def list(self, detailed=False, return_raw=False): return self._list('/licenses?detailed=' + str(detailed), 'licenses', return_raw=return_raw)
Python
nomic_cornstack_python_v1
function s3_key_parameter self begin return get _values string s3_key_parameter end function
def s3_key_parameter(self) -> str: return self._values.get('s3_key_parameter')
Python
nomic_cornstack_python_v1
import sys while 1 begin set line = read line stdin if not line begin break end write stdout line end
import sys while 1: line = sys.stdin.readline() if not line: break sys.stdout.write(line)
Python
zaydzuhri_stack_edu_python
import tweepy import yfinance as yf import creds import pandas as pd import matplotlib.pyplot as plt comment Authenticate to Twitter set auth = call OAuthHandler auth_key auth_secret call set_access_token auth_token auth_token_secret comment Create API object set api = call API auth set test_tweet_num = 1 set price_gra...
import tweepy import yfinance as yf import creds import pandas as pd import matplotlib.pyplot as plt # Authenticate to Twitter auth = tweepy.OAuthHandler(creds.auth_key, creds.auth_secret) auth.set_access_token(creds.auth_token, creds.auth_token_secret) # Create API object api = tweepy.API(auth) test_tweet_num = 1 ...
Python
zaydzuhri_stack_edu_python
from PyQt4.QtCore import * from PyQt4.QtGui import * class devirHizi extends QDialog begin function __init__ self ebeveyn=none begin call __init__ ebeveyn set grid = call QGridLayout call addWidget call QLabel string İşten ayrılan personel: 0 0 set ayrilanPer = call QLineEdit call addWidget ayrilanPer 0 1 call addWidge...
from PyQt4.QtCore import * from PyQt4.QtGui import * class devirHizi(QDialog): def __init__(self,ebeveyn=None): super(devirHizi,self).__init__(ebeveyn) grid=QGridLayout() grid.addWidget(QLabel("İşten ayrılan personel:"),0,0) self.ayrilanPer=QLineEdit() grid.addWid...
Python
zaydzuhri_stack_edu_python
function plot_confusion_matrix cm classes normalize=false title=string Confusion matrix cmap=Blues begin image show cm interpolation=string nearest cmap=cmap title plt title call colorbar set tick_marks = array range length classes call xticks tick_marks classes rotation=45 call yticks tick_marks classes if normalize b...
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) ...
Python
nomic_cornstack_python_v1
comment Manipulacao de arquivos comment Gravacao comment Utiliza-se funcao open(), passando como parametro o nome do arquivo com a extensao e o parametro 'w' comment "w" significa write, ou seja, escrever/gravar no arquivo comment Funcao write() escreve o texto passado por parametro no arquivo criado comment Utilizar S...
# Manipulacao de arquivos # Gravacao # Utiliza-se funcao open(), passando como parametro o nome do arquivo com a extensao e o parametro 'w' # "w" significa write, ou seja, escrever/gravar no arquivo # Funcao write() escreve o texto passado por parametro no arquivo criado # Utilizar SEMPRE a funcao close() após abrir e...
Python
zaydzuhri_stack_edu_python
import sys append path string motor append path string adxl345 from libdynamixel import * from adxl345 import * set DEBUG = true set MOTOR_ID = 1 set sensor = call ADXL345 while true begin set axes = call getAxes true set x = axes at string x set speedX = x * 80 end
import sys sys.path.append('motor') sys.path.append('adxl345') from libdynamixel import * from adxl345 import * DEBUG = True MOTOR_ID = 1 sensor = ADXL345() while True: axes = sensor.getAxes(True) x = axes['x'] speedX = x*80
Python
zaydzuhri_stack_edu_python
if age <= 3 begin print string Your movie ticket is free. end else if age > 3 and age < 12 begin print string Your ticket is 10$ end else if age > 12 begin print string Your ticket is 15$ end
if age <= 3: print("Your movie ticket is free.") elif (age > 3) and (age < 12): print("Your ticket is 10$") elif age > 12: print("Your ticket is 15$")
Python
zaydzuhri_stack_edu_python
comment exercise 168: Repeated Words from lists.ex117 import words_in_string import sys from pathlib import Path string to launch from CLI, go to the root directory python_workbook, then use the command: python -m files_and_exceptions.ex168 file.txt function findDuplicates myfile begin set duplicates = list try begin ...
# exercise 168: Repeated Words from lists.ex117 import words_in_string import sys from pathlib import Path """ to launch from CLI, go to the root directory python_workbook, then use the command: python -m files_and_exceptions.ex168 file.txt """ def findDuplicates(myfile): duplicates = [] try: inf =...
Python
zaydzuhri_stack_edu_python
import operator from domain.shared.entity import Entity from domain.model.sales.line_item import LineItem class Invoice extends Entity begin function __init__ self invoice_id customer invoice_date order_id=none customer_reference=none begin set invoice_id = invoice_id set customer = customer set invoice_date = invoice_...
import operator from domain.shared.entity import Entity from domain.model.sales.line_item import LineItem class Invoice(Entity): def __init__(self, invoice_id, customer, invoice_date, order_id=None, customer_reference=None): self.invoice_id = invoice_id self.customer = customer self.invoi...
Python
zaydzuhri_stack_edu_python
function smartAppend table name value begin if name not in list keys table begin set table at name = list end append table at name value end function
def smartAppend(table,name,value): if name not in list(table.keys()): table[name] = [] table[name].append(value)
Python
nomic_cornstack_python_v1
function get_speed_setpoint self begin set _speed_setpoint = call send GET_SPEED_SET return _speed_setpoint end function
def get_speed_setpoint(self) -> int: self._speed_setpoint = self.send(self.cmd.GET_SPEED_SET) return self._speed_setpoint
Python
nomic_cornstack_python_v1
class Inimene begin set jk = 0 function __init__ self begin set id = jk + 1 set jk = jk + 1 end function function info self begin print string Inimese id = + string id print string Inimese jk = + string jk end function end class
class Inimene(): jk = 0 def __init__(self): self.id = self.jk + 1 self.jk += 1 def info(self): print("Inimese id = " + str(self.id)) print("Inimese jk = " +str(self.jk))
Python
zaydzuhri_stack_edu_python
string livraria/forms/cliente.py Define formularios usados no menu Clientes. from flask_wtf import FlaskForm from wtforms import StringField , DateField , SelectField , FormField , SubmitField from wtforms.validators import DataRequired as Data , Email , Regexp from livraria.models import * set MSG_DOC = string Informe...
""" livraria/forms/cliente.py Define formularios usados no menu Clientes. """ from flask_wtf import FlaskForm from wtforms import StringField, DateField, SelectField, FormField, SubmitField from wtforms.validators import DataRequired as Data, Email, Regexp from livraria.models import * MSG_DOC = 'Informe apenas núme...
Python
zaydzuhri_stack_edu_python
import tkinter set map_data = list list 0 1 1 1 1 0 0 1 1 1 1 0 list 0 2 3 3 2 1 1 2 3 3 2 0 list 0 3 0 0 3 3 3 3 0 0 3 0 list 0 3 1 1 3 0 0 3 1 1 3 0 list 0 3 2 2 3 0 0 3 2 2 3 0 list 0 3 0 0 3 1 1 3 0 0 3 0 list 0 3 1 1 3 3 3 3 1 1 3 0 list 0 2 3 3 2 0 0 2 3 3 2 0 list 0 0 0 0 0 0 0 0 0 0 0 0 comment 게임 화면 그리기 functi...
import tkinter map_data = [ [0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0], [0, 2, 3, 3, 2, 1, 1, 2, 3, 3, 2, 0], [0, 3, 0, 0, 3, 3, 3, 3, 0, 0, 3, 0], [0, 3, 1, 1, 3, 0, 0, 3, 1, 1, 3, 0], [0, 3, 2, 2, 3, 0, 0, 3, 2, 2, 3, 0], [0, 3, 0, 0, 3, 1, 1, 3, 0, 0, 3, 0], [0, 3, 1, 1, 3, 3, 3, 3, 1, 1, 3, 0...
Python
zaydzuhri_stack_edu_python
function setinactive self irc msg args channel begin set res = call _checkDBhasChannel channel if res is true begin set SQL = string UPDATE registry SET isActive = ? WHERE channel = ? set SQLargs = tuple 0 channel call _SQLexec SQL SQLargs acquire lock for x in range 0 length channelscontrol begin set v0 = string chann...
def setinactive(self, irc, msg, args, channel): res = self._checkDBhasChannel(channel) if res is True: SQL = 'UPDATE registry SET isActive = ? WHERE channel = ?' SQLargs = (0, channel) self._SQLexec(SQL, SQLargs) self.lock.acquire() for x in ra...
Python
nomic_cornstack_python_v1
import pandas as pd import os import openpyxl from copy import copy comment 获取并生成转置表### class TransposeTable extends object begin string 生成转置表 function __init__ self begin set store_path = string ./table/by store/ set save_path = string ./download_file/stroe_files/ set title_file = string ./stc_title/bystore/ set fitte...
import pandas as pd import os import openpyxl from copy import copy ###获取并生成转置表### class TransposeTable(object): """ 生成转置表 """ def __init__(self): self.store_path = './table/by store/' self.save_path = './download_file/stroe_files/' self.title_file = './stc_ti...
Python
zaydzuhri_stack_edu_python
import sys import requests import pandas as pd import json set url1 = string https://inf551-48566.firebaseio.com/invert_index.json set url2 = string https://inf551-48566.firebaseio.com/loaded_data.json set inverted_index = dict set response = get requests url1 set response2 = get requests url2 set original_database = ...
import sys import requests import pandas as pd import json url1="https://inf551-48566.firebaseio.com/invert_index.json" url2="https://inf551-48566.firebaseio.com/loaded_data.json" inverted_index={} response=requests.get(url1) response2 = requests.get(url2) original_database = response2.json() inverted_index...
Python
zaydzuhri_stack_edu_python
function arp self arp_type sender_mac sender_ip target_mac target_ip begin call string_set list string ARP request string ARP reply string RARP request string RARP reply arp_type set arp_type_translator = dict set arp_type_translator at string ARP request = string 1 set arp_type_translator at string ARP reply = string...
def arp(self, arp_type, sender_mac, sender_ip, target_mac, target_ip): input_validator.string_set(['ARP request', 'ARP reply', 'RARP request', 'RARP reply'], arp_type) self.arp_type_translator = {} self.arp_type_translator['ARP request'] = '1' self.arp_type_translator['ARP reply'] = '2' self.arp_type_translat...
Python
nomic_cornstack_python_v1
function extract_data_from_analysis_json analysis_json sample_id limit begin set ec = dict set hr = dict set sample_key = string ThreatGrid.Sample(val.ID === obj.ID) set sample_process = call extract_sample_process_from_analysis_processes get demisto analysis_json string dynamic.processes or dict set ec at sample_ke...
def extract_data_from_analysis_json(analysis_json, sample_id, limit): ec = {} hr = {} sample_key = 'ThreatGrid.Sample(val.ID === obj.ID)' sample_process = extract_sample_process_from_analysis_processes(demisto.get(analysis_json, ...
Python
nomic_cornstack_python_v1
function stack st num out ii oo begin if ii > oo begin set st1 = copy st set out1 = copy out set num1 = copy num append out1 pop st1 if oo + 1 == N begin print out1 return end else begin stack st1 num out1 ii oo + 1 end end if length num > 0 begin set st1 = copy st set out1 = copy out set num1 = copy num append st1 pop...
def stack(st,num,out,ii,oo): if ii>oo: st1=st.copy() out1=out.copy() num1=num.copy() out1.append(st1.pop()) if oo+1==N: print(out1) return else: stack(st1,num,out1,ii,oo+1) if len(num)>0 : st1=st.cop...
Python
zaydzuhri_stack_edu_python
import tkinter set keys = list list tuple string C 1 tuple string CE 1 list tuple string 7 1 tuple string 8 1 tuple string 9 1 tuple string + 1 list tuple string 4 1 tuple string 5 1 tuple string 6 1 tuple string - 1 list tuple string 1 1 tuple string 2 1 tuple string 3 1 tuple string * 1 list tuple string 0 1 tuple st...
import tkinter keys = [[('C', 1), ('CE', 1)], [('7', 1), ('8', 1), ('9', 1), ('+', 1)], [('4', 1), ('5', 1), ('6', 1), ('-', 1)], [('1', 1), ('2', 1), ('3', 1), ('*', 1)], [('0', 1), ('=', 1), ('/', 1)], ] mainWindowPadding = 8 mainWindow = tkinter.Tk() mainWindow.title("Calcu...
Python
zaydzuhri_stack_edu_python
function add_laser_label self begin set laser_label = call CenteredBoldLabel direction if direction in list string v string ^ begin set row = if expression direction == string v then 0 else 2 + height + 1 call addWidget laser_label row 2 + y end else begin set col = if expression direction == string > then 0 else 2 + w...
def add_laser_label(self): laser_label = widgets.CenteredBoldLabel(self._laser.direction) if self._laser.direction in ['v', '^']: row = (0 if self._laser.direction == 'v' else 2 + self._grid.height + 1) self._graphic_grid.addWidget(laser_label, row, 2 + self._l...
Python
nomic_cornstack_python_v1
function _get_tr_dataset_size_from_z0 z0 begin return integer round exp z0 end function
def _get_tr_dataset_size_from_z0(z0): return int(np.round(np.exp(z0)))
Python
nomic_cornstack_python_v1
import sys import itertools import math import numpy as np function distance p1 p2 begin set dx = p2 at 0 - p1 at 0 set dy = p2 at 1 - p1 at 1 set d = square root dx ^ 2 + dy ^ 2 return d end function function calc_route_cost travel_hist begin set d = 0 for i in range length travel_hist - 1 begin set d = d + distance t...
import sys import itertools import math import numpy as np def distance(p1, p2): dx = p2[0] - p1[0] dy = p2[1] - p1[1] d = math.sqrt(dx**2 + dy**2) return d def calc_route_cost(travel_hist): d = 0 for i in range(len(travel_hist) - 1): d += distance(travel_hist[i], travel_hist[i+1]) ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Jan 16 12:09:04 2014 @author: max Rows in csv should have following format <INCHI>,<IUPAC>,<SMILES> <temperature1>, <energy1>, <method1>, <source1> <temperature2>, <energy2>, <method2>, <source2> <temperature3>, <energy3>, <method3>, <source3>, ... import db_interface...
# -*- coding: utf-8 -*- """ Created on Thu Jan 16 12:09:04 2014 @author: max Rows in csv should have following format <INCHI>,<IUPAC>,<SMILES> <temperature1>, <energy1>, <method1>, <source1> <temperature2>, <energy2>, <method2>, <source2> <temperature3>, <energy3>, <method3>, <source3>, ... """ import db_interface...
Python
zaydzuhri_stack_edu_python
class Patient begin set __firstName = string set __surname = string set __hasMedCard = false set __isPrivatePatient = false set __daysInHospital = 1 function __init__ self f_name=string l_name=string med_card_holder=false is_private=false days_stayed=1 begin set __firstName = f_name set __surname = l_name set __has...
class Patient: __firstName = '' __surname = '' __hasMedCard = False __isPrivatePatient = False __daysInHospital = 1 def __init__(self, f_name='', l_name='', med_card_holder=False, is_private=False, days_stayed=1): self.__firstName = f_name self.__surname = l_name self.__...
Python
zaydzuhri_stack_edu_python
function change_currency self currency begin call click call click end function
def change_currency(self, currency): self.browser.find_element(*self.CURRENCY_PICKER).click() self.browser.find_element(By.CSS_SELECTOR, self.CURRENCY_CHOICE + f"[name='{currency}']").click()
Python
nomic_cornstack_python_v1
function convert obj unit axis begin return obj end function
def convert(obj, unit, axis): return obj
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import math from LinearTriangulation import linear_triagulation from Misc.utils import PlotFuncs function cheirality_check C R X_list begin set count = 0 comment third row of R set r3 = R at 2 for X in X_list begin if dot r3 X - C > 0 begin set...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import math from LinearTriangulation import linear_triagulation from Misc.utils import PlotFuncs def cheirality_check(C, R, X_list): count = 0 # third row of R r3 = R[2] for X in X_list: if(np.dot(r3, X-C) > 0): ...
Python
zaydzuhri_stack_edu_python
function parse self begin set parsed_dictionary = call Dictionary set dictionary = call Dictionary set state = pre_signature for tuple lineno line in line_iter begin set lineno = lineno + 1 set line = call decomment_and_normalize line if line == string begin continue end set parsed = false set expected_lines = call ex...
def parse(self) -> Dictionary: self.parsed_dictionary = dictionary = Dictionary() state = State.pre_signature for lineno, line in self.line_iter: lineno += 1 line = decomment_and_normalize(line) if line == "": continue parsed = False ex...
Python
nomic_cornstack_python_v1
function updateconf self md_json begin set metadata = loads md_json comment Global (WMS-wide) metadata set wms_md = metadata at string wmsdata comment Layer medata (array of dicts) set layers = metadata at string layers comment TODO: rasters, vectors should be processed separately in javascript (client-side) to avoid t...
def updateconf( self, md_json ): metadata = json.loads(md_json) ## Global (WMS-wide) metadata self.wms_md = metadata["wmsdata"] ## Layer medata (array of dicts) layers = metadata["layers"] # TODO: rasters, vectors should be processed separately in javasc...
Python
nomic_cornstack_python_v1
function f_R self R begin set R = array R ndmin=1 copy=false comment uniform comment f = ((R >= self.Rrange[0]) & (R <= self.Rrange[1])).astype(int)/(self.Rrange[1]-self.Rrange[0]) comment log-uniform set f = as type R >= Rrange at 0 ? R <= Rrange at 1 int / R * log Rrange at 1 / Rrange at 0 return f end function
def f_R(self, R): R = np.array(R, ndmin=1, copy=False) # uniform # f = ((R >= self.Rrange[0]) & (R <= self.Rrange[1])).astype(int)/(self.Rrange[1]-self.Rrange[0]) # log-uniform f = ((R >= self.Rrange[0]) & (R <= self.Rrange[1])).astype(int)/(R*np.log(self.Rrange[1]/self.R...
Python
nomic_cornstack_python_v1
function main begin set calculator = call Calculator while true begin set count = 1 set cont = string set value1 = none set value2 = none call print_menu set operand = input string Your option from the menu (1 - 10): if operand in valid_choice and operand not in valid_choice at slice 6 : : begin set value1 = call nu...
def main(): calculator = Calculator() while True: count = 1 cont = "" value1 = None value2 = None calculator.print_menu() operand = input("Your option from the menu (1 - 10): ") if operand in valid_choice and operand not in valid_choice[6:]: ...
Python
nomic_cornstack_python_v1
import sqlite3 set conn = call connect string RAMAN.db set c = call cursor execute c string CREATE table LINK(ID INT, ELEMENT_NUMBER INT, MOL_NUMBER INT) execute c string INSERT INTO LINK VALUES (1, 1, '1') execute c string INSERT INTO LINK VALUES (2, 8, '1') execute c string INSERT INTO LINK VALUES (3, 6, '2') execute...
import sqlite3 conn = sqlite3.connect('RAMAN.db') c = conn.cursor() c.execute("CREATE table LINK(ID INT, ELEMENT_NUMBER INT, MOL_NUMBER INT)"); c.execute("INSERT INTO LINK VALUES (1, 1, '1')"); c.execute("INSERT INTO LINK VALUES (2, 8, '1')"); c.execute("INSERT INTO LINK VALUES (3, 6, '2')"); c.execute("INSERT ...
Python
zaydzuhri_stack_edu_python
function fannkuch n begin set count = list range 1 n + 1 set max_flips = 0 set m = n - 1 set r = n set check = 0 set perm1 = list range n set perm = list range n set perm1_ins = insert set perm1_pop = pop while 1 begin if check < 30 begin print join string generator expression string i + 1 for i in perm1 set check = c...
def fannkuch(n): count = list(range(1, n+1)) max_flips = 0 m = n-1 r = n check = 0 perm1 = list(range(n)) perm = list(range(n)) perm1_ins = perm1.insert perm1_pop = perm1.pop while 1: if check < 30: print("".join(str(i+1) for i in perm1)) check +=...
Python
zaydzuhri_stack_edu_python
function get_instance_list begin return call parse_list_output communicate popen split string nova list --all-tenants stdout=STDOUT stderr=STDERR at 0 end function
def get_instance_list(): return parse_list_output(Popen('nova list --all-tenants'.split(), stdout=STDOUT, stderr=STDERR).communicate()[0])
Python
nomic_cornstack_python_v1
import numpy as np import cv2 from matplotlib import pyplot as plt set cap = call VideoCapture string movie.mp4 set count = integer get cap CAP_PROP_FRAME_COUNT print count set tuple ret frame = read cap set count = count - 1 print count set hsv = call cvtColor frame COLOR_BGR2HSV set satulationAverage = list comprehen...
import numpy as np import cv2 from matplotlib import pyplot as plt cap = cv2.VideoCapture("movie.mp4") count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) print(count) ret, frame = cap.read() count = count - 1 print(count) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) satulationAverage = [i[0] for i in cv2.calcHist([hsv]...
Python
zaydzuhri_stack_edu_python
function list_intersection listA listB begin comment create empty intersection set intersection = list comment for each item a of listA for a in listA begin comment is any b of listB the same as a? for b in listB begin if a == b begin comment found a, add it to intersection append intersection a end end end comment al...
def list_intersection(listA, listB): # create empty intersection intersection = [] # for each item a of listA for a in listA: # is any b of listB the same as a? for b in listB: if a == b: # found a, add it to intersection intersection.append(...
Python
nomic_cornstack_python_v1
comment Gets two inputs as two integers. Outputs the first integer and subsequent increments of 10 as long as the value is less than or equal to the second integer. set num1 = integer input set num2 = integer input if num2 < num1 begin print string Second integer can't be less than the first. end else if num1 == num2 b...
# Gets two inputs as two integers. Outputs the first integer and subsequent increments of 10 as long as the value is less than or equal to the second integer. num1 = int(input()) num2 = int(input()) if num2 < num1: print('Second integer can\'t be less than the first.') elif num1 == num2: print(num1, end=' ') ...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd from sklearn.base import TransformerMixin , BaseEstimator from nltk.sentiment.vader import SentimentIntensityAnalyzer class FeatureExtraction extends BaseEstimator TransformerMixin begin string Accepts a df, returns feature list based on params given converts a corpus into a featu...
import numpy as np import pandas as pd from sklearn.base import TransformerMixin, BaseEstimator from nltk.sentiment.vader import SentimentIntensityAnalyzer; class FeatureExtraction(BaseEstimator, TransformerMixin): ''' Accepts a df, returns feature list based on params given converts a corpus into a featur...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render from models import Data , Result from forms import DataForm comment http://127.0.0.1:8000/task/add comment Представление, которое предназначено для отображения страницы ввода набора данных function add request begin comment Служебные переменные set type_page = string home set headlin...
from django.shortcuts import render from .models import Data, Result from .forms import DataForm # http://127.0.0.1:8000/task/add # Представление, которое предназначено для отображения страницы ввода набора данных def add(request): # Служебные переменные type_page = "home" headline = "Тестовое задание" ...
Python
zaydzuhri_stack_edu_python
function build_loss_and_gradients self var_list begin if use_rb begin print string USING RAO-BLACKWELL return call build_score_rb_loss_and_gradients_relbo self var_list end else begin return call build_reparam_loss_and_gradients self var_list end comment the rest is ignored set is_reparameterizable = all list comprehen...
def build_loss_and_gradients(self, var_list): if FLAGS.use_rb: print("USING RAO-BLACKWELL") return build_score_rb_loss_and_gradients_relbo(self, var_list) else: return build_reparam_loss_and_gradients(self, var_list) # the rest is ignored is_reparameterizable = all([ rv.repar...
Python
nomic_cornstack_python_v1
import math import sys import pygame from bork import Bork from kitty import Kitty comment The following functions contain code for game controls. function check_events settings screen stats scoreboard play_button kitties corgi borks begin string Handle registration of all available key events for event in get event be...
import math import sys import pygame from bork import Bork from kitty import Kitty # The following functions contain code for game controls. def check_events(settings, screen, stats, scoreboard, play_button, kitties, corgi, borks): """Handle registration of all available key events""" for e...
Python
zaydzuhri_stack_edu_python
from expyriment import stimuli from expyriment.misc import constants from keys_info import key_mapping class PianoKey begin string Class implementing a single piano key as stimulus rectangle function __init__ self key_mapping begin set name = key_mapping at string key set kid = key_mapping at string kid comment key boa...
from expyriment import stimuli from expyriment.misc import constants from keys_info import key_mapping class PianoKey: ''' Class implementing a single piano key as stimulus rectangle ''' def __init__(self, key_mapping): self.name = key_mapping['key'] self.kid = key_mapping['kid'] ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import argparse import sys set parser = call ArgumentParser description=string remove entries with heterozygosity rate over specified percent call add_argument string -i string --input default=stdin type=call FileType string r help=string input file (default stdin) call add_argument string ...
#!/usr/bin/env python import argparse import sys parser = argparse.ArgumentParser(description='remove entries with heterozygosity rate over specified percent') parser.add_argument('-i', '--input', default=sys.stdin, type=argparse.FileType('r'), help='input file (default stdin)') parser.add_argument('-m', '--max_het_r...
Python
zaydzuhri_stack_edu_python
function decompose polygon origin=none width=1.0 begin set p = call generate_intersections polygon width if origin == none begin return call order_points p bounds at slice 0 : 2 : end else begin return call order_points p origin end end function
def decompose(polygon, origin=None, width=1.0): p = generate_intersections(polygon, width) if origin == None: return order_points(p, polygon.bounds[0:2]) else: return order_points(p, origin)
Python
nomic_cornstack_python_v1
function _reload self event opts begin set options = get opts string fn_task_utils dict end function
def _reload(self, event, opts): self.options = opts.get("fn_task_utils", {})
Python
nomic_cornstack_python_v1