code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function get_raw_data url begin set req = get requests url stream=true set decode_content = true return raw end function
def get_raw_data(url): req = requests.get(url, stream=True) req.raw.decode_content = True return req.raw
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri Nov 25 09:05 2016 Updated on Fri Apr 07 23:07 2017 @author: timotheeaupetit import time class City extends object begin function __init__ self json_data begin comment self.id = json_data['city']['id'] # Not used set name = json_data at st...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 25 09:05 2016 Updated on Fri Apr 07 23:07 2017 @author: timotheeaupetit """ import time class City(object): def __init__(self, json_data): # self.id = json_data['city']['id'] # Not used self.name = json_data['city']['name']...
Python
zaydzuhri_stack_edu_python
comment 환전 서비스 comment 원화(₩)에서 달러($)로 변환하는 함수 function krw_to_usd krw begin return krw / 1000 end function comment 달러($)에서 엔화(¥)로 변환하는 함수 function usd_to_jpy usd begin return usd * 1000 / 8 end function comment 원화(₩)으로 각각 얼마인가요? set prices = list 34000 13000 5000 21000 1000 2000 8000 3000 print string 한국 화폐: + string p...
# 환전 서비스 # 원화(₩)에서 달러($)로 변환하는 함수 def krw_to_usd(krw): return krw / 1000 # 달러($)에서 엔화(¥)로 변환하는 함수 def usd_to_jpy(usd): return (usd * 1000) / 8 # 원화(₩)으로 각각 얼마인가요? prices = [34000, 13000, 5000, 21000, 1000, 2000, 8000, 3000] print("한국 화폐: " + str(prices)) i = 0 while i < len(prices): prices[i] = krw_t...
Python
zaydzuhri_stack_edu_python
while true begin try begin set altura = integer input string Ingresar altura del triangulo: set base = integer input string Ingresar base del triangulo: if not altura > 0 and base > 0 begin print string Los parametros ingresados deben ser mayor a 0 end else begin break end end except Exception as e begin print string E...
while True: try: altura = int(input('Ingresar altura del triangulo: ')) base = int(input('Ingresar base del triangulo: ')) if not (altura > 0 and base > 0): print(f'Los parametros ingresados deben ser mayor a 0') else: break except Exception as e: ...
Python
zaydzuhri_stack_edu_python
string Hocam isteğiniz üzere fonksiyon çağırma adlarını dosya ismi . fonksiyon ismi olarak editledim from listeleme import * from ara import * from ekleme import * from yeniveritabani import * from kitapal import * call sira while true begin print string Arama Yap(A) - Kitap Ekle (K) Yeni Veri Tabanı Oluşturma (Y) Başk...
""" Hocam isteğiniz üzere fonksiyon çağırma adlarını dosya ismi . fonksiyon ismi olarak editledim """ from listeleme import * from ara import * from ekleme import * from yeniveritabani import * from kitapal import * sira() while True: print(" Arama Yap(A) - Kitap Ekle (K) Yeni Ver...
Python
zaydzuhri_stack_edu_python
import re set state = 0 set match_fields = list set nearby_tickets = list with open string input_day16.txt as f begin for line in call splitlines begin if line == string begin continue end if state == 0 begin set match = match string ([a-z ]+): ([0-9]+-[0-9]+) or ([0-9]+-[0-9]+) line if match != none begin append ma...
import re state = 0 match_fields = [] nearby_tickets = [] with open("input_day16.txt") as f: for line in f.read().splitlines(): if line == "": continue if state == 0: match = re.match("([a-z ]+): ([0-9]+-[0-9]+) or ([0-9]+-[0-9]+)", line) if match != None: ...
Python
zaydzuhri_stack_edu_python
function trip_duration_stats df begin print string Calculating Trip Duration... set start_time = time set df at string Trip Duration = df at string End hour - df at string Start hour comment display total travel time print format string The total travel time : {} sum comment display mean travel time print format string...
def trip_duration_stats(df): print('\nCalculating Trip Duration...\n') start_time = time.time() df['Trip Duration'] = df['End hour'] - df['Start hour'] # display total travel time print('The total travel time : {}'.format(df['Trip Duration'].sum())) # display mean travel time print('The...
Python
nomic_cornstack_python_v1
function divide_protected num den vsub_zero=0 begin set pro_num = select np tuple den != 0 tuple num default=vsub_zero set pro_den = select np tuple den != 0 tuple den default=1 return pro_num / pro_den end function
def divide_protected(num, den, vsub_zero=0): pro_num = np.select((den!=0,), (num,), default=vsub_zero) pro_den = np.select((den!=0,), (den,), default=1) return pro_num / pro_den
Python
nomic_cornstack_python_v1
function run_inference_on_image image begin if not exists gfile image begin call fatal string File does not exist %s image end set image_data = read call FastGFile image string rb comment Creates graph from saved GraphDef. comment create_graph() with call Session as sess begin comment Some useful tensors: comment 'soft...
def run_inference_on_image(image): if not tf.gfile.Exists(image): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() # Creates graph from saved GraphDef. #create_graph() with tf.Session() as sess: # Some useful tensors: # 'softmax:0': A tensor c...
Python
nomic_cornstack_python_v1
function get_moving_average close span begin set i = call SMAIndicator close window=span return call sma_indicator end function
def get_moving_average(close, span): i = SMAIndicator(close, window=span) return i.sma_indicator()
Python
nomic_cornstack_python_v1
function hook_buy_card self game player card begin if call isVictory begin call output string Gaining Gold from Hoard call add_card remove game at string Gold end end function
def hook_buy_card(self, game, player, card): if card.isVictory(): player.output("Gaining Gold from Hoard") player.add_card(game["Gold"].remove())
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment 関数デコレーターのサンプル
# coding: utf-8 # # 関数デコレーターのサンプル
Python
zaydzuhri_stack_edu_python
import logging set logger = call getLogger class clrs begin set OKBLUE = string  set RED = string  set CYAN = string  set GREEN = string  set YELLOW = string  set END = string  set WHITE = string  end class class Printer begin function color_message self color msg insert begin info for...
import logging logger = logging.getLogger() class clrs: OKBLUE = '\033[94m' RED = '\033[31m' CYAN = '\033[36m' GREEN = '\033[92m' YELLOW = '\033[93m' END = '\033[0m' WHITE = '\033[97m' class Printer: def color_message(self, color, msg, insert): logger.info("{}[{}] {}{}".fo...
Python
zaydzuhri_stack_edu_python
function unique_repos_from_snyk_projects snyk_gh_projects begin set snyk_gh_repos = list for project in snyk_gh_projects begin if project at string repo_full_name not in set comprehension s at string full_name for s in snyk_gh_repos begin append snyk_gh_repos dict string full_name project at string repo_full_name ; st...
def unique_repos_from_snyk_projects(snyk_gh_projects): snyk_gh_repos = [] for project in snyk_gh_projects: if project["repo_full_name"] not in {s["full_name"] for s in snyk_gh_repos}: snyk_gh_repos.append( { "full_name": project["repo_full_name"], ...
Python
nomic_cornstack_python_v1
function prime_factors n begin set prime_factors = list while n % 2 == 0 begin append prime_factors 2 set n = n / 2 end for i in range 3 integer square root n + 1 2 begin while n % i == 0 begin append prime_factors integer i set n = n / i end end if n > 2 begin append prime_factors integer n end return prime_factors e...
def prime_factors(n): prime_factors = [] while n % 2 == 0: prime_factors.append(2) n = n / 2 for i in range(3, int(math.sqrt(n)) + 1, 2): while n % i == 0: prime_factors.append(int(i)) n = n / i if n > 2: prime_factors.append(int(n)) return...
Python
jtatman_500k
from functions.input_number import inputNumber from functions.numbers_generator import randomNumberGenerator , humanFriendly from functions.numbers_comparation import numbersComparation function humanPlay humanNumber machineNumber begin string Compare the typed number with the random number. Define when the game is ove...
from functions.input_number import inputNumber from functions.numbers_generator import randomNumberGenerator, humanFriendly from functions.numbers_comparation import numbersComparation def humanPlay(humanNumber, machineNumber): """ Compare the typed number with the random number. Define when the game is o...
Python
zaydzuhri_stack_edu_python
function address *args **kwargs begin try begin comment Special cases: this allows us to get feedback on processes that are already done if Monitor in args begin set mon = kwargs at string monitor call link lambda dead_proc -> call mon func exception end else if Link in args begin set me = call getcurrent call link_exc...
def address(*args, **kwargs): try: # Special cases: this allows us to get feedback on processes that are already done if Monitor in args: mon = kwargs['monitor'] proc.link(lambda dead_proc: mon(func, dead_proc.exception)) elif Link in args: ...
Python
nomic_cornstack_python_v1
import random function generate_sequence begin set sequence = string for _ in range 20 begin set char = character random integer 97 122 set sequence = sequence + char end return sequence end function set output = call generate_sequence print output
import random def generate_sequence(): sequence = "" for _ in range(20): char = chr(random.randint(97, 122)) sequence += char return sequence output = generate_sequence() print(output)
Python
flytech_python_25k
function webhook_for_whatsapp_messages begin global last_whatsapp_requests if method == string POST begin set data = call get_json force=true append last_whatsapp_requests data if data at string to at string number == WHATSAPP_SANDBOX_NUMBER begin print string THIS IS MO MESSAGE set user_number = data at string from at...
def webhook_for_whatsapp_messages(): global last_whatsapp_requests if request.method == 'POST': data = request.get_json(force=True) last_whatsapp_requests.append(data) if data['to']['number'] == WHATSAPP_SANDBOX_NUMBER: print("THIS IS MO MESSAGE") user_number = da...
Python
nomic_cornstack_python_v1
function create_item self matrix begin set matrix = matrix set exist = list set item = list for opu in item begin call create_position sprite_x sprite_y append item call fill_item_list opu sprite_x sprite_y append exist item set exist = item end set obj = item end function
def create_item(self, matrix): self.matrix = matrix exist = [] item = [] for self.opu in self.item: self.create_position(self.sprite_x, self.sprite_y) item.append(self.fill_item_list(self.opu, self.sprite_x, self.sprite_y)) exist.append(item) ...
Python
nomic_cornstack_python_v1
function add_relations self relations begin if not relations begin return none end set labels_str = rel_type set prop_str = join string , list comprehension string rel.%s = relation.%s % tuple k k for k in data set query = string UNWIND $relations AS relation MATCH (e1 {id: relation.source_id}), (e2 {id: relation.targe...
def add_relations(self, relations: List[Relation]): if not relations: return None labels_str = relations[0].rel_type prop_str = ",\n".join( ["rel.%s = relation.%s" % (k, k) for k in relations[0].data] ) query = """ UNWIND $relations AS relation...
Python
nomic_cornstack_python_v1
from datetime import date function categoria idade begin if idade <= 9 begin return 0 end else if idade <= 14 begin return 1 end else if idade <= 19 begin return 2 end else if idade <= 20 begin return 3 end else begin return 4 end end function set categorias = list string Mirim string Infantil string Junior string Seni...
from datetime import date def categoria (idade): if idade <= 9: return 0 elif idade <= 14: return 1 elif idade <= 19: return 2 elif idade <= 20: return 3 else: return 4 categorias = ["Mirim", "Infantil", "Junior", "Senior", "Master"] #anoNas...
Python
zaydzuhri_stack_edu_python
function piecewise_linear x xmin xmax begin set m = 1.0 / xmax - xmin set b = 1.0 - m * xmax set x = where x >= xmin ? x <= xmax add tf call multiply x m b x set x = where x > 1.0 1.0 x set x = where x < 0.0 0.0 x return x end function
def piecewise_linear(x, xmin, xmax): m = 1./(xmax-xmin) b = 1. - (m * xmax) x = tf.where((x >= xmin) & (x <= xmax), tf.add(tf.multiply(x,m),b),x) x = tf.where(x > 1., 1.,x) x = tf.where(x < 0., 0.,x) return x
Python
nomic_cornstack_python_v1
if __name__ == string __main__ begin set N = integer input set List = list for i in range N begin set _ = split input set cmd = _ at 0 set arg = _ at slice 1 : : if cmd == string print begin print List end else begin eval string List. + cmd + string ( + join string , arg + string ) end end end
if __name__ == '__main__': N = int(input()) List = [] for i in range(N): _ = input().split() cmd = _[0] arg = _[1:] if cmd == "print": print(List) else: eval("List." + cmd + "(" + (",".join(arg)) + ")")
Python
zaydzuhri_stack_edu_python
function main inputSTR begin string 這支程式的主要函式(「函式」就是「功能」的意思!) print format string Hello {}, {} inputSTR string 你好 comment 用 substring 的方式取得字串中的某一部份 set inputSubSTR = inputSTR at slice 0 : 4 : print inputSubSTR comment 用 split() 函式,透過空格把字串切割成列表 set inputSubLIST = split inputSTR string print format string 姓名: {} inputSu...
def main(inputSTR): ''' 這支程式的主要函式(「函式」就是「功能」的意思!) ''' print("Hello {}, {}".format(inputSTR, "你好")) inputSubSTR = inputSTR[0:4] #用 substring 的方式取得字串中的某一部份 print(inputSubSTR) inputSubLIST = inputSTR.split(" ") #用 split() 函式,透過空格把字串切割成列表 print("姓名: {}".format(inputSubLIST[0])) ...
Python
zaydzuhri_stack_edu_python
string Created on 27 janv. 2020 @author: gresset6u from timeit import Timer from Fibo import * comment parametres implicites set t = call Timer string fibo(10) string from __main__ import fibo comment parametres explites set trec = call Timer stmt=string fiborec(10) setup=string from __main__ import fiborec print strin...
''' Created on 27 janv. 2020 @author: gresset6u ''' from timeit import Timer from Fibo import * #parametres implicites t = Timer("fibo(10)","from __main__ import fibo") #parametres explites trec = Timer(stmt="fiborec(10)",setup="from __main__ import fiborec") print ("10000 iterations iteratif : ", t.t...
Python
zaydzuhri_stack_edu_python
comment 字符串 str() ord() chr() format() print format string {0:0>45d} 1 set xz = list for i in range 0 12 begin append xz character 9800 + i end print xz set xz_code = list comprehension ordinal i for i in xz print xz_code set sxh = list for j in range 100 1000 begin set m = string j set s = 0 for i in m begin set s =...
# 字符串 str() ord() chr() format() print("{0:0>45d}".format(1)) xz = [] for i in range(0,12): xz.append(chr(9800+i)) print(xz) xz_code = [ord(i) for i in xz] print(xz_code) sxh = [] for j in range(100, 1000): m = str(j) s = 0 for i in m: s += eval(i)**3 if s == j: sxh.append(j) print(s...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf -8-*- import sys function reverse_iterative sequence left right begin string Funkcja iteratywnie odwraca sekwencję sequence od liczby o indeksie left do right wlacznie >>> reverse_iterative([1,2,3,4,5,6], 1, 4) [1, 5, 4, 3, 2, 6] >>> reverse_iterative([10,9,8,7,6,5,...
#!/usr/bin/env python3 # -*- coding: utf -8-*- import sys def reverse_iterative(sequence, left, right): """ Funkcja iteratywnie odwraca sekwencję sequence od liczby o indeksie left do right wlacznie >>> reverse_iterative([1,2,3,4,5,6], 1, 4) [1, 5, 4, 3, 2, 6] >>> reverse_iterative([10,9,8,7,6,5,4,3,2,...
Python
zaydzuhri_stack_edu_python
import Adafruit_DHT import time import mysql.connector set DHT_SENSOR = DHT11 set DHT_PIN = 4 set db_connection = call connect host=string localhost user=string acv passwd=string P@ssw0rd database=string sensors print db_connection set prev_temp = none set prev_humi = none function insertRecord temp hum begin set db_cu...
import Adafruit_DHT import time import mysql.connector DHT_SENSOR = Adafruit_DHT.DHT11 DHT_PIN = 4 db_connection = mysql.connector.connect( host="localhost", user="acv", passwd="P@ssw0rd", database="sensors" ) print(db_connection) prev_temp = None prev_humi = None def insertRecord(temp, hum): db_cursor ...
Python
zaydzuhri_stack_edu_python
function AddDescriptionArg parser begin call add_argument string --description help=string The description of the workflow to deploy. end function
def AddDescriptionArg(parser): parser.add_argument( '--description', help='The description of the workflow to deploy.')
Python
nomic_cornstack_python_v1
from __future__ import division class Evaluator begin string Abstract parser evaluator class. Subclasses perform various operations for some evaluation program (e.g. evalb, sparseval, etc.). function evaluate self test gold begin string Return the text from running this evaluator, comparing test trees against gold tree...
from __future__ import division class Evaluator: """Abstract parser evaluator class. Subclasses perform various operations for some evaluation program (e.g. evalb, sparseval, etc.).""" def evaluate(self, test, gold): """Return the text from running this evaluator, comparing test trees ...
Python
zaydzuhri_stack_edu_python
comment 고정점 찾기 comment 인덱스 값이랑 value랑 같은 위치 찾기 최대 1개의 고정점이 있음 comment 고정점이 없다면 -1를 출력하기. comment 시간복잡도가 O(logN)이여야 하고 comment 1 <= N <= 1,000,000 import sys set N = integer input set arr = list map int split read line stdin set start = 0 set last = N - 1 comment 이문제는 이분탐색으로 돌다가 만약 mid가 arr[mid]보다 크면 오른쪽으로 작은면 왼쪽으로 탐색하는...
# 고정점 찾기 # 인덱스 값이랑 value랑 같은 위치 찾기 최대 1개의 고정점이 있음 # 고정점이 없다면 -1를 출력하기. # 시간복잡도가 O(logN)이여야 하고 # 1 <= N <= 1,000,000 import sys N=int(input()) arr=list(map(int,sys.stdin.readline().split())) start=0 last=N-1 while True:# 이문제는 이분탐색으로 돌다가 만약 mid가 arr[mid]보다 크면 오른쪽으로 작은면 왼쪽으로 탐색하는 걸 만들기만하면 됨. mid=(start+last)//2 ...
Python
zaydzuhri_stack_edu_python
function start_pane pane begin set frame = call Window open pane set loop = call MainLoop frame PALETTE unhandled_input=on_key_press run end function
def start_pane(pane): frame = Window() frame.open(pane) loop = urwid.MainLoop(frame, Window.PALETTE, unhandled_input=frame.on_key_press) loop.run()
Python
nomic_cornstack_python_v1
function __init__ self M1 qmin=0.1 qmax=1 Pmin=0.5 Pmax=365 N=100000.0 logP=true eccfn=none begin set M1s = ones N * M1 set M2s = random size=N * qmax - qmin + qmin * M1s if logP begin set Ps = 10 ^ random size=N * call log10 Pmax - call log10 Pmin + call log10 Pmin end else begin set Ps = random size=N * Pmax - Pmin +...
def __init__(self, M1, qmin=0.1, qmax=1, Pmin=0.5, Pmax=365, N=1e5, logP=True, eccfn=None): M1s = np.ones(N)*M1 M2s = (rand.random(size=N)*(qmax-qmin) + qmin)*M1s if logP: Ps = 10**(rand.random(size=N)*((np.log10(Pmax) - np.log10(Pmin))) + np.log10(Pmin)) else: Ps...
Python
nomic_cornstack_python_v1
function register_factory self factory begin if not callable factory begin raise call ValueError string factory must be callable end append _factories factory end function
def register_factory(self, factory): if not callable(factory): raise ValueError('factory must be callable') self._factories.append(factory)
Python
nomic_cornstack_python_v1
import socket from service import Service class IrcCat extends Service begin function __init__ self host port channel begin call __init__ string irccat set _host = host set _port = port set _channel = channel end function function announce self message channel=none begin set s = call socket AF_INET SOCK_STREAM call con...
import socket from .service import Service class IrcCat(Service): def __init__(self, host, port, channel): super().__init__("irccat") self._host = host self._port = port self._channel = channel def announce(self, message, channel=None): s = socket.socket(socket.AF_INE...
Python
zaydzuhri_stack_edu_python
import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine , func from flask import Flask , jsonify import datetime as dt from datetime import datetime set engine = call create_engine string sqlite:///Resources/hawaii.sqli...
import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify import datetime as dt from datetime import datetime engine = create_engine("sqlite:///Resources/hawaii.sqlite") Base = autom...
Python
zaydzuhri_stack_edu_python
from utils.utils import * from compare import expect decorator call when string I need to test the response in the {service} using {method} function step_impl context service snippet=none method=string GET begin set method = method set service = service set payload = call fill_payload apiKey end function decorator call...
from utils.utils import * from compare import expect @when('I need to test the response in the {service} using {method}') def step_impl(context, service, snippet=None, method="GET"): context.method = method context.service = service context.payload = fill_payload(context.apiKey) @then('I get response wi...
Python
zaydzuhri_stack_edu_python
function contains1 value lst begin string (object, list of list) -> bool Return whether value is an element of one of the nested lists in lst. >>> contains1('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]]) True comment intialize found value to False, change it to True if we find the value in the list of lists...
def contains1(value, lst): """ (object, list of list) -> bool Return whether value is an element of one of the nested lists in lst. >>> contains1('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]]) True """ # intialize found value to False, change it to True if we find the value in ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import datetime set gg = list string BGO string OSL string SVG string TOS string TRD set filepath = string -OUT.csv for i in gg begin set filep = i + filepath set df = read csv filep set weekdaylist = list set IATA = list for tuple index row in call iterrows begin set tuple Year Month Day = split ...
import pandas as pd import datetime gg = ["BGO", "OSL", "SVG", "TOS", "TRD"] filepath = "-OUT.csv" for i in gg: filep = i + filepath df = pd.read_csv(filep) weekdaylist = [] IATA = [] for index, row in df.iterrows(): Year, Month, Day = row["Date"].split("-") weekday = ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf8 import copy set __author__ = string mkompan class Tree extends object begin function __init__ self node begin set node = node set branches = list end function function setBranches self branches begin set branches = list for branch in branches begin if is instance branch...
#!/usr/bin/python # -*- coding: utf8 import copy __author__ = 'mkompan' class Tree(object): def __init__(self, node): self.node = node self.branches = list() def setBranches(self, branches): self.branches = list() for branch in branches: if isinstance(branch, Tree...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import ConfigParser class Parser begin function __init__ self begin set config = call RawConfigParser end function function load self file begin read config file end function function get self section key begin get config section key end function end class
#!/usr/bin/env python import ConfigParser class Parser: def __init__(self): self.config = ConfigParser.RawConfigParser() def load(self, file): self.config.read(file) def get(self, section, key): self.config.get(section, key)
Python
zaydzuhri_stack_edu_python
from collections import Counter class Solution begin comment @param A : list of integers comment @param B : integer comment @param C : integer comment @return an integer function solve self A B C begin if length A == 0 begin return 0 end set lenC = length format string {0} C if lenC < B begin return 0 end if lenC > B b...
from collections import Counter class Solution: # @param A : list of integers # @param B : integer # @param C : integer # @return an integer def solve(self, A, B, C): if len(A) == 0: return 0 lenC = len("{0}".format(C)) if lenC < B: ...
Python
zaydzuhri_stack_edu_python
function __init__ self l max_phi max_u1 max_u2 begin set l = l set max_phi = max_phi set max_u1 = max_u1 set max_u2 = max_u2 end function
def __init__(self, l, max_phi, max_u1, max_u2): self.l = l self.max_phi = max_phi self.max_u1 = max_u1 self.max_u2 = max_u2
Python
nomic_cornstack_python_v1
function gp2cellids grid gp idomain idomain_active=true type=string polygon layer=0 areas=3 begin set ix = call GridIntersect grid if type == string polygon begin set result = call intersect_polygon geometry at 0 comment only take into account cells that have a least 1/3 intersected set result = result at areas > max a...
def gp2cellids (grid, gp, idomain, idomain_active=True, type = "polygon",layer=0,areas=3): ix = GridIntersect(grid) if type == "polygon": result = ix.intersect_polygon(gp.geometry[0]) result = result[result.areas>(np.max(result.areas)/3)] # only take into account cells that have a least 1/3...
Python
nomic_cornstack_python_v1
function _get_flag field begin return call get_flag_value field none end function
def _get_flag(field: str) -> Any: return flags.FLAGS.get_flag_value(field, None)
Python
nomic_cornstack_python_v1
from selenium import webdriver import time import datetime import re import subprocess function create_repo name begin comment 创建浏览器实体 set driver = call Firefox executable_path=string E:\examples\login_createcodelib\venv\selenium\webdriver\geckodriver-v0.21.0-win64\geckodriver.exe comment 打开github网站 get driver string h...
from selenium import webdriver import time import datetime import re import subprocess def create_repo(name): #创建浏览器实体 driver = webdriver.Firefox(executable_path=r'E:\examples\login_createcodelib\venv\selenium\webdriver\geckodriver-v0.21.0-win64\geckodriver.exe') #打开github网站 driver.get('https://githu...
Python
zaydzuhri_stack_edu_python
comment Definition for singly-linked list. comment class ListNode(object): comment def __init__(self, x): comment self.val = x comment self.next = None class Solution extends object begin function reorderList self head begin string :type head: ListNode :rtype: None Do not return anything, modify head in-place instead. ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: None Do not return anything, modify head in-place instead. ...
Python
zaydzuhri_stack_edu_python
function write_material_data ka_red=255.0 / 255 ka_green=255.0 / 255 ka_blue=255.0 / 255 ka_texture_ID=9223372036854775807 ks_red=255.0 / 255 ks_green=255.0 / 255 ks_blue=255.0 / 255 ks_texture_ID=9223372036854775807 kd_red=255.0 / 255 kd_green=255.0 / 255 kd_blue=255.0 / 255 kd_texture_ID=9223372036854775807 ns=0.1 al...
def write_material_data(ka_red=255.0 / 255, ka_green=255.0 / 255, ka_blue=255.0 / 255, ka_texture_ID=9223372036854775807, # ambient ks_red=255.0 / 255, ks_green=255.0 / 255, ks_blue=255.0 / 255, ks_texture_ID=9223372036854775807, # specular ...
Python
nomic_cornstack_python_v1
function __init__ self container controller begin call __init__ container controller set label_new = call Label self text=string New font=FONT_HEADER bg=string white grid row=0 column=0 columnspan=16 rowspan=1 sticky=string EW padx=PAD_SMALL set button_new_experiment = call BigButton self text=string ADD EXPERIMENT hei...
def __init__(self, container, controller): super().__init__(container, controller) label_new = tk.Label(self, text="New", font=FONT_HEADER, bg='white') label_new.grid(row=0, column=0, columnspan=16, rowspan=1, sticky='EW', padx=PAD_SMALL) self.button_new_experiment = BigButton(self, te...
Python
nomic_cornstack_python_v1
import pandas as pd from sqlalchemy import create_engine set weather_file = string austin_weather.csv set crime_file = string austin_crime.csv set weather_df = read csv weather_file set crime_df = read csv crime_file string Cleaned up the weather dataframe and dropped all unwanted data set weather_columns = weather_df ...
import pandas as pd from sqlalchemy import create_engine weather_file = 'austin_weather.csv' crime_file = "austin_crime.csv" weather_df = pd.read_csv(weather_file) crime_df = pd.read_csv(crime_file) ''' Cleaned up the weather dataframe and dropped all unwanted data''' weather_columns = weather_df[['Dat...
Python
zaydzuhri_stack_edu_python
function solution S K begin set l = length S set s = list S set n = 0 for i in range l begin if s at i == string - and i + K > l begin return string IMPOSSIBLE end else if s at i == string - begin set n = n + 1 for j in range K begin if s at i + j == string - begin set s at i + j = string + end else begin set s at i + ...
def solution(S, K): l= len(S) s= list(S) n= 0 for i in range(l): if s[i] == '-' and i + K > l: return 'IMPOSSIBLE' elif s[i] == '-': n+= 1 for j in range(K): if s[i + j] == '-': s[i + j]= '+' else: s[i + j]= '-' return str(n) file= open( __file__.split('.')[0]+'.in') lines= file.rea...
Python
zaydzuhri_stack_edu_python
comment ! python3 comment you need to run this before you use the r2w Quick Log option. It finds your shoe list on r2w and stores it on your machine comment you can also run this to update the shoe list if you've been manually logging from selenium import webdriver from selenium.webdriver.support.ui import Select impor...
#! python3 #you need to run this before you use the r2w Quick Log option. It finds your shoe list on r2w and stores it on your machine #you can also run this to update the shoe list if you've been manually logging from selenium import webdriver from selenium.webdriver.support.ui import Select import shelve import ti...
Python
zaydzuhri_stack_edu_python
function printMappedDataPoints mappedDataPoints key=none begin set totalDataPoints = 0 if key == none begin for key in mappedDataPoints begin print key + string Datapoints set componentDataPoints = length mappedDataPoints at key set totalDataPoints = totalDataPoints + componentDataPoints comment print("\n" + key + " da...
def printMappedDataPoints(mappedDataPoints, key = None): totalDataPoints = 0 if key == None: for key in mappedDataPoints: print(key + "Datapoints") componentDataPoints = len(mappedDataPoints[key]) totalDataPoints += componentDataPoints #print("\n" + key + " datapoints = ", componentDataPoints) f...
Python
nomic_cornstack_python_v1
comment Author: Mon Cedrick G. Frias comment Date: May 28, 2018 comment Filename: ground_truth.py comment Code Reference: This program maps all ground truth segments in an image. import numpy as np import cv2 set DRYRUN = true set name = string sp_12 comment Read image file set img = call imread string ../dataset/predi...
# Author: Mon Cedrick G. Frias # Date: May 28, 2018 # Filename: ground_truth.py # Code Reference: This program maps all ground truth segments in an image. import numpy as np import cv2 DRYRUN = True name = "sp_12" # Read image file img = cv2.imread("../dataset/predictions/images/" + name + ".jpg") # Open text file...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Mon May 10 18:27:32 2021 @author: Vlad from GA.chromosome import Chromosome class GeneticAlgorithm begin function __init__ self setlistSize nrGens popLength csvreader energy_function dance_function valence_function dance_diff energy_diff valence_diff begin set __setlistSi...
# -*- coding: utf-8 -*- """ Created on Mon May 10 18:27:32 2021 @author: Vlad """ from GA.chromosome import Chromosome class GeneticAlgorithm(): def __init__(self,setlistSize,nrGens,popLength,csvreader,energy_function,dance_function ,valence_function,dance_diff,energy_diff,valence_diff): ...
Python
zaydzuhri_stack_edu_python
function get_byname cityname begin set city = first filter by query session City name=cityname comment if city[0]: comment return city[0] comment return None return city or none end function
def get_byname(cityname): city = db.session.query(City).filter_by(name=cityname).first() #if city[0]: # return city[0] #return None return city or None
Python
nomic_cornstack_python_v1
import cv2 import numpy as np import pandas as pd import csv comment Variable to be Changed and Threshold Process if needed as per image set FILE_NAME = string nirajan.png comment percent of original size set scale_percent = 50 set contour_number = 0 set im = call imread string ./img/ + FILE_NAME comment resizing the i...
import cv2 import numpy as np import pandas as pd import csv # Variable to be Changed and Threshold Process if needed as per image FILE_NAME = "nirajan.png" scale_percent = 50 # percent of original size contour_number = 0 im = cv2.imread("./img/" + FILE_NAME) #resizing the image width = int(im.shape[1] * scale_percen...
Python
zaydzuhri_stack_edu_python
function getHMMoles self begin return call getHMDens / MOLES_PER_CC_TO_ATOMS_PER_BARN_CM * call getVolume * call getSymmetryFactor end function
def getHMMoles(self): return ( self.getHMDens() / units.MOLES_PER_CC_TO_ATOMS_PER_BARN_CM * self.getVolume() * self.getSymmetryFactor() )
Python
nomic_cornstack_python_v1
function test_atomic_non_negative_integer_min_exclusive_2_nistxml_sv_iv_atomic_non_negative_integer_min_exclusive_3_1 mode save_output output_format begin call assert_bindings schema=string nistData/atomic/nonNegativeInteger/Schema+Instance/NISTSchema-SV-IV-atomic-nonNegativeInteger-minExclusive-3.xsd instance=string n...
def test_atomic_non_negative_integer_min_exclusive_2_nistxml_sv_iv_atomic_non_negative_integer_min_exclusive_3_1(mode, save_output, output_format): assert_bindings( schema="nistData/atomic/nonNegativeInteger/Schema+Instance/NISTSchema-SV-IV-atomic-nonNegativeInteger-minExclusive-3.xsd", instance="ni...
Python
nomic_cornstack_python_v1
function has_extension cls cursor extension begin if not call table_exists cursor GEOPACKAGE_EXTENSIONS_TABLE_NAME begin return false end comment select all the rows set rows = call select_query cursor=cursor table_name=GEOPACKAGE_EXTENSIONS_TABLE_NAME select_columns=list string table_name string column_name string ext...
def has_extension(cls, cursor, extension): if not table_exists(cursor, GEOPACKAGE_EXTENSIONS_TABLE_NAME): return False # select all the rows rows = select_query(cursor=cursor, table_name=GEOPACKAGE_EXTENSIONS_TABLE_NAME, selec...
Python
nomic_cornstack_python_v1
import sys from collections import deque function solution begin set input = readline set n = integer strip input for _ in range n begin set stack = deque set ps = strip input set is_vps = true for i in ps begin if i == string ( begin call appendleft i end else if length stack > 0 begin call popleft end else begin set ...
import sys from collections import deque def solution(): input = sys.stdin.readline n = int(input().strip()) for _ in range(n): stack = deque() ps = input().strip() is_vps = True for i in ps: if i == '(': stack.appendleft(i) else: ...
Python
zaydzuhri_stack_edu_python
function serial_number_device serial_number=call read_serial begin return list serial_number device serial_number end function
def serial_number_device(serial_number=read_serial()): return [serial_number, Device(serial_number)]
Python
nomic_cornstack_python_v1
class ESIM extends Module begin function __init__ self config_base begin call __init__ set device = device set dropout = dropout if embedding_pretrained is not none begin set word_emb = call from_pretrained embedding_pretrained freeze=false end else begin set word_emb = embedding vord_size embeds_dim end decimal set re...
class ESIM(nn.Module): def __init__(self, config_base): super(ESIM, self).__init__() self.device = config_base.device self.dropout=config_base.dropout if config_base.embedding_pretrained is not None: self.word_emb = nn.Embedding.from_pretrained(config_base.embedding_pretr...
Python
zaydzuhri_stack_edu_python
function predict_and_save self test_data_paths filename min_acceptable=0.5 begin comment get number of examples set num_examples = length test_data_paths comment create data buffers for images and masks set images = zeros tuple num_examples image_height image_width 1 set depths = zeros tuple num_examples 1 dtype=uint16...
def predict_and_save(self, test_data_paths, filename, min_acceptable=0.5): # get number of examples num_examples = len(test_data_paths) # create data buffers for images and masks images = np.zeros((num_examples, self.image_height, self.image_width, 1)) depths = np.zeros...
Python
nomic_cornstack_python_v1
function lpj2pjc lpj begin set up_lpg_bound = 0.0 set shft = up_lpg_bound - max dim=1 keepdim=true at 0 set tmp = exp lpj + shft return call div_ sum dim=1 keepdim=true end function
def lpj2pjc(lpj: to.Tensor): up_lpg_bound = 0.0 shft = up_lpg_bound - lpj.max(dim=1, keepdim=True)[0] tmp = to.exp(lpj + shft) return tmp.div_(tmp.sum(dim=1, keepdim=True))
Python
nomic_cornstack_python_v1
function Uploads begin if method == string POST begin if string file not in files begin call flash string No file part return call redirect url end set file = files at string file save join path string Solar filename return call render_template string index.html message=string File Uploaded Successfuly end return call ...
def Uploads(): if request.method=="POST": if 'file' not in request.files: flash('No file part') return redirect(request.url) file=request.files["file"] file.save(os.path.join("Solar", file.filename)) return render_template("index.html", message = "File Uploade...
Python
nomic_cornstack_python_v1
function unblock self begin if not enable_nwfilters begin return end if not _nwfilter begin raise call DevopsError format string Unable to unblock interface {} on node {}: nwfilter not found! label name end set filter_xml = call build_interface_filter name=nwfilter_name filterref=network_name uuid=call UUIDString call ...
def unblock(self): if not self.driver.enable_nwfilters: return if not self._nwfilter: raise error.DevopsError( "Unable to unblock interface {} on node {}: nwfilter not" " found!".format(self.label, self.node.name)) filter_xml = builder.Lib...
Python
nomic_cornstack_python_v1
import sys set stdin = open string 5650.txt string r function is_wall r c begin global N return 0 <= r < N and 0 <= c < N end function function dfs r c i sr sc begin set v = 0 while true begin set r = r + dy at i set c = c + dx at i if not call is_wall r c begin if i == 0 begin set i = 2 end else if i == 1 begin set i ...
import sys sys.stdin = open("5650.txt", "r") def is_wall(r, c): global N return 0 <= r < N and 0 <= c < N def dfs(r, c, i, sr, sc): v = 0 while True: r += dy[i] c += dx[i] if not is_wall(r, c): if i == 0: i = 2 elif i == 1: i = 3 elif i == ...
Python
zaydzuhri_stack_edu_python
function _create_network self begin comment 1st convolution layer w/ 64 5x5 kernels and 2x2 maxpool set layer1_conv_W = call weight_variable list 5 5 1 64 name=string layer1_W set layer1_conv_b = call bias_variable list 64 name=string layer1_b set layer1_conv = relu conv 2d x layer1_conv_W name=string layer1_conv + lay...
def _create_network(self): #1st convolution layer w/ 64 5x5 kernels and 2x2 maxpool layer1_conv_W = weight_variable([5,5,1,64], name="layer1_W") layer1_conv_b = bias_variable([64], name="layer1_b") layer1_conv = tf.nn.relu(conv2d(self.x, layer1_conv_W, name='layer1_conv') + layer1_con...
Python
nomic_cornstack_python_v1
from tkinter import * from tkinter import filedialog from pytube import YouTube from moviepy.editor import * import shutil set root = call Tk function get_path begin set path = call askdirectory call config text=path end function function mp3 begin set video_path = get url_entry set file_path = call cget string text pr...
from tkinter import * from tkinter import filedialog from pytube import YouTube from moviepy.editor import * import shutil root = Tk() def get_path(): path = filedialog.askdirectory() path_label.config(text=path) def mp3(): video_path = url_entry.get() file_path = path_label.cget("t...
Python
zaydzuhri_stack_edu_python
function test_associates_tweets_with_user self begin set ingester = call Version2TweetIngester call ingest directory=FIXTURES_DIR_WITH_TWEETS set tweet = first objects set user = first objects assert equal user user end function
def test_associates_tweets_with_user(self): ingester = Version2TweetIngester() ingester.ingest(directory=FIXTURES_DIR_WITH_TWEETS) tweet = Tweet.objects.first() user = User.objects.first() self.assertEqual(tweet.user, user)
Python
nomic_cornstack_python_v1
function diop_solve eq param=call symbols string t integer=true begin set tuple var coeff eq_type = call classify_diop eq _dict=false if eq_type == name begin return call diop_linear eq param end else if eq_type == name begin return call diop_quadratic eq param end else if eq_type == name begin return call diop_ternary...
def diop_solve(eq, param=symbols("t", integer=True)): var, coeff, eq_type = classify_diop(eq, _dict=False) if eq_type == Linear.name: return diop_linear(eq, param) elif eq_type == BinaryQuadratic.name: return diop_quadratic(eq, param) elif eq_type == HomogeneousTernaryQuadratic.name: ...
Python
nomic_cornstack_python_v1
import re set st = input string Enter String : set result = split re string a st print result print string Thte Total No of a's are : length result - 1 print string ========================== set result = split re string a st 0 print result
import re st = input("Enter String : ") result = re.split(r"a",st) print(result) print("Thte Total No of a's are : ",len(result)-1) print("==========================") result = re.split(r"a",st,0) print(result)
Python
zaydzuhri_stack_edu_python
comment Read in the input set tuple a b c = map int split input comment Solve the problem and output the result
# Read in the input a,b,c = map(int, input().split()) # Solve the problem and output the result
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt function graph1 p5 p10 Tp5 Tp10 begin comment line 1 points set x1 = list string 5 string 10 set y1 = list p5 p10 comment plotting the line 1 points plot x1 y1 label=string From LGA comment line 2 points set x2 = list string 5 string 10 set y2 = list Tp5 Tp10 comment plotting the line 2 ...
import matplotlib.pyplot as plt def graph1(p5, p10, Tp5, Tp10): # line 1 points x1 = ["5", "10"] y1 = [p5, p10] # plotting the line 1 points plt.plot(x1, y1, label="From LGA") # line 2 points x2 = ["5", "10"] y2 = [Tp5, Tp10] # plotting the line 2 points plt.plot(x2, y2, label...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment -*- coding: utf-8 -*- string Python支持多种图形界面的第三方库,包括: Tk wxWidgets Qt GTK等等。 但是Python自带的库是支持Tk的Tkinter,使用Tkinter,无需安装任何包,就可以直接使用。 Tkinter 我们编写的Python代码会调用内置的Tkinter,Tkinter封装了访问Tk的接口; Tk是一个图形库,支持多个操作系统,使用Tcl语言开发; Tk会调用操作系统提供的本地GUI接口,完成最终的GUI。 所以,我们的代码只需要调用Tkinter提供的接口就可以了。 comment 第...
#! /usr/bin/env python # -*- coding: utf-8 -*- ''' Python支持多种图形界面的第三方库,包括: Tk wxWidgets Qt GTK等等。 但是Python自带的库是支持Tk的Tkinter,使用Tkinter,无需安装任何包,就可以直接使用。 Tkinter 我们编写的Python代码会调用内置的Tkinter,Tkinter封装了访问Tk的接口; Tk是一个图形库,支持多个操作系统,使用Tcl语言开发; Tk会调用操作系统提供的本地GUI接口,完成最终的GUI。 所以,我们的代码只需要调用Tkinter提供的...
Python
zaydzuhri_stack_edu_python
comment Alex is the dankest of McGroreys from lxml import html import requests import sys class Element begin function __init__ self station system price begin set station = station set system = system set price = replace price string , string set price = integer price end function function pprint self begin print stri...
#Alex is the dankest of McGroreys from lxml import html import requests import sys class Element(): def __init__(self, station, system, price): self.station = station self.system = system price = price.replace(',', '') self.price = int(price) def pprint(self): print(str(self.price)+" at "+self.station+" i...
Python
zaydzuhri_stack_edu_python
function itkVectorUC5___len__ begin return call itkVectorUC5___len__ end function
def itkVectorUC5___len__() -> "unsigned int": return _itkVectorPython.itkVectorUC5___len__()
Python
nomic_cornstack_python_v1
async function twitter self ctx user begin set user = strip user string @ if not match string ^[a-zA-Z0-9_]{1,15}$ user begin return await call send string Invalid username. end await call send string https://twitter.com/ { user } end function
async def twitter(self, ctx, *, user: str): user = user.strip("@") if not re.match(r"^[a-zA-Z0-9_]{1,15}$", user): return await ctx.send("Invalid username.") await ctx.send(f"https://twitter.com/{user}")
Python
nomic_cornstack_python_v1
function signup begin return call render_template string auth/signup.html end function
def signup(): return render_template('auth/signup.html')
Python
nomic_cornstack_python_v1
function _check_size self graph begin set number_of_nodes = call number_of_nodes if number_of_nodes > switch begin set mechanism = string approximate end end function
def _check_size(self, graph): self.number_of_nodes = graph.number_of_nodes() if self.number_of_nodes > self.switch: self.mechanism = "approximate"
Python
nomic_cornstack_python_v1
function result board action begin set tuple i j = action set new_board = deep copy board if board at i at j begin raise ValueError end else begin set new_board at i at j = call player board end return new_board end function
def result(board, action): i, j = action new_board = copy.deepcopy(board) if board[i][j]: raise ValueError else: new_board[i][j] = player(board) return new_board
Python
nomic_cornstack_python_v1
from typing import List set nums = list 0 0 1 1 1 2 2 3 3 4 class Solution begin function removeDuplicates self nums begin string Input: nums = [0,0,1,1,1,2,2,3,3,4] i j [0,1,2,3,0,2,1,3,1,4] i j i = 0 j = 1 while j < len(nums) if i == j: i++ j++ if i != j: if j + 1 == j j++ else: swap i++ j++ if j == len(nums)-1: swap...
from typing import List nums = [0,0,1,1,1,2,2,3,3,4] class Solution: def removeDuplicates(self, nums: List[int]) -> int: """ Input: nums = [0,0,1,1,1,2,2,3,3,4] i j [0,1,2,3,0,2,1,3,1,4] ...
Python
zaydzuhri_stack_edu_python
from typing import List class Solution begin function closedIsland self grid begin comment first sink those islands connected with edge comment then count the number of islands set tuple H W = tuple length grid length grid at 0 function sink i j begin comment sink it set grid at i at j = 1 for tuple a b in list tuple i...
from typing import List class Solution: def closedIsland(self, grid: List[List[int]]) -> int: # first sink those islands connected with edge # then count the number of islands H, W = len(grid), len(grid[0]) def sink(i, j): grid[i][j] = 1 # sink it for a...
Python
zaydzuhri_stack_edu_python
function get_success_url self begin set url_slug = call source_to_url_slug source return reverse string activity-management kwargs=dict string source url_slug end function
def get_success_url(self): url_slug = source_to_url_slug(self.source) return reverse('activity-management', kwargs={'source': url_slug})
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import torch.nn as nn comment import torch.nn.functional as F from torchsummary import summary string Conv-Bn-Relu moduule class ConvBnRelu extends Module begin function __init__ self in_channels out_channels kernel_size stride=1 padding=0 dilation=1 groups=1 relu6=false begin call __init_...
# -*- coding: utf-8 -*- import torch.nn as nn #import torch.nn.functional as F from torchsummary import summary """ Conv-Bn-Relu moduule """ class ConvBnRelu(nn.Module): def __init__(self,in_channels,out_channels,kernel_size,stride=1, padding=0,dilation=1,groups=1,relu6=False): super(ConvB...
Python
zaydzuhri_stack_edu_python
import re set s = string Hello, world ! How are you? set s = sub string + string s print s comment Output comment 'Hello, world! How are you?'
import re s = "Hello, world ! How are you?" s = re.sub(' +', ' ', s) print(s) # Output # 'Hello, world! How are you?'
Python
flytech_python_25k
import numpy as np import tensorflow as tf import os from functools import reduce import time set PATH = get current directory comment LAYER_NAMES = ['conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', comment 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', '...
import numpy as np import tensorflow as tf import os from functools import reduce import time PATH = os.getcwd() # LAYER_NAMES = ['conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', 'relu2_1', 'conv2_2', 'relu2_2', # 'pool2', 'conv3_1', 'relu3_1', 'conv3_2', 'relu3_2', 'conv3_3', '...
Python
zaydzuhri_stack_edu_python
function untar archive_fpath=EXTERNAL_DIR / METADATA_TAR_FNAME dst_dirpath=RAW_DIR force_overwrite=false begin try begin if not is instance archive_fpath Path begin set archive_fpath = call Path archive_fpath end if not exists archive_fpath begin raise call FileNotFoundError end end except tuple TypeError FileNotFoundE...
def untar( archive_fpath=EXTERNAL_DIR / METADATA_TAR_FNAME, dst_dirpath=RAW_DIR, force_overwrite=False ): try: if not isinstance(archive_fpath, Path): archive_fpath = Path(archive_fpath) if not archive_fpath.exists(): raise FileNotFoundError() except (TypeErr...
Python
nomic_cornstack_python_v1
import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from keras.models import Sequential from keras.layers import Dense function read_wine_data begin comment White wine data [489...
import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from keras.models import Sequential from keras.layers import Dense def read_wine_data(): # White wine data [4898 rows x...
Python
zaydzuhri_stack_edu_python
comment Stephen Krewson, August 24, 2019 comment filter_image_csv.py comment Input: a CSV file where an image resource is the *first* column comment Output: the same CSV file but with all the rows removed that do not comment have `inline_image`as the top prediction for the image comment Example usage, with export.pkl m...
# Stephen Krewson, August 24, 2019 # # filter_image_csv.py # # Input: a CSV file where an image resource is the *first* column # Output: the same CSV file but with all the rows removed that do not # have `inline_image`as the top prediction for the image # # Example usage, with export.pkl model file in the working direc...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import hashlib import random import os set main_dir = directory name path absolute path path __file__ set word_path = join path main_dir string ../../my_heap/words function alpha_shard word begin string Using poor job of assigning data to servers by using first letters. comment abcdef if w...
# -*- coding: utf-8 -*- import hashlib import random import os main_dir = os.path.dirname(os.path.abspath(__file__)) word_path = os.path.join(main_dir, "../../my_heap/words") def alpha_shard(word): """Using poor job of assigning data to servers by using first letters.""" if word[0] < 'g': # abcdef ...
Python
zaydzuhri_stack_edu_python
function check_alphabets_v1 words begin set alphabets = list 0 * 26 set a = ordinal string a set z = ordinal string z for x in lower words begin set char = ordinal x if a <= char and char <= z begin set alphabets at char - a = 1 end end set results = 0 for x in alphabets begin set results = results + x end return resul...
def check_alphabets_v1(words): alphabets = [0] * 26 a = ord('a') z = ord('z') for x in words.lower(): char = ord(x) if a <= char and char <= z: alphabets[char - a] = 1 results = 0 for x in alphabets: results += x return results
Python
nomic_cornstack_python_v1
function Cdeblend input omode=0 bthresh=0.1 mthresh=0.6 xr=1.5 yr=2.0 fnr=false dclip=none begin set funcName = string Cdeblend if _is_api4 begin import warnings warn string this function may produce visible incorrect output end comment check if not is instance input VideoNode begin raise call TypeError string { funcNa...
def Cdeblend(input: vs.VideoNode, omode: int = 0, bthresh: float = 0.1, mthresh: float = 0.6, xr: float = 1.5, yr: float = 2.0, fnr: bool = False, dclip: Optional[vs.VideoNode] = None ) -> vs.VideoNode: funcName = 'Cdeblend' if _is_api4: import warnings w...
Python
nomic_cornstack_python_v1
comment --coding=utf-8-- comment ! python3 import requests , os , bs4 set url = string http://xkcd.com/5/ make directories string xkcd exist_ok=true while not ends with url string # begin comment download the page print string Downloading page %s ... % url set response = get requests url print string the return code : ...
# --coding=utf-8-- #! python3 import requests, os, bs4 url = 'http://xkcd.com/5/' os.makedirs("xkcd", exist_ok=True) while not url.endswith('#'): # download the page print("Downloading page %s ..." % url) response = requests.get(url) print("the return code : " + str(response.status_code)) soup ...
Python
zaydzuhri_stack_edu_python
string se datan fosiles con la ecuacion dA/dt=-alfa*A, A cantidad de sustancia radioactiva remanente, alfa es constante, t en anios. Asumiendo a=1.5e-7, detemrinar edad de un fosil contiene sustancia A con solo remanente de 30% comment se importan las librerias a utilizar from sympy import * from sympy.abc import t com...
'''se datan fosiles con la ecuacion dA/dt=-alfa*A, A cantidad de sustancia radioactiva remanente, alfa es constante, t en anios. Asumiendo a=1.5e-7, detemrinar edad de un fosil contiene sustancia A con solo remanente de 30%''' #se importan las librerias a utilizar from sympy import * from sympy.abc import t #EDO A=F...
Python
zaydzuhri_stack_edu_python
function getDocumentsByHostnameDomain begin comment Grab POST data set data = call get_json force=true comment Grab POST data vars set hostname = data at string docParams at string hostname set runname = data at string docParams at string runname comment Assemble query and execute set test_query = dict string run_infor...
def getDocumentsByHostnameDomain(): #Grab POST data data = request.get_json(force=True) #Grab POST data vars hostname = data['docParams']['hostname'] runname = data['docParams']['runname'] #Assemble query and execute test_query = {'run_information': {'$exists': 'true'}, 'run_informati...
Python
nomic_cornstack_python_v1
function feedback_group_error self classname method group begin debug string feedback_group_error(%s, %s, %s) classname method group info string Testcase %s %s failed in the following group classname method for tuple test_class test_method in group begin info string - %s %s test_class test_method end set result_html_fi...
def feedback_group_error(self, classname, method, group): logging.debug("feedback_group_error(%s, %s, %s)", classname, method, group) logging.info("Testcase %s %s failed in the following group", classname, method) for (test_class, test_method) in group: logging.info(" - %s %s", test...
Python
nomic_cornstack_python_v1
string Takes an indefinite number of strings until an empty string is entered Will check if any strings were repeated set strings = list set repeated_strings = list set repeats = false set string = string input string Enter a string: while not string == string begin if string in strings begin append repeated_strings...
""" Takes an indefinite number of strings until an empty string is entered Will check if any strings were repeated """ strings = [] repeated_strings = [] repeats = False string = str(input("Enter a string: ")) while not string == '': if string in strings: repeated_strings.append(string) repeats = ...
Python
zaydzuhri_stack_edu_python