code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function clear_generic_text_badge_color node begin comment Try to remove the user data from the node. If the data doesn't exist comment it will fail, but we can just ignore that. with call disabler ; suppress OperationFailed begin call destroyUserData call get_generic_text_color_key end end function
def clear_generic_text_badge_color(node: hou.Node) -> None: # Try to remove the user data from the node. If the data doesn't exist # it will fail, but we can just ignore that. with hou.undos.disabler(), contextlib.suppress(hou.OperationFailed): node.destroyUserData(_ht_generic_text_badge.get_generic...
Python
nomic_cornstack_python_v1
class TreeNode begin function __init__ self val=0 left=none right=none begin set val = val set left = left set right = right end function end class class Solution begin function widthOfBinaryTree self root begin if not root begin return 0 end comment (node, depth, position) set queue = list tuple root 0 0 set max_width...
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def widthOfBinaryTree(self, root: TreeNode) -> int: if not root: return 0 queue = [(root, 0, 0)] #(node, depth, position) ...
Python
zaydzuhri_stack_edu_python
function test_std_tensorboard_all_parameters self begin with call session_context call Graph begin set model = call create_linear_model function task_factory writer begin comment create 2 extra summaries set dummy_vars = list call Variable 5.0 call Variable 6.0 set dummy_vars_init = call variables_initializer dummy_var...
def test_std_tensorboard_all_parameters(self): with session_context(tf.Graph()): model = create_linear_model() def task_factory(writer: mon.LogdirWriter): # create 2 extra summaries dummy_vars = [tf.Variable(5.0), tf.Variable(6.0)] dummy_v...
Python
nomic_cornstack_python_v1
function which program begin function is_exe fpath begin if is file path fpath and call access fpath X_OK begin return true end return false end function for path in split environ at string PATH pathsep begin for ext in split call getenv string PATHEXT string pathsep begin set fname = program + lower ext set abspath = ...
def which(program): def is_exe(fpath): if os.path.isfile(fpath) and os.access(fpath, os.X_OK): return True return False for path in os.environ["PATH"].split(os.pathsep): for ext in os.getenv("PATHEXT", "").split(os.pathsep): fname = program + ext.lower() ...
Python
nomic_cornstack_python_v1
string These test cases are designed to test the ability to create experiments from WebUI.WebUI import WebUI set web_sess = call WebUI function test_create_experiment login_texpadmin begin string **Requirements:** - 3.1.4: The system shall allow experiments to be created. - 3.1.4.1.1: Experiment administrators shall ha...
""" These test cases are designed to test the ability to create experiments """ from WebUI.WebUI import WebUI web_sess = WebUI() def test_create_experiment(login_texpadmin): """ **Requirements:** - 3.1.4: The system shall allow experiments to be created. - 3.1.4.1.1: Experiment administrators shall ...
Python
zaydzuhri_stack_edu_python
import operator set str = input string Please enter a string: set str = lower str set l = length str set Dict = dict set a = 0 function most_frequent st begin set i = 0 while i < l begin set k = 1 set a = 0 set ch = st at i if i == 0 begin set j = 1 while j < l begin set ch2 = st at j if ch == ch2 begin set k = k + 1 ...
import operator str = input("Please enter a string: ") str = str.lower() l = len(str) Dict = {} a=0 def most_frequent(st): i = 0 while i < l: k=1 a=0 ch = st[i] if i == 0: j = 1 while j<l: ch2 = st[j] if ...
Python
zaydzuhri_stack_edu_python
import base64 , getpass from base_datos import db_ecommerce from validacion import check from ubicacion import city class New_User begin function __init__ self begin set __id = 0 set __nombre = string set __email = string set __password = string set __ciudad = string set __provincia = string set __pais = string e...
import base64, getpass from base_datos import db_ecommerce from validacion import check from ubicacion import city class New_User(): def __init__(self): self.__id=0 self.__nombre="" self.__email="" self.__password="" self.__ciudad="" self.__provincia="" self._...
Python
zaydzuhri_stack_edu_python
function get_serial_hwid self begin return hwid end function
def get_serial_hwid(self): return self.__SERIAL_CONNECTION.hwid
Python
nomic_cornstack_python_v1
function data_definition query cursor execute_many=false data=none begin if execute_many begin call executemany query data end else begin execute cursor query end if string DROP in query begin print string Table dropped successfully end else if string CREATE in query begin print string Table created successfully end en...
def data_definition(query: str, cursor, execute_many=False, data=None): if execute_many: cursor.executemany(query, data) else: cursor.execute(query) if "DROP" in query: print('Table dropped successfully') elif "CREATE" in query: print("Table created successfully")
Python
nomic_cornstack_python_v1
set curupira = integer input * 300 set boitata = integer input * 1500 set boto = integer input * 600 set mapinguari = integer input * 1000 set iara = integer input * 150 set chica = 225 set total = curupira + boitata + boto + mapinguari + iara + chica print total
curupira = int(input())*300 boitata = int(input())*1500 boto = int(input())*600 mapinguari = int(input())*1000 iara = int(input())*150 chica = 225 total = curupira + boitata + boto + mapinguari + iara + chica print(total)
Python
zaydzuhri_stack_edu_python
string Реализуйте программу, которая будет эмулировать работу с пространствами имен. Необходимо реализовать поддержку создания пространств имен и добавление в них переменных. В данной задаче у каждого пространства имен есть уникальный текстовый идентификатор – его имя. Вашей программе на вход подаются следующие запросы...
''' Реализуйте программу, которая будет эмулировать работу с пространствами имен. Необходимо реализовать поддержку создания пространств имен и добавление в них переменных. В данной задаче у каждого пространства имен есть уникальный текстовый идентификатор – его имя. Вашей программе на вход подаются следующие запросы:...
Python
zaydzuhri_stack_edu_python
comment pip install requests comment pip install pygeoip comment Display Temperature with Python import requests import pygeoip set url_ip = string http://httpbin.org/ip set response_ip = get requests url_ip set ip_addr = string json response_ip at string origin comment http://dev.maxmind.com/geoip/legacy/install/city/...
# pip install requests # pip install pygeoip #Display Temperature with Python import requests import pygeoip url_ip = "http://httpbin.org/ip" response_ip = requests.get(url_ip) ip_addr = str(response_ip.json()['origin']) # http://dev.maxmind.com/geoip/legacy/install/city/ gi = pygeoip.GeoIP('/usr/local/share/GeoI...
Python
zaydzuhri_stack_edu_python
import Tkinter as tk comment create TK object as window set window = call Tk title window string RasPi_Scope comment funcs function say_something begin set name = string get entry_field1 comment create text field set phrase_display = call Text master=window height=10 width=30 comment position it grid row=3 column=2 ins...
import Tkinter as tk window = tk.Tk() #create TK object as window window.title("RasPi_Scope") #funcs def say_something(): name = str(entry_field1.get()) #create text field phrase_display = tk.Text(master=window, height=10, width=30) #position it phrase_display.grid(row=3, column=2) phrase_display.insert(tk.EN...
Python
zaydzuhri_stack_edu_python
function _get_reordered_list self origlist reordering begin return list comprehension origlist at e for e in reordering end function
def _get_reordered_list(self, origlist, reordering): return [origlist[e] for e in reordering]
Python
nomic_cornstack_python_v1
function basic_die size=tuple 10000 10000 street_width=100 street_length=1000 die_name=string chip99 text_size=100 text_location=string SW layer=0 draw_bbox=true bbox_layer=99 begin set D = device name=string die set tuple sx sy = tuple size at 0 / 2 size at 1 / 2 set xpts = array list sx sx sx - street_width sx - stre...
def basic_die(size = (10000, 10000), street_width = 100, street_length = 1000, die_name = 'chip99', text_size = 100, text_location = 'SW', layer = 0, draw_bbox = True, bbox_layer = 99): D = Device(name = ...
Python
nomic_cornstack_python_v1
string A module for loading settings import logging.config import sys from logging import getLogger from pathlib import Path import yaml from hazelsync.metrics import get_metrics_engine set DEFAULT_SETTINGS = string /etc/hazelsync.yaml set CLUSTER_DIRECTORY = string /etc/hazelsync.d set DEFAULT_LOGGING = dict string ve...
'''A module for loading settings''' import logging.config import sys from logging import getLogger from pathlib import Path import yaml from hazelsync.metrics import get_metrics_engine DEFAULT_SETTINGS = '/etc/hazelsync.yaml' CLUSTER_DIRECTORY = '/etc/hazelsync.d' DEFAULT_LOGGING = { 'version': 1, 'formatt...
Python
jtatman_500k
for x in range n begin set a = split input set fin = list for i in a begin append fin integer i end append array fin end set cumm = list comprehension list comprehension 0 for x in range m for y in range n set i = 0 while i < m begin set j = n - 1 while j >= 0 begin if j == n - 1 begin set cumm at j at i = array at j ...
for x in range(n): a=input().split() fin=[] for i in a: fin.append(int(i)) array.append(fin) cumm=[[0 for x in range(m)] for y in range(n)] i=0 while(i<m): j=n-1 while(j>=0): if(j==n-1): cumm[j][i]=array[j][i] elif(array[j][i]==1): cumm[j][i]=cumm[...
Python
jtatman_500k
function cartesian arrays out=none begin set arrays = list comprehension call asarray x for x in arrays set dtype = dtype set n = call prod list comprehension size for x in arrays if out is none begin set out = zeros list n length arrays dtype=dtype end set m = n / size set out at tuple slice : : 0 = repeat arrays a...
def cartesian(arrays, out=None): arrays = [numpy.asarray(x) for x in arrays] dtype = arrays[0].dtype n = numpy.prod([x.size for x in arrays]) if out is None: out = numpy.zeros([n, len(arrays)], dtype=dtype) m = n / arrays[0].size out[:, 0] = numpy.repeat(arrays[0], m) if arrays[1:...
Python
nomic_cornstack_python_v1
function build_eight_process_flowsheet begin set m = call ConcreteModel name=string DuranEx3 Disjunctive string Set declarations set streams = call RangeSet 2 25 doc=string process streams set units = call RangeSet 1 8 doc=string process units set no_unit_zero_flows = dict 1 tuple 2 3 ; 2 tuple 4 5 ; 3 tuple 9 ; 4 tupl...
def build_eight_process_flowsheet(): m = ConcreteModel(name='DuranEx3 Disjunctive') """Set declarations""" m.streams = RangeSet(2, 25, doc="process streams") m.units = RangeSet(1, 8, doc="process units") no_unit_zero_flows = { 1: (2, 3), 2: (4, 5), 3: (9,), 4: (12, ...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt from skimage import filters as skimfilt from scipy.ndimage import label as sci_lab comment project the image onto a specific direction function project img direction begin if direction == string x begin set proj = sum img 0 end else if direction == string y begin set p...
import numpy as np import matplotlib.pyplot as plt from skimage import filters as skimfilt from scipy.ndimage import label as sci_lab # project the image onto a specific direction def project(img, direction): if direction == "x": proj = np.sum(img, 0) elif direction == "y": proj = np.sum(img, ...
Python
zaydzuhri_stack_edu_python
while true begin print string Bienvenido al menu iterativo Elige una opcion: 1) Saludo 2) Sumar dos numeros 3) Iterar 4) Salir set r = input if r == string 1 begin print string Hola, saludos desde la terminal de Rodrigo end else if r == string 2 begin set n1 = decimal input string Ingresa el primer numero: set n2 = dec...
while True: print("""Bienvenido al menu iterativo Elige una opcion: 1) Saludo 2) Sumar dos numeros 3) Iterar 4) Salir""") r = input() if r == '1': print("Hola, saludos desde la terminal de Rodrigo") elif r == '2': n1 = float(input("Ingresa el primer numero: ")) n2 = float(input("Ingresa el segundo nume...
Python
zaydzuhri_stack_edu_python
async function ban self ctx target reason=string No reason given. begin call check_perms author target set handler = await call new bot guild await call ban author target reason await call success string { target } (` { id } `) has been banned for: { reason } end function
async def ban(self, ctx, target: BanCandidateConverter, *, reason: str = "No reason given." ): self.check_perms(ctx.author, target) handler = await Handler.new(self.bot, ctx.guild) await handler.ban(ctx.author, target, reason) await ctx.success(f"{target} (`{target.id}`) has been banned for:\n{reaso...
Python
nomic_cornstack_python_v1
string This file is part of Sugar-Clic Sugar-Clic is copyrigth 2009 by Maria Jose Casany Guerrero and Marc Alier Forment of the Universitat Politecnica de Catalunya http://www.upc.edu Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu Sugar-Clic is free software: you can redistribute it and/o...
''' This file is part of Sugar-Clic Sugar-Clic is copyrigth 2009 by Maria Jose Casany Guerrero and Marc Alier Forment of the Universitat Politecnica de Catalunya http://www.upc.edu Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu Sugar-Clic is free softwar...
Python
zaydzuhri_stack_edu_python
import random 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 is_palindrome n begin return string n == string n at slice : : - 1 end function set primes = list while length primes < 10 begi...
import random 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 is_palindrome(n): return str(n) == str(n)[::-1] primes = [] while len(primes) < 10: num = random.randint(500, 1000) if is_prime(num...
Python
jtatman_500k
comment ====== Find the kth max and min elelment of an array ========= string Input --> N = 6 arr[] = 7 10 4 3 20 15 k = 3 output : 7 Explanation: 3rd smallest element in the given array is 7 comment kth smallest element set list = list 7 10 4 3 20 15 set k = 3 set asceding_list = list function kth_min_element list be...
#====== Find the kth max and min elelment of an array ========= ''' Input --> N = 6 arr[] = 7 10 4 3 20 15 k = 3 output : 7 Explanation: 3rd smallest element in the given array is 7 ''' # kth smallest element list = [7,10,4,3,20,15] k = 3 asceding_list =[] def kth_min_element(list): i = list[0] if len(list...
Python
zaydzuhri_stack_edu_python
function factorialDigitSum self n begin set ans = list 1 for i in call xrange n + 1 begin if i < length factorialList begin set ans = factorialList at i end else begin set ans = call __multiply i ans append factorialList ans end end return sum factorialList at n end function
def factorialDigitSum(self, n): ans = [1] for i in xrange(n+1): if i < len(self.factorialList): ans = self.factorialList[i] else: ans = self.__multiply(i, ans) self.factorialList.append(ans) return sum(self.factorialList[n])
Python
nomic_cornstack_python_v1
comment for02.py set a = list 0 1 2 3 4 5 6 7 8 9 set b = list range 0 10 1 print b set c = list range 100 print c set d = list range 100 0 - 1 print d set e = list comprehension i * i for i in range 1 11 print e set e = list comprehension i * i for i in range 1 11 if i * i % 2 == 1 print e set e = list comprehension i...
# for02.py a = [0,1,2,3,4,5,6,7,8,9] b = list(range(0,10,1)) print(b) c = list(range(100)) print(c) d = list(range(100,0,-1)) print(d) e = [ i*i for i in range(1,11)] print(e) e = [ i*i for i in range(1,11) if(((i*i)%2) == 1) ] print(e) e = [ i*i for i in range(1,11) if not (i*i)%2 ] print(e) f ...
Python
zaydzuhri_stack_edu_python
function get_course_grade_items self coursename begin set params = request_params update params dict string wsfunction string local_presentation_get_course_grade_items ; string course coursename return json get session api_url params=params end function
def get_course_grade_items(self, coursename): params = self.config.request_params params.update({ 'wsfunction': 'local_presentation_get_course_grade_items', 'course': coursename }) return self.config.session.get(self.config.api_url, params=params).json()
Python
nomic_cornstack_python_v1
import collections import math function nod mas begin if length mas == 1 begin return mas at 0 end return call gcd mas at 0 call nod mas at slice 1 : : end function function get_substrings length begin set result = counter with open string crypt.txt string r as fin begin set text = read fin end for i in range 0 length...
import collections import math def nod(mas): if len(mas) == 1: return mas[0] return math.gcd(mas[0], nod(mas[1:])) def get_substrings(length): result = collections.Counter() with open("crypt.txt", 'r') as fin: text = fin.read() for i in range(0, len(text) - length + 1): r...
Python
zaydzuhri_stack_edu_python
import re import time import os import argparse set MAX_SIMILAR_LENGTH = 1 set MAX_LEVENSHTEIN_DISTANCE = 2 comment calculates leveshtein distance between two strings function levenshtein s1 s2 begin if length s1 < length s2 begin return call levenshtein s2 s1 end if length s2 == 0 begin return length s1 end set previo...
import re import time import os import argparse MAX_SIMILAR_LENGTH = 1 MAX_LEVENSHTEIN_DISTANCE = 2 # calculates leveshtein distance between two strings def levenshtein(s1, s2): if len(s1) < len(s2): return levenshtein(s2, s1) if len(s2) == 0: return len(s1) previous_row = range(len(s2) ...
Python
zaydzuhri_stack_edu_python
for i in range 0 n begin append marks integer input string enter marks: append names string input string enter names: end function maximum ma na begin set maxmarks = max ma set i = index ma maxmarks set name = na at i return tuple maxmarks name end function set maxi = call maximum marks names print string marks: marks ...
for i in range(0,n): marks.append(int(input("enter marks: "))) names.append(str(input("enter names: "))) def maximum(ma,na): maxmarks=max(ma) i=ma.index(maxmarks) name=na[i] return(maxmarks,name) maxi=maximum(marks,names) print("marks: ",marks) print("names: ",names) print(maxi)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string kongpengju.com import pygame , sys , time , random , re , readFile from pygame.locals import * call init comment open file set openWordNote = open string wordlist.md string r comment write lists function mainSeeWordList begin set wordList = find all str...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ kongpengju.com """ import pygame, sys, time, random, re, readFile from pygame.locals import * pygame.init() # open file openWordNote = open('wordlist.md','r') # write lists def mainSeeWordList(): wordList = re.findall(r'[(](.*?)[)]', openWordNote.read()) ...
Python
zaydzuhri_stack_edu_python
function skipUnlessAnyDBFeature *features begin return call _deferredSkip lambda -> not any generator expression get attribute features feature false for feature in features string Database doesn't support any of the feature(s): %s % join string , features string skipUnlessAnyDBFeature end function
def skipUnlessAnyDBFeature(*features): return _deferredSkip( lambda: not any(getattr(connection.features, feature, False) for feature in features), "Database doesn't support any of the feature(s): %s" % ", ".join(features), 'skipUnlessAnyDBFeature', )
Python
nomic_cornstack_python_v1
import csv set csvfile = open string mn_headers.csv string rt encoding=string UTF-8 set reader = reader csvfile comment 存放的是简写名和全名,全部的数据 set dict = dict for row in reader begin comment print(row[0],'\t',row[1]) set dict at row at 0 = row at 1 end close csvfile print length dict set file = open string mn.csv string rt ...
import csv csvfile = open('mn_headers.csv','rt',encoding='UTF-8') reader = csv.reader(csvfile) #存放的是简写名和全名,全部的数据 dict = {} for row in reader: # print(row[0],'\t',row[1]) dict[row[0]] = row[1] csvfile.close() print(len(dict)) file = open('mn.csv','rt',encoding='UTF-8') reader = csv.reader(file) header = [h fo...
Python
zaydzuhri_stack_edu_python
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt set all_images_path = string lfw2Data/lfw2 set main_directory_content = list comprehension join sep list all_images_path x for x in list filter lambda x -> not find lower string x string ds_store != - 1 list directory all_images_path funct...
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt all_images_path = 'lfw2Data/lfw2' main_directory_content = [os.sep.join([all_images_path, x]) for x in list(filter(lambda x: not str(x).lower().find('ds_store')!=-1, os.listdir(all_images_path)))] def plot_distribution_num_of_images()...
Python
zaydzuhri_stack_edu_python
comment ou are given a set and other sets. comment Your job is to find whether set is a strict superset of each of the sets. comment Print True, if is a strict superset of each of the sets. Otherwise, print False. comment A strict superset has at least one element that does not exist in its subset. comment Example comm...
# ou are given a set and other sets. # Your job is to find whether set is a strict superset of each of the sets. # Print True, if is a strict superset of each of the sets. Otherwise, print False. # A strict superset has at least one element that does not exist in its subset. # Example # Set is a strict superse...
Python
zaydzuhri_stack_edu_python
comment MODULE BASIS PROGRAMMEREN comment OEFENING 2 comment CURSIST: JONAS LANCKMAN comment SEQUENTIE EN SELECTIE comment DATATYPES : CHAR, STRING, INTEGER comment De gebruiker dient een geboortejaar in te geven comment De gebruiker dient ook het huidige jaar in te geven comment Wanneer het verschil tussen het huidige...
# MODULE BASIS PROGRAMMEREN # OEFENING 2 # CURSIST: JONAS LANCKMAN # SEQUENTIE EN SELECTIE # DATATYPES : CHAR, STRING, INTEGER # De gebruiker dient een geboortejaar in te geven # De gebruiker dient ook het huidige jaar in te geven # Wanneer het verschil tussen het huidige jaar en geboortejaar groter is of gelijk is aan...
Python
zaydzuhri_stack_edu_python
comment import image_slicer comment import scipy comment from matplotlib import pyplot as plt import cv2 comment from PIL import ImageDraw, ImageFont comment #from scipy.misc import imsave comment from scipy import ndimage comment from scipy import misc comment import scipy.misc import numpy as np comment import random...
# import image_slicer # import scipy # from matplotlib import pyplot as plt import cv2 # from PIL import ImageDraw, ImageFont # #from scipy.misc import imsave # from scipy import ndimage # from scipy import misc # import scipy.misc import numpy as np # import random # import sys # from image_slicer import join # from d...
Python
zaydzuhri_stack_edu_python
function handlers self begin return _handlers end function
def handlers(self) -> Dict[str, Callable]: return self._handlers
Python
nomic_cornstack_python_v1
import pandas as pd comment importing cleaned Primary NAR dataset set NAR = call ExcelFile string /home/varun/PrimaryNAR_cleaned.xlsx set NAR = call read_excel string /home/varun/PrimaryNAR_cleaned.xlsx index_col=1 comment Dividing of countries into region comment we made a list of countries according to their ISO Code...
import pandas as pd # importing cleaned Primary NAR dataset NAR = pd.ExcelFile(r"/home/varun/PrimaryNAR_cleaned.xlsx") NAR = pd.read_excel("/home/varun/PrimaryNAR_cleaned.xlsx",index_col = 1) # Dividing of countries into region # we made a list of countries according to their ISO Code Arabic = ['ARM','GEO','IRQ','JO...
Python
zaydzuhri_stack_edu_python
function identifiers self begin return dict string user_guid call user_guid end function
def identifiers(self): return {"user_guid": self.user_guid()}
Python
nomic_cornstack_python_v1
function list_artifacts self path begin pass end function
def list_artifacts(self, path): pass
Python
nomic_cornstack_python_v1
function create cls payload begin set payload at string slug = call create_order_slug return call create payload end function
def create(cls, payload: dict) -> 'Item': payload['slug'] = create_order_slug() return super().create(payload)
Python
nomic_cornstack_python_v1
comment Импорт объекта app из модуля app from app import app comment Импорт нужных функций из библиотеки flask from flask import render_template , request comment Импортируем наш модуль from app.model.task import Task decorator call route string / methods=list string GET string POST comment Декоратор, который говорил к...
# Импорт объекта app из модуля app from app import app # Импорт нужных функций из библиотеки flask from flask import render_template, request # Импортируем наш модуль from app.model.task import Task # Декоратор, который говорил какой url слушать, в данном случае / и методы которые обработчик может воспринемать (post ...
Python
zaydzuhri_stack_edu_python
function query_interval self query begin yield list comprehension iv for iv in centered if iv at 0 <= query at 1 and iv at 1 >= query at 0 if query at 1 < center and children at 0 begin for found in call query_interval query begin yield found end end if center < query at 0 and children at 1 begin for found in call quer...
def query_interval(self, query): yield [iv for iv in self.centered if iv[0] <= query[1] \ and iv[1] >= query[0]] if query[1] < self.center \ and self.children[0]: for found in self.children[0].query_interval(query): yield fo...
Python
nomic_cornstack_python_v1
function check_design self begin comment compute VIF from self.desmtx.mat by iteration comment through all of the parameters (columns). comment Iterate through each column of the matrix by comment using a boolean array index with compress. comment Collect each parameter's VIF in par_vif using comment the getVIF helper ...
def check_design(self): # compute VIF from self.desmtx.mat by iteration # through all of the parameters (columns). # Iterate through each column of the matrix by # using a boolean array index with compress. # Collect each parameter's VIF in par_vif using # the getVIF helpe...
Python
nomic_cornstack_python_v1
function IsContainer self begin set callResult = call _Call string IsContainer if callResult is none begin return none end return callResult end function
def IsContainer(self): callResult = self._Call("IsContainer", ) if callResult is None: return None return callResult
Python
nomic_cornstack_python_v1
from Classes.Models.HashNotification import HashNotification from Classes.Models.notification import Notification class NotiObjAdapter extends HashNotification begin string converts Notification Object inot Hash Format Notification function __init__ self notiObj begin set notiObj = notiObj end function function getNoti...
from Classes.Models.HashNotification import HashNotification from Classes.Models.notification import Notification class NotiObjAdapter(HashNotification): """converts Notification Object inot Hash Format Notification""" def __init__(self, notiObj): self.notiObj = notiObj def getNotificationMsg(se...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import string import keras from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from keras.layers import Dense , Dropout , Embedding , LSTM , Input , Flatten from keras.models import Sequential...
import numpy as np import pandas as pd import string import keras from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.utils import to_categorical from keras.layers import Dense, Dropout, Embedding, LSTM, Input, Flatten from keras.models import Sequential da...
Python
jtatman_500k
comment !/usr/bin/env python3 import sys import os set __doc__ = string Yêu cầu: Viết script ex8_2.py: - khi gọi với -h tên_file sẽ in ra 10 dòng đầu tiên của file, - khi gọi với -t tên_file sẽ in ra 10 dòng cuối cùng của file. Usage:: ex8_2.py -h file_path -> Print 10 first lines of file_path ex8_2.py -t file_path -> ...
#!/usr/bin/env python3 import sys import os __doc__ = ''' Yêu cầu: Viết script ex8_2.py: - khi gọi với -h tên_file sẽ in ra 10 dòng đầu tiên của file, - khi gọi với -t tên_file sẽ in ra 10 dòng cuối cùng của file. Usage:: ex8_2.py -h file_path -> Print 10 first lines of file_path ex8_2.py -t file_path -> P...
Python
zaydzuhri_stack_edu_python
function _save_topic_word_counts self outfilestr begin with open outfilestr string w+ as fid begin comment Print the topic-headers write fid string WordLabel, for i_topic in range n_topics begin write fid format string Topic_{0:02d}, i_topic + 1 end write fid string comment For each row / wlabel: wlabel-string and its ...
def _save_topic_word_counts(self, outfilestr): with open(outfilestr, "w+") as fid: # Print the topic-headers fid.write("WordLabel,") for i_topic in range(self.n_topics): fid.write("Topic_{0:02d},".format(i_topic + 1)) fid.write("\n") #...
Python
nomic_cornstack_python_v1
import os import subprocess import glob comment Disclaimer: If you want to do a full, more robust amount of testing, comment I would recommend using the unittest library comment <- Yeah this one import unittest comment But it requires a little more than what we're just going over in this comment tutorial (e.g. classes)...
import os import subprocess import glob # Disclaimer: If you want to do a full, more robust amount of testing, # I would recommend using the unittest library import unittest # <- Yeah this one # But it requires a little more than what we're just going over in this # tutorial (e.g. classes), but with a little bit read...
Python
zaydzuhri_stack_edu_python
comment You work for a manufacturer, comment and have been asked to calculate comment the total profit made on the comment sales of a product. You are given comment a dictionary containing the cost comment price per unit (in dollars), comment sell price per unit (in dollars), comment and the starting inventory. comment...
#You work for a manufacturer, #and have been asked to calculate #the total profit made on the #sales of a product. You are given #a dictionary containing the cost #price per unit (in dollars), #sell price per unit (in dollars), #and the starting inventory. #Return the total profit made, rounded to the nearest dollar. ...
Python
zaydzuhri_stack_edu_python
import numpy as np function generate_private_key w row col begin comment proving max(S) < w set K = call rand row col * w / 2 ^ 16 return K end function function encryption p K row col w begin comment proving max(e) < w / 2 set e = call rand row set c = dot w * p + e return c end function function decryption c K w begi...
import numpy as np def generate_private_key(w,row,col): K = (np.random.rand(row,col) * w / (2 ** 16)) # proving max(S) < w return K def encryption(p,K,row,col,w): e = (np.random.rand(row)) # proving max(e) < w / 2 c = np.linalg.inv(K).dot((w * p) + e) return c def decryption(c,K,w): retur...
Python
zaydzuhri_stack_edu_python
import typing import functools import inspect import pathlib from dataclasses import dataclass from types import AnyKwargs , AnyCallable set default_sub_path = string decorator dataclass class Route begin set endpoint : Callable at tuple Ellipsis Any set args : Tuple set kwargs : AnyKwargs set path : str = default_sub...
import typing import functools import inspect import pathlib from dataclasses import dataclass from .types import AnyKwargs, AnyCallable default_sub_path = "" @dataclass class Route: endpoint: typing.Callable[..., typing.Any] args: typing.Tuple kwargs: AnyKwargs path: str = default_sub_path T = t...
Python
zaydzuhri_stack_edu_python
comment Double-Base Palindromes function is_palindrome s begin if is instance s int begin set s = string s end return s == s at slice : : - 1 end function function to_base_2 n begin if is instance n str begin set n = integer n end return binary n at slice 2 : : end function function is_double_base_palindrome n begi...
# Double-Base Palindromes def is_palindrome(s): if isinstance(s, int): s = str(s) return s == s[::-1] def to_base_2(n): if isinstance(n, str): n = int(n) return bin(n)[2:] def is_double_base_palindrome(n): return is_palindrome(n) and is_palindrome(to_base_2(n)) def double_base_pa...
Python
zaydzuhri_stack_edu_python
function ip_configurations self begin return get pulumi self string ip_configurations end function
def ip_configurations(self) -> Optional[Sequence['outputs.NicIpConfigurationResourceSettingsResponse']]: return pulumi.get(self, "ip_configurations")
Python
nomic_cornstack_python_v1
import numpy as np import cv2 import os comment face_cascade_Haar=cv2.CascadeClassifier('C:\\Users\\nic 005\\Downloads\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml') comment face_cascade_LBP=cv2.CascadeClassifier('C:\\Users\\nic 005\\Downloads\\opencv\\sources\\data\\lbpcascades\\lbpcascade...
import numpy as np import cv2 import os #face_cascade_Haar=cv2.CascadeClassifier('C:\\Users\\nic 005\\Downloads\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml') #face_cascade_LBP=cv2.CascadeClassifier('C:\\Users\\nic 005\\Downloads\\opencv\\sources\\data\\lbpcascades\\lbpcascade_frontalface....
Python
zaydzuhri_stack_edu_python
function testWebobRequest self begin import webob set request = call blank string /a/b/c assert equal url string http://localhost/a/b/c end function
def testWebobRequest(self): import webob request = webob.Request.blank("/a/b/c") self.assertEqual(request.url, "http://localhost/a/b/c")
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import sys import os import time import json import StringIO import socket import urllib import urllib2 import urlparse import httplib import optparse from urlredirects import * from utils import * from datetime import datetime import inspect from threading import Thread import threading im...
#!/usr/bin/env python import sys import os import time import json import StringIO import socket import urllib import urllib2 import urlparse import httplib import optparse from urlredirects import * from utils import * from datetime import datetime import inspect from threading import Thread import threading import ...
Python
zaydzuhri_stack_edu_python
comment C:\Users\teamw\OneDrive\Documents\william\Atom comment com is /dev/cu.usbmodem14201 on mac or COM3 on windows import os import serial import sys function testserial ardu_port baud begin try begin set ser = call Serial ardu_port baud return string works end except any begin print string Error: Could not connect....
#C:\Users\teamw\OneDrive\Documents\william\Atom #com is /dev/cu.usbmodem14201 on mac or COM3 on windows import os import serial import sys def testserial(ardu_port, baud): try: ser = serial.Serial(ardu_port, baud) return "works" except: print("Error: Could not connect. Connect ...
Python
zaydzuhri_stack_edu_python
function consolidate self begin info string Consolidating statistics set all_df = list for triple in call all_par_triples begin set path = _output_dir_path / call result_filename if not exists path begin debug string Statistic file {} does not exist. The corresponding triple [{}] most likely hasn't finished or failed ...
def consolidate(self) -> None: logging.info("Consolidating statistics") all_df = [] for triple in self.all_par_triples(): path = self._output_dir_path / triple.result_filename() if not path.exists(): logging.debug( "Statistic file {} do...
Python
nomic_cornstack_python_v1
import math set A = integer input set c = call radians A set x = sin c set c1 = round x 1 set k = absolute c1 if k < 1 begin print c1 end else begin print round c1 end
import math A=int(input()) c=math.radians(A) x=math.sin(c) c1=(round(x,1)) k=abs(c1) if k<1 : print(c1) else: print(round(c1))
Python
zaydzuhri_stack_edu_python
comment 猫眼电影 import scrapy import json class MaoYanSpider extends Spider begin set name = string movies_maoyan_spider set allowed_domains = list string piaofang.maoyan.com set start_urls = list string https://box.maoyan.com/promovie/api/box/second.json function parse self response begin set data = loads text encoding=s...
# 猫眼电影 import scrapy import json class MaoYanSpider(scrapy.Spider): name = 'movies_maoyan_spider' allowed_domains = ['piaofang.maoyan.com'] start_urls = ['https://box.maoyan.com/promovie/api/box/second.json'] def parse(self, response): data = json.loads(response.text, encoding='utf-8') ...
Python
zaydzuhri_stack_edu_python
comment На улице встретились N друзей. Каждый пожал руку всем остальным друзьям comment (по одному разу). Сколько рукопожатий было? comment Примечание. Решите задачу при помощи построения графа. set n = integer input string Enter vertex number: set graph = list comprehension list 0 * n for _ in range n set sum_edge = 0...
# На улице встретились N друзей. Каждый пожал руку всем остальным друзьям # (по одному разу). Сколько рукопожатий было? # Примечание. Решите задачу при помощи построения графа. n = int(input("Enter vertex number: ")) graph = [[0] * n for _ in range(n)] sum_edge = 0 for r in range(n): for c in range(n): ...
Python
zaydzuhri_stack_edu_python
function full_sky_car_template ncomp res begin if ncomp == 3 begin set pre = tuple 3 end else begin set pre = tuple end set res = res * pi / 180 * 60 set temp = call so_map set tuple shape wcs = call fullsky_geometry res=res dims=pre set data = zeros shape wcs=wcs dtype=none set pixel = string CAR set nside = none set...
def full_sky_car_template(ncomp, res): if ncomp == 3: pre = (3,) else: pre = () res = res * np.pi / (180 * 60) temp = so_map() shape, wcs = enmap.fullsky_geometry(res=res, dims=pre) temp.data = enmap.zeros(shape, wcs=wcs, dtype=None) temp.pixel = "CAR" temp.nside = None...
Python
nomic_cornstack_python_v1
import requests import pprint import time comment OpenWeatherMap API set params = dict string q string Frederick,US ; string appid string 4ce082e5c4e81ec8283fde2f65796473 ; string units string imperial set response = get requests string http://api.openweathermap.org/data/2.5/weather params=params set weather_data = jso...
import requests import pprint import time # OpenWeatherMap API params = { 'q': 'Frederick,US', 'appid': '4ce082e5c4e81ec8283fde2f65796473', 'units' : 'imperial', } response = requests.get( 'http://api.openweathermap.org/data/2.5/weather', params=params) weather_data = response.json() # pprint.pprint(weather_data...
Python
zaydzuhri_stack_edu_python
function reverse_other t begin function reverse_branches tree begin set branches = branches for i in range length branches // 2 begin set tuple label label = tuple label label end end function set level = 0 set current_layer = list t while current_layer begin if level % 2 == 0 begin for tree in current_layer begin call...
def reverse_other(t): def reverse_branches(tree): branches = tree.branches for i in range(len(branches) // 2): branches[i].label, branches[-1-i].label = branches[-1-i].label, branches[i].label level = 0 current_layer = [t] while current_layer: if level % 2 == 0: ...
Python
nomic_cornstack_python_v1
comment noqa function __init__ self mask name=ROOT AF=0 **kwargs begin if name not in NODE_NAMES begin raise call ValueError string Wrong Fast SSC Node type end call __init__ name keyword kwargs set mask = mask set AF = AF set node_type = call get_node_type supported_nodes=supported_nodes mask=mask AF=AF set is_compute...
def __init__(self, mask: np.array, name: str = ROOT, AF: int = 0, **kwargs): # noqa if name not in self.__class__.NODE_NAMES: raise ValueError('Wrong Fast SSC Node type') super().__init__(name, **kwargs) self.mask = mask self.AF = AF self.node_type = get_node_type(...
Python
nomic_cornstack_python_v1
function x_offset self begin set width = call width if halign == string right begin return 1 - width end if halign == string center begin return - width / 2 end if halign == string left begin return 0 end raise call ValueError string Unrecognized horizontal alignment: %s % halign end function
def x_offset(self): width = self.target.width() if self.halign == "right": return 1 - width if self.halign == "center": return -(width/2) if self.halign == "left": return 0 raise ValueError("Unrecognized horizontal alignment: %s"%self.halign)
Python
nomic_cornstack_python_v1
import pandas , collections set df = read csv string data.csv set langC = counter list comprehension update langC split counts string ; for counts in df at string LanguagesWorkedWith set tuple langs rep_count = tuple list list list comprehension list append langs data at 0 append rep_count data at 1 for data in call ...
import pandas,collections df = pandas.read_csv('data.csv') langC = collections.Counter() [langC.update(counts.split(';')) for counts in df['LanguagesWorkedWith']] langs,rep_count =[],[] [[langs.append(data[0]), rep_count.append(data[1])] for data in langC.most_common(len(langC))] print("The information such as languag...
Python
zaydzuhri_stack_edu_python
import Tkinter as tk class Example extends Frame begin function __init__ self parent begin call __init__ self parent end function end class
import Tkinter as tk class Example(tk.Frame): def __init__(self, parent): tk.Frame.__init__(self, parent)
Python
zaydzuhri_stack_edu_python
function _fit self X y sample_weight=none begin from scipy.sparse import issparse comment Validate or convert input data if sample_weight is not none begin set sample_weight = call check_array sample_weight ensure_2d=false end if call issparse X begin comment Pre-sort indices to avoid that each individual tree of the c...
def _fit(self, X, y, sample_weight=None): from scipy.sparse import issparse # Validate or convert input data if sample_weight is not None: sample_weight = check_array(sample_weight, ensure_2d=False) if issparse(X): # Pre-sort indices to avoid that each individual...
Python
nomic_cornstack_python_v1
function bulk_anisotropy self scheme=string Voigt begin set tuple Ua Ua_sigma = call uAniso call bulk_cij scheme=scheme comment We don't use the error (Ua_sigma) comment as we don't know the error on the comment single crystal elasticity. return Ua end function
def bulk_anisotropy(self, scheme='Voigt'): Ua, Ua_sigma = CijUtil.uAniso(self.bulk_cij(scheme=scheme)) # We don't use the error (Ua_sigma) # as we don't know the error on the # si...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plot import cmath as cm function dft x N begin set c = 0 set r = list for k in range N - 1 begin set j = square root - 1 for n in range 0 N - 1 1 begin set c = c + x at n * exp - j * 2 * pi * k * n / N end append r c set c = 0 end return r end function set k = input strin...
import numpy as np import matplotlib.pyplot as plot import cmath as cm def dft(x,N): c=0 r=[ ] for k in range(N-1): j=cm.sqrt(-1) for n in range (0,N-1,1): c=c+(x[n]*np.exp((-(j*2*np.pi*k*n/N)))) r.append(c) c=0 return r k=input("enter the shift value") x1=[3,4,5,7,8,9,2,1] N1=len(x1) x2=[ ] for n in ran...
Python
zaydzuhri_stack_edu_python
function post self request begin try begin set json_data = loads body end except ValueError begin return call Response dict string detail string No valid json body status=HTTP_400_BAD_REQUEST end set serializer = call RelayRegisterChallengeSerializer data=json_data if not call is_valid begin return call Response errors...
def post(self, request): try: json_data = json.loads(request.body) except ValueError: return Response({ 'detail': 'No valid json body', }, status=status.HTTP_400_BAD_REQUEST) serializer = RelayRegisterChallengeSerializer(data=json_data) ...
Python
nomic_cornstack_python_v1
import os import torchvision.datasets import torchvision.transforms as transforms import research_project_name.data.utils set available_datasets = list string mnist string celeba string cifar10 string svhn function load_dataset dataroot dataset_name image_size num_channels **kwargs begin if dataset_name not in availabl...
import os import torchvision.datasets import torchvision.transforms as transforms import research_project_name.data.utils available_datasets = ["mnist", "celeba", "cifar10", "svhn"] def load_dataset(dataroot, dataset_name, image_size, num_channels, **kwargs): if dataset_name not in available_datasets: ra...
Python
zaydzuhri_stack_edu_python
function determine_aa_change self begin comment k = string that is isoform_id, v = Isoform instance for tuple k v in call iteritems begin set obj_tt = call create_transcript_instances k comment METHOD 1: get the original codon & mutated codon comment orig_codon = obj_tt.retrieve_containing_codon( self.snv_start, self.s...
def determine_aa_change( self ): for k,v in self.obj_mi.hash_isoforms.iteritems(): #k = string that is isoform_id, v = Isoform instance obj_tt = self.create_transcript_instances( k ) #METHOD 1: get the original codon & mutated codon # orig_codon = obj_tt.retrieve_cont...
Python
nomic_cornstack_python_v1
comment Definition der Klasse Lieferwagen class Lieferwagen extends PKW LKW begin function __init__ self bez ge ins la begin call __init__ self bez ge ins call __init__ self bez ge ins end function function __str__ self begin return call __str__ self + string + call __str__ self end function end class
# Definition der Klasse Lieferwagen class Lieferwagen(PKW, LKW): def __init__(self, bez, ge, ins, la): PKW.__init__(self, bez, ge, ins) LKW.__init__(self, bez, ge, ins) def __str__(self): return PKW.__str__(self) + "\n" \ + LKW.__str__(self)
Python
zaydzuhri_stack_edu_python
function getAction self gameState begin comment Collect legal moves and successor states set legalMoves = call getLegalActions comment Choose one of the best actions set scores = list comprehension call evaluationFunction gameState action for action in legalMoves set bestScore = max scores set bestIndices = list compre...
def getAction(self, gameState): # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len...
Python
nomic_cornstack_python_v1
comment Assignment 5 - Introduction to Amazon Web Services (and Web Interface) comment Name : Shweta Pathak comment UTA ID : 1001154572 comment Net Id : ssp4572 comment import statements import boto import csv import time import sys import urllib2 import boto.dynamodb from boto.s3.key import Key from boto.s3.connection...
# Assignment 5 - Introduction to Amazon Web Services (and Web Interface) # Name : Shweta Pathak # UTA ID : 1001154572 # Net Id : ssp4572 # import statements import boto import csv import time import sys import urllib2 import boto.dynamodb from boto.s3.key import Key from boto.s3.connection import S3Connection from b...
Python
zaydzuhri_stack_edu_python
string test class Rover_direction library used in the MarsRover Challenge program. It used to show positive testing of module In this instance we make use of unittest from Python 3.9. comment We import the python math module to make use of Pi import math as mt comment Import python unittest for testing import unittest ...
""" test class Rover_direction library used in the MarsRover Challenge program. It used to show positive testing of module In this instance we make use of unittest from Python 3.9. """ # We import the python math module to make use of Pi import math as mt # Import python unittest for testing import unittest # I...
Python
zaydzuhri_stack_edu_python
import random set x = list string l string c string w set a = list set b = list set c = list append a x at random integer 0 2 remove x a at 0 append b x at random integer 0 1 remove x b at 0 append c x at 0 print string Kids born in east francee print a print string kids born in sweden print b print string kids born...
import random x = ['l','c','w'] a = [] b = [] c = [] a.append(x[random.randint(0,2)]) x.remove(a[0]) b.append(x[random.randint(0,1)]) x.remove(b[0]) c.append(x[0]) print("Kids born in east francee") print(a) print("kids born in sweden") print(b) print("kids born in russia") print(c)
Python
zaydzuhri_stack_edu_python
function to_dict decoder dict_class=dict begin return dictionary generator expression tuple name get attribute decoder name for name in directory decoder if not starts with name string _ and name != string namespaces end function
def to_dict(decoder, dict_class=dict): return dict( (name, getattr(decoder, name)) for name in dir(decoder) if not name.startswith("_") and name != "namespaces" )
Python
nomic_cornstack_python_v1
function sum_array_elements arr begin set result = 0 for i in range length arr begin set result = result + arr at i end return result end function set arr = list 1 2 3 4 print call sum_array_elements arr
def sum_array_elements(arr): result = 0 for i in range(len(arr)): result += arr[i] return result arr = [1, 2, 3, 4] print(sum_array_elements(arr))
Python
jtatman_500k
comment Edgar Moises Hernandez Gonzalez (Moyete) comment 26/09/18-12/01/19 comment Pruebas4 Matrices con Numpy import numpy as np set A = zeros tuple 5 2 set B = ones tuple 3 3 set C = zeros like B set D = ones like A set E = array list 1 2 3 print string A = print A print string B = print B print string C = print C pr...
#Edgar Moises Hernandez Gonzalez (Moyete) #26/09/18-12/01/19 #Pruebas4 Matrices con Numpy import numpy as np A=np.zeros((5,2)) B=np.ones((3,3)) C=np.zeros_like(B) D=np.ones_like(A) E=np.array([1,2,3]) print("A =") print(A) print("B =") print(B) print("C =") print(C) print("D =") print(D) print("E =") print(E) X=np...
Python
zaydzuhri_stack_edu_python
comment importing the file that defines the movie class and the file that generates the html import media import fave_trailers comment Initializing movie objects comment baahubali movie object set baahubali = call Movie string Baahubali string The story of Mahishmati kingdom string https://upload.wikimedia.org/wikipedi...
#importing the file that defines the movie class and the file that generates the html import media import fave_trailers #Initializing movie objects #baahubali movie object baahubali=media.Movie("Baahubali", "The story of Mahishmati kingdom", "https://upload.wikimedia.org...
Python
zaydzuhri_stack_edu_python
function delete_template self template_id begin set endpoint = string %s/%s % tuple STS_TEMPLATES template_id set response = call delete_json endpoint set success = status_code == 204 return response end function
def delete_template(self, template_id): endpoint = "%s/%s" % (STS_TEMPLATES, template_id) response = self.client.delete_json(endpoint) response.success = response.status_code == 204 return response
Python
nomic_cornstack_python_v1
function runLinAdvec begin comment Courant number set c = 0.4 comment just run and print, for two different Courant numbers call main 50 50 c displayResults=true call main 400 400 c displayResults=true print string comment run order of convergence tests call runErrorTests c 50 300 stepNx=50 display=true comment run tim...
def runLinAdvec(): # Courant number c = 0.4 #just run and print, for two different Courant numbers main(50, 50, c, displayResults = True) main(400, 400, c, displayResults = True) print("\n") # run order of convergence tests runErrorTests(c, 50, 300, stepNx=50, display=True) # run...
Python
nomic_cornstack_python_v1
comment • Задано ціле число N, вивести перші N чисел фібоначі. set n = integer input string please enter n set n1 = 0 set n2 = 1 set count = 0 if n <= 0 begin print string Please enter n again end else if n == 1 begin print string Fib seq is n string : print n1 end else begin print string Fib seq: while count < n begin...
# • Задано ціле число N, вивести перші N чисел фібоначі. n = int(input("please enter n ")) n1 = 0 n2 = 1 count = 0 if n <= 0: print("Please enter n again") elif n == 1: print("Fib seq is",n,":") print(n1) else: print("Fib seq:") while count < n: print(n1) m = n1 + n2 n1 = n2 ...
Python
zaydzuhri_stack_edu_python
function interpolate_to_netcdf self in_lon in_lat out_path date_unit=string seconds since 1970-01-01T00:00 interp_type=string spline begin string Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create separate directories for each variable if they are not already available. ...
def interpolate_to_netcdf(self, in_lon, in_lat, out_path, date_unit="seconds since 1970-01-01T00:00", interp_type="spline"): """ Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create separate directories for each variab...
Python
jtatman_500k
function stack_state self begin return dyn_stack_current_state end function
def stack_state(self): return self.dyn_stack_current_state
Python
nomic_cornstack_python_v1
function __analyzeHtml self data latest_date begin set result_list = list set rows = find data id=string FundHoldSharesTable set idx = 1 set summary_unit = call SummaryPerSeason for row in find all rows string tr recursive=false begin set td = find row string td class_=string tdr if td != none begin set propertyValue ...
def __analyzeHtml(self, data, latest_date): result_list = [] rows = data.find(id="FundHoldSharesTable") idx = 1 summary_unit = SummaryPerSeason() for row in rows.find_all('tr',recursive=False): td = row.find('td', class_='tdr') if td!=None: ...
Python
nomic_cornstack_python_v1
from collections import defaultdict class Solution begin function wordBreak self s wordDict begin set dictn = default dictionary list for word in wordDict begin append dictn at word at 0 length word end function search start begin if start >= length s begin return true end for word in dictn at s at start begin if searc...
from collections import defaultdict class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: dictn = defaultdict(list) for word in wordDict: dictn[word[0]].append(len(word)) def search(start): if start >= len(s): return True ...
Python
zaydzuhri_stack_edu_python
import math function is_prime n begin for i in range 2 integer square root n + 1 begin if n % i == 0 begin return false end end return true end function print call is_prime n
import math def is_prime(n): for i in range(2, int(math.sqrt(n))+1): if n % i == 0: return False return True print(is_prime(n))
Python
flytech_python_25k
string 给定一个二叉树,找出其最小深度 comment Definition for a binary tree node. comment class TreeNode(object): comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None class Solution extends object begin function minDepth self root begin string :type root: TreeNode :rtype: int return ca...
""" 给定一个二叉树,找出其最小深度 """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def minDepth(self, root): """ :type root: TreeNode :rtype: int ""...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment ~/.python27rc comment This is a startup script for python
#!/usr/bin/env python # ~/.python27rc # This is a startup script for python
Python
zaydzuhri_stack_edu_python
from typing import List , Dict from src.model.tweet import Tweet class RawTweetSetter begin string An abstract class representing an object that stores tweets in a datastore function store_tweet self tweet begin raise call NotImplementedError string Subclasses should implement this end function function store_tweets se...
from typing import List, Dict from src.model.tweet import Tweet class RawTweetSetter: """ An abstract class representing an object that stores tweets in a datastore """ def store_tweet(self, tweet: Tweet): raise NotImplementedError("Subclasses should implement this") def store_tweets(s...
Python
zaydzuhri_stack_edu_python
from kivy.animation import Animation from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import NumericProperty , ReferenceListProperty , ObjectProperty , ListProperty from kivy.vector import Vector from kivy.clock import Clock from random import randint class Fly_b extends Widget begin fun...
from kivy.animation import Animation from kivy.app import App from kivy.uix.widget import Widget from kivy.properties import ( NumericProperty, ReferenceListProperty, ObjectProperty, ListProperty ) from kivy.vector import Vector from kivy.clock import Clock from random import randint class Fly_b(Widget): def _...
Python
zaydzuhri_stack_edu_python
string Interface definition for a database query from typing import Any , Protocol class DatabaseQuery extends Protocol begin string Interface to abstract away from sqlalchemy query function count self begin string Get number of matching items end function function first self begin string Get first matching item end fu...
""" Interface definition for a database query """ from typing import Any, Protocol class DatabaseQuery(Protocol): """ Interface to abstract away from sqlalchemy query """ def count(self) -> int: """Get number of matching items""" def first(self) -> Any: """Get first matching item"...
Python
zaydzuhri_stack_edu_python