code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string Problem 1 - Check consistency of a curriculum Right now assuming all nodes in graph are connected
import sys
comment use depth first search to find if cycles
function dfs adj i visited inner_visit
begin
set visited at i = 1
set inner_visit at i = 1
for n in adj at i
begin
if visited at n == 0
begin
set tuple out... | '''
Problem 1 - Check consistency of a curriculum
Right now assuming all nodes in graph are connected
'''
import sys
#use depth first search to find if cycles
def dfs(adj, i, visited, inner_visit):
visited[i] = 1
inner_visit[i] = 1
for n in adj[i]:
if visited[n] == 0:
out, visited = d... | Python | zaydzuhri_stack_edu_python |
comment Manipulando Cadeia de Textos
string #FATIAMENTO (começo, fim, pulando) print(frase[9]) print(frase[9:13]) print(frase[9:21]) print(frase[9:21:2]) # começa posição 9 e vai até posição 21, pulando de dois em dois print(frase[:5]) # começa posição 0 e vai até a posição 5 print(frase[15:]) # começa posição 15 até o... | #Manipulando Cadeia de Textos
'''
#FATIAMENTO (começo, fim, pulando)
print(frase[9])
print(frase[9:13])
print(frase[9:21])
print(frase[9:21:2]) # começa posição 9 e vai até posição 21, pulando de dois em dois
print(frase[:5]) # começa posição 0 e vai até a posição 5
print(frase[15:]) # começa posição 15 até o f... | Python | zaydzuhri_stack_edu_python |
comment LSTM1 for touchData
comment This script accepts experimental spike data from a day of touch experiments
comment and runs them through a single layer LSTM classifier. Each data point is a
comment vector of length N (total number of 3b neurons) with each entry being that neurons
comment spike count during a windo... | # LSTM1 for touchData
#This script accepts experimental spike data from a day of touch experiments
#and runs them through a single layer LSTM classifier. Each data point is a
#vector of length N (total number of 3b neurons) with each entry being that neurons
#spike count during a window of time, w. The LSTM seeks to c... | Python | zaydzuhri_stack_edu_python |
function _getDistributeDestinations self
begin
set nodeDestinationList = list
set gatewayConnectionList = list
for connection in connections
begin
comment Make sure that the connection is active
if active == false
begin
continue
end
set destinationLRNode = none
if gateway_connection == true
begin
append gatewayConnec... | def _getDistributeDestinations(self):
nodeDestinationList =[]
gatewayConnectionList = []
for connection in sourceLRNode.connections:
# Make sure that the connection is active
if connection.active == False:
continue
destinationLRNode = None
... | Python | nomic_cornstack_python_v1 |
class AddUserPage extends object
begin
function __init__ self driver
begin
set driver = driver
end function
function add_user self username password
begin
set user_form = call find_element_by_id string user_form
set username_ = call find_element_by_name string username
set password1 = call find_element_by_name string p... | class AddUserPage(object):
def __init__(self, driver):
self.driver = driver
def add_user(self, username, password):
user_form = self.driver.find_element_by_id('user_form')
username_ = user_form.find_element_by_name('username')
password1 = user_form.find_element_by_name('passwor... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Thu Oct 19 03:59:04 2017 @author: fabricio Using accuracy metric
import numpy as np
comment import matplotlib.pyplot as plt
import gzip
import sys
from keras.models import Model
from keras.layers import Dense , Input
from keras.layers import ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 03:59:04 2017
@author: fabricio
Using accuracy metric
"""
import numpy as np
#import matplotlib.pyplot as plt
import gzip
import sys
from keras.models import Model
from keras.layers import Dense, Input
from keras.layers import Dropout, GaussianN... | Python | zaydzuhri_stack_edu_python |
function ball_track screen ball_list ball rn_tol p_ball direction
begin
set tuple paddle_prox wall_prox = call proximity_alarm ball_list rn_tol
comment Ball is near lossy area or no direction has been established
if paddle_prox or wall_prox or not p_ball
begin
set test = call omni_search screen ball_list ball rn_tol
en... | def ball_track(screen, ball_list, ball, rn_tol, p_ball, direction):
paddle_prox, wall_prox = proximity_alarm(ball_list, rn_tol)
if paddle_prox or wall_prox or not p_ball: # Ball is near lossy area or no direction has been established
test = omni_search(screen, ball_list, ball, rn_tol)
else:
... | Python | nomic_cornstack_python_v1 |
function get_welcome_response
begin
set session_attributes = dict
set card_title = string Welcome
set speech_output = string Welcome to the atomosphere analyzer.
comment If the user either does not reply to the welcome message or says something
comment that is not understood, they will be prompted again with this text... | def get_welcome_response():
session_attributes = {}
card_title = "Welcome"
speech_output = "Welcome to the atomosphere analyzer."
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = "W... | Python | nomic_cornstack_python_v1 |
function is_prime num
begin
set prime = true
if num <= 1
begin
set prime = false
end
else
begin
for i in range 2 num
begin
if num % i == 0
begin
set prime = false
end
end
end
return prime
end function
function main
begin
set num = 10
print string All prime numbers up to num string are:
for i in range 2 num + 1
begin
if... | def is_prime(num):
prime = True
if num <= 1:
prime = False
else:
for i in range(2, num):
if num % i == 0:
prime = False
return prime
def main():
num = 10
print("All prime numbers up to", num, "are:")
for i in range(2, num+1):
if is_prime(... | Python | iamtarun_python_18k_alpaca |
comment ! /usr/bin/env python3
comment 2020-07-28
string Multiple States https://plotly.com/python/county-choropleth/#multiple-states
import plotly.figure_factory as ff
import pandas as pd
set NE_states = list string Connecticut string Maine string Massachusetts string New Hampshire string Rhode Island string Vermont
s... | #! /usr/bin/env python3
#
# 2020-07-28
"""
Multiple States
https://plotly.com/python/county-choropleth/#multiple-states
"""
import plotly.figure_factory as ff
import pandas as pd
NE_states = ['Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'Rhode Island', 'Vermont']
df_sample = pd.read_csv('https://raw.g... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string ingest.py : Data ingest script for ProTK 2
import os , sys
append path directory name path real path path __file__
from protk2.db.core import *
from protk2.db.types import *
from protk2.loaders import *
from protk2.parsers import *
from protk2.fs import *
from protk2.praat import *
f... | #!/usr/bin/env python
"""
ingest.py : Data ingest script for ProTK 2
"""
import os,sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from protk2.db.core import *
from protk2.db.types import *
from protk2.loaders import *
from protk2.parsers import *
from protk2.fs import *
from protk2.praat import *
fro... | Python | zaydzuhri_stack_edu_python |
function parse_first self response
begin
set ajax_url = call extract_first
set ajax_url = url join replace replace ajax_url string ${size} string 30 string ${page} string 1
yield call Request ajax_url callback=parse_cate
end function | def parse_first(self, response):
ajax_url = (response.xpath('//div[@id="js-live-list-panel"]/div[2]/@data-url') or
response.xpath('//div[@id="js-live-list-panel"]/div[2]/div/@data-url') or
response.xpath('//div[@id="js-live-list-panel"]/div[3]/@data-url')).extract_firs... | Python | nomic_cornstack_python_v1 |
function findTime C F X
begin
set rate = 2
set seconds = 0
set best_so_far = X / rate
if rate == X
begin
return format string {:.7f} 1
end
while 1
begin
set farm = C / rate
set seconds = seconds + farm
set rate = rate + F
set rem = X / rate
set poss = seconds + rem
if poss > best_so_far
begin
break
end
set best_so_far ... | def findTime(C, F, X):
rate = 2
seconds = 0
best_so_far = X/rate
if rate == X:
return "{:.7f}".format(1)
while (1):
farm = C/rate
seconds += farm
rate += F
rem = X/rate
poss = seconds + rem
if poss > best_so_far:
break
best_so_far = poss
return "{:.7f}".format(best_so_far)
def main():
num_te... | Python | zaydzuhri_stack_edu_python |
function _update_weights self xi target
begin
set output = call net_input xi
set error = target - output
set w_ at slice 1 : : = w_ at slice 1 : : + eta * dot error
set w_ at 0 = w_ at 0 + eta * error
set cost = 0.5 * error ^ 2
return cost
end function | def _update_weights(self, xi, target):
output = self.net_input(xi)
error= (target - output)
self.w_[1:] += self.eta * xi.dot(error)
self.w_[0] += self.eta * error
cost =0.5* error**2
return cost | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string function that returns the number of lines of a text file:
function number_of_lines filename=string
begin
string function that returns the number of lines of a text file:
with open filename string r as f
begin
return length list f
end
end function | #!/usr/bin/python3
"""
function that returns the number of lines of a text file:
"""
def number_of_lines(filename=""):
"""
function that returns the number of lines of a text file:
"""
with open(filename, "r") as f:
return len(list(f))
| Python | zaydzuhri_stack_edu_python |
function findMaxSubArray arr
begin
set n = length arr
comment Initialize result
set max_len = 0
set ending_index = - 1
comment Initialize sum of elements
set curr_sum = 0
comment Initialize start
set start = 0
comment Traverse through the given array
for i in range 0 n
begin
comment Add current element to sum
set curr_... | def findMaxSubArray(arr):
n = len(arr)
# Initialize result
max_len = 0
ending_index = -1
# Initialize sum of elements
curr_sum = 0
# Initialize start
start = 0
# Traverse through the given array
for i in range(0, n):
# Add current element to sum ... | Python | iamtarun_python_18k_alpaca |
comment 此例示意类方法的定义方法和用法
class Car
begin
comment 类变量
set count = 0
decorator classmethod
function getTotalCount cls
begin
string 此方法为类方法,第一个参数为cls,代表调用此方法的类
return count
end function
decorator classmethod
function updateCount cls number
begin
set count = count + number
end function
end class
comment 用类来调用类方法
print call ... | # 此例示意类方法的定义方法和用法
class Car:
count = 0 # 类变量
@classmethod
def getTotalCount(cls):
'''此方法为类方法,第一个参数为cls,代表调用此方法的类'''
return cls.count
@classmethod
def updateCount(cls, number):
cls.count += number
print(Car.getTotalCount()) # 用类来调用类方法
Car.updateCount(2) ... | Python | zaydzuhri_stack_edu_python |
import ColourDetection
from os.path import exists
try
begin
import Tkinter as tk
from Tkinter import messagebox
end
except ImportError
begin
import tkinter as tk
from tkinter import messagebox
end
comment Global Variables
set iname = string
function checkImage
begin
comment Function to check for the existance of the f... | import ColourDetection
from os.path import exists
try:
import Tkinter as tk
from Tkinter import messagebox
except ImportError:
import tkinter as tk
from tkinter import messagebox
#Global Variables
iname=""
def checkImage():
#Function to check for the existance of the file
if Imag... | Python | zaydzuhri_stack_edu_python |
import sys
set stdin = open string 컨테이너 운반.txt
set T = integer input
for tc in range 1 1 + T
begin
set tuple n m = map int split input
set container = list map int split input
set truck = list map int split input
sort container
sort truck
set visited = list 0 * length container
set goal = 0
for q in range 1 length truc... | import sys
sys.stdin = open('컨테이너 운반.txt')
T = int(input())
for tc in range(1,1+T):
n,m = map(int,input().split())
container = list(map(int,input().split()))
truck = list(map(int,input().split()))
container.sort()
truck.sort()
visited = [0]*len(container)
goal = 0
for q in range(1,l... | Python | zaydzuhri_stack_edu_python |
from robot import Robot
from exceptions import InvalidMove
import pytest
decorator call parametrize string x,y,facing,expected list tuple string -1 string -1 string NORTH InvalidMove tuple string 0 string -1 string NORTH InvalidMove tuple string -1 string 0 string NORTH InvalidMove tuple string 5 string 0 string EAST I... | from robot import Robot
from exceptions import InvalidMove
import pytest
@pytest.mark.parametrize("x,y,facing,expected", [
('-1', '-1', 'NORTH', InvalidMove),
('0', '-1', 'NORTH', InvalidMove),
('-1', '0', 'NORTH', InvalidMove),
('5', '0', 'EAST', InvalidMove),
('0', '5', 'EAST', InvalidMove),... | Python | zaydzuhri_stack_edu_python |
function max_subarray_sum arr
begin
set max_sum = 0
set current_sum = 0
set max_length = length arr
set start_index = 0
for i in range length arr
begin
set current_sum = current_sum + arr at i
if current_sum > max_sum
begin
set max_sum = current_sum
set max_length = i - start_index + 1
end
if current_sum < 0
begin
set ... | def max_subarray_sum(arr):
max_sum = 0
current_sum = 0
max_length = len(arr)
start_index = 0
for i in range(len(arr)):
current_sum += arr[i]
if current_sum > max_sum:
max_sum = current_sum
max_length = i - start_index + 1
if curr... | Python | jtatman_500k |
import pendulum
from airflow.contrib.hooks.ftp_hook import FTPSHook , FTPHook
from airflow.contrib.hooks.sftp_hook import SFTPHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
import dateutil.parser
import re
import json
class FTPSearchOperator extends BaseOperator
begin
s... | import pendulum
from airflow.contrib.hooks.ftp_hook import FTPSHook, FTPHook
from airflow.contrib.hooks.sftp_hook import SFTPHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
import dateutil.parser
import re
import json
class FTPSearchOperator(BaseOperator):
"""
... | Python | zaydzuhri_stack_edu_python |
function to_json self
begin
return dict string username username ; string password password ; string code code ; string langId lang
end function | def to_json(self) -> dict:
return {
"username": self.username,
"password": self.password,
"code": self.code,
"langId": self.lang
} | Python | nomic_cornstack_python_v1 |
from datetime import datetime
set ano = year
set anoNasc = integer input string Digite o ano de nascimento do atleta:
set idade = ano - anoNasc
if idade <= 9
begin
print string Atleta Mirim
end
else
if idade <= 14
begin
print string Atleta Infantil
end
else
if idade <= 19
begin
print string Atleta Júnior
end
else
if id... | from datetime import datetime
ano = datetime.now().year
anoNasc = int(input('Digite o ano de nascimento do atleta: '))
idade = ano-anoNasc
if (idade<=9):
print('Atleta Mirim')
elif (idade <= 14):
print('Atleta Infantil')
elif (idade <= 19):
print('Atleta Júnior')
elif (idade <= 25):
print('Atleta Sênior... | Python | zaydzuhri_stack_edu_python |
function update_network_status network_id public
begin
set network = call get_network_by_id_or_404 network_id
if report is none
begin
call abort 400 string Network does not have an associated report.
end
if not is_admin or id != user_id
begin
call abort 403 string You do not have permission to modify that network
end
s... | def update_network_status(network_id: int, public: bool) -> Response:
network = manager.get_network_by_id_or_404(network_id)
if network.report is None:
abort(400, 'Network does not have an associated report.')
if not current_user.is_admin or current_user.id != network.report.user_id:
abort... | Python | nomic_cornstack_python_v1 |
function set_max_noutput_items self *args **kwargs
begin
return call ncofdm_carrier_allocator_sptr_set_max_noutput_items self *args keyword kwargs
end function | def set_max_noutput_items(self, *args, **kwargs):
return _ncofdm_swig.ncofdm_carrier_allocator_sptr_set_max_noutput_items(self, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import os
comment import preparation.translator as translator
import preparation.translator as translator
import preparation.chassis_model as chassis_model
from sklearn.utils import shuffle
function LoadData
begin
set dirname = directory name path directory name path real path path __file__
set data... | import pandas as pd
import os
# import preparation.translator as translator
import preparation.translator as translator
import preparation.chassis_model as chassis_model
from sklearn.utils import shuffle
def LoadData():
dirname = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
data_dir = os.path.j... | Python | zaydzuhri_stack_edu_python |
function zones self
begin
set _zones = list
set device = get _device_conf string Device dict
if get device string HasThermostatZone1 false
begin
append _zones call Zone self lambda -> _state lambda -> _device_conf 1
end
if get device string HasZone2 and get device string HasThermostatZone2 false
begin
append _zones ... | def zones(self) -> Optional[List[Zone]]:
_zones = []
device = self._device_conf.get("Device", {})
if device.get("HasThermostatZone1", False):
_zones.append(Zone(self, lambda: self._state, lambda: self._device_conf, 1))
if device.get("HasZone2") and device.get("HasThermostat... | Python | nomic_cornstack_python_v1 |
comment scripting language : Python 3.6
comment module : Pandas
import pandas as pd
comment read logfile
set filename = string logfile.tsv
set df = read csv filename sep=string header=0
comment rename column name
rename columns=dict string # date string date inplace=true
comment convert 'date' to timestamp
set df at s... | # scripting language : Python 3.6
# module : Pandas
import pandas as pd
# read logfile
filename = "logfile.tsv"
df = pd.read_csv(filename, sep='\t', header=0)
# rename column name
df.rename(columns={'# date':'date'}, inplace=True)
# convert 'date' to timestamp
df['date'] = pd.to_datetime(df['date'])
def total_dat... | Python | zaydzuhri_stack_edu_python |
function retweet server id_
begin
return call Tweet *get_db().do(partial(get_ops().create_retweet, server, id_))
end function | def retweet(server, id_):
return Tweet(*get_db().do(partial(get_ops().create_retweet, server, id_))) | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
import numpy as np
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
import warnings
simple filter string ignore
import tushare as ts
string Momentum 动量效应 指在一定时期内,如果某股票或证券 (1) time-series 过去涨 未来一段时间内也会涨 (2) cross-sectional 横切面数据, 同一行业,有几个股票涨得好,未来预测也会涨得比较好;本来涨得不好的,未来也... | #coding:utf-8
import numpy as np
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
import warnings
warnings.simplefilter('ignore')
import tushare as ts
'''
Momentum 动量效应 指在一定时期内,如果某股票或证券
(1) time-series 过去涨 未来一段时间内也会涨
(2) cross-sectional 横切面数据, 同一行业,有几个股票涨得好,未来预测也会涨得比较好;本来涨得不好的,未来也涨得不好... | Python | zaydzuhri_stack_edu_python |
function _r3 shape
begin
set tuple az ay ax = list comprehension array range - l / 2.0 + 0.5 l / 2.0 + 0.5 for l in shape
set tuple zz yy xx = call meshgrid az ay ax indexing=string ij
return tuple xx yy zz
end function | def _r3(shape):
az, ay, ax = [np.arange(-l / 2. + .5, l / 2. + .5) for l in shape]
zz,yy,xx = np.meshgrid(az,ay,ax, indexing = "ij")
return xx, yy, zz | Python | nomic_cornstack_python_v1 |
import sqlite3
set n = string 0
set test_type = string relax
set list_of_dic = list dict string AF3 tuple 1 2 ; string AF4 tuple 3 3 ; string F3 tuple 2 4 ; string F4 tuple 1 5 ; string F7 tuple 6 6 ; string F8 tuple 12 7 ; string FC5 tuple 1 8 ; string FC6 tuple 8 9 ; string T7 tuple 9 10 ; string T8 tuple 0 11 ; stri... | import sqlite3
n = "0"
test_type = "relax"
list_of_dic = [{"AF3":(1,2),
"AF4":(3,3),
"F3":(2,4),
"F4":(1,5),
"F7":(6,6),
"F8":(12,7),
"FC5":(1,8),
"FC6":(8,9),
"T7":(9,10),
"T8":(0,11),
"P7":(1,12),
"P8":(8,13)... | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
import torch.nn.functional as F
class BayesianCNN extends Module
begin
string From the paper: "acquisition functions are assessed with the same model structure: convolution-relu-convolution-relu-max pooling-dropout-dense-relu-dropout-dense-softmax, with 32 convolution kernels, 4x4 ker... | import torch
import torch.nn as nn
import torch.nn.functional as F
class BayesianCNN(nn.Module):
"""
From the paper: "acquisition functions are assessed with the same model structure:
convolution-relu-convolution-relu-max pooling-dropout-dense-relu-dropout-dense-softmax,
with 32 convolution kernels, 4x... | Python | zaydzuhri_stack_edu_python |
from euler import isPrime
set curr = 1
set diff = 2
set primecount = 0
set side = 1
while primecount / side * 2.0 - 1 > 0.1 or primecount == 0
begin
for k in range 4
begin
set curr = curr + diff
if call isPrime curr
begin
set primecount = primecount + 1
end
end
set diff = diff + 2
set side = side + 2
end | from euler import isPrime
curr = 1
diff = 2
primecount = 0
side = 1
while (primecount/(side*2.0-1))>0.1 or primecount==0:
for k in range(4):
curr = curr + diff
if isPrime(curr):
primecount+=1
diff+=2
side+=2
| Python | zaydzuhri_stack_edu_python |
function select_by_location self other matches_only=true
begin
if is instance other Geometry
begin
if lower geometry_type == string point
begin
set res = call within other
end
else
begin
set res = call overlaps other
end
if matches_only
begin
return self at res
end
else
begin
set self at string select_by_location = res... | def select_by_location(self, other, matches_only=True):
if isinstance(other, Geometry):
if self.geometry_type.lower() == 'point':
res = self.within(other)
else:
res = self.overlaps(other)
if matches_only:
return self[res]... | Python | nomic_cornstack_python_v1 |
function call_error
begin
print string Error in input format.
exit
end function | def call_error():
print("Error in input format.")
sys.exit() | Python | nomic_cornstack_python_v1 |
function findTheCity self n edges distanceThreshold
begin
set costs = default dictionary lambda -> decimal string inf
for i in range n
begin
set costs at tuple i i = 0
end
for tuple i j cost in edges
begin
set costs at tuple i j = cost
set costs at tuple j i = cost
end
for k in range n
begin
for i in range n
begin
for... | def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int:
costs = defaultdict(lambda:float('inf'))
for i in range(n):
costs[(i,i)] = 0
for i, j, cost in edges:
costs[(i,j)] = cost
costs[(j,i)] = cost
for k in r... | Python | nomic_cornstack_python_v1 |
function _get_changed_docs self ancestral_commit_sha doc_id_from_repo_path doc_ids_to_check=none
begin
string Returns the set of documents that have changed on the master since commit `ancestral_commit_sha` or `False` (on an error) 'doc_id_from_repo_path' is a required function if `doc_ids_to_check` is passed in, it sh... | def _get_changed_docs(self,
ancestral_commit_sha,
doc_id_from_repo_path,
doc_ids_to_check=None):
"""Returns the set of documents that have changed on the master since
commit `ancestral_commit_sha` or `False` (on an error)
... | Python | jtatman_500k |
function get_context_data self **kwargs
begin
comment Call the base implementation first to get a context
set context = call get_context_data keyword kwargs
return context
end function | def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(SmansaUserVerifyView, self).get_context_data(**kwargs)
return context | Python | nomic_cornstack_python_v1 |
function runDataRef self dataRef psfCache=none
begin
try
begin
dataId at string tract
end
except any
begin
call getTract dataRef
end
set refWcs = call getWcs dataRef
set exposure = call getExposure dataRef
if psfCache is not none
begin
call setCacheSize psfCache
end
set refCat = call fetchReferences dataRef exposure
se... | def runDataRef(self, dataRef, psfCache=None):
try:
dataRef.dataId["tract"]
except:
self.getTract(dataRef)
refWcs = self.references.getWcs(dataRef)
exposure = self.getExposure(dataRef)
if psfCache is not None:
exposure.getPsf().setC... | Python | nomic_cornstack_python_v1 |
from flask import Blueprint , jsonify , request , abort , make_response
from app import db
from app.models.goal import Goal
from app.routes.task_routes import get_task , get_task_from_id
import requests
import os
set TOKEN = get environ string TOKEN
set goal_bp = call Blueprint string goal __name__ url_prefix=string /g... | from flask import Blueprint, jsonify, request, abort, make_response
from app import db
from app.models.goal import Goal
from app.routes.task_routes import get_task, get_task_from_id
import requests
import os
TOKEN = os.environ.get('TOKEN')
goal_bp = Blueprint("goal", __name__, url_prefix="/goals")
# Helper Functions... | Python | zaydzuhri_stack_edu_python |
comment SpaceWare by @TokyoEdTech
comment Part I : Getting started
import os
import random
import turtle
comment Set the animations sepeed to the maximum
call speed 0
comment Change the background color
call bgcolor string black
comment hide the default turtle
call hideturtle
comment This saves memory
call setundobuffe... | # SpaceWare by @TokyoEdTech
# Part I : Getting started
import os
import random
import turtle
turtle.speed(0) # Set the animations sepeed to the maximum
turtle.bgcolor('black') # Change the background color
turtle.hideturtle() # hide the default turtle
turtle.setundobuffer(1) # This saves memory
turtle.tracer(1) # T... | Python | zaydzuhri_stack_edu_python |
for i in score
begin
comment converting from string to int with using another list, but only if i is greater than minScore.
if i > minScore
begin
append lst i
end
end
comment standard adding and averaging.
for x in lst
begin
set summ = summ + x
end
set avg = summ / length lst
print round avg 2
comment not sure if neces... | for (
i
) in (
score
): # converting from string to int with using another list, but only if i is greater than minScore.
if i > minScore:
lst.append(i)
for x in lst: # standard adding and averaging.
summ = summ + x
avg = summ / len(lst)
print(
round(avg, 2)
) # not sure if necessary, but ... | Python | zaydzuhri_stack_edu_python |
function get_resized_size self
begin
set f = fmt
set tuple iw ih = size
if not stretch and iw <= fw and ih <= fh
begin
return
end
if image_ratio == format_ratio
begin
comment same ratio, just resize
return tuple fw fh
end
else
if image_ratio < format_ratio
begin
comment image taller than format
return tuple fh * iw / i... | def get_resized_size(self):
f = self.fmt
iw, ih = self.image.size
if not f.stretch and iw <= self.fw and ih <= self.fh:
return
if self.image_ratio == self.format_ratio:
# same ratio, just resize
return (self.fw, self.fh)
elif self... | Python | nomic_cornstack_python_v1 |
import random
class Character
begin
set attributes = list string Strength string Dexterity string Intelligence string Wisdom string Charisma string Constitution
function __init__ self name
begin
print string This is the constructor method
end function
end class
comment def diceRolling(attributes): | import random
class Character:
attributes = ["Strength", "Dexterity", "Intelligence", "Wisdom", "Charisma", "Constitution"]
def __init__(self, name):
print("This is the constructor method")
# def diceRolling(attributes):
| Python | zaydzuhri_stack_edu_python |
function survey_detail request survey_slug
begin
if is_authenticated
begin
if not exists filter name=string Survey Creators
begin
raise call Http404 string Page not found
end
end
else
begin
raise call Http404 string Page not found
end
set survey = call get_object_or_404 Survey slug=survey_slug
set my_surveys = call ord... | def survey_detail(request, survey_slug):
if request.user.is_authenticated:
if not request.user.groups.filter(name='Survey Creators').exists():
raise Http404("Page not found")
else:
raise Http404("Page not found")
survey = get_object_or_404(Survey, slug=survey_slug)
my_survey... | Python | nomic_cornstack_python_v1 |
function view_radial_model_stack sources model scale_radius=string r200 fit_method=string mcmc use_peak=true model_priors=none model_start_pars=none pix_step=1 radii=linear space 0.01 1 20 min_snr=0.0 lo_en=call Quantity 0.5 string keV hi_en=call Quantity 2.0 string keV custom_temps=none sim_met=0.3 abund_table=string ... | def view_radial_model_stack(sources: ClusterSample, model: str, scale_radius: str = "r200", fit_method: str = 'mcmc',
use_peak: bool = True, model_priors: List = None, model_start_pars: list = None,
pix_step: int = 1, radii: np.ndarray = np.linspace(0.01, 1, 20), ... | Python | nomic_cornstack_python_v1 |
function MLP D n H K p
begin
if n == 0
begin
print string Defaulting to linear classifier/regressor
return linear D K
end
else
begin
print string Using mlp with D=%d,H=%d,K=%d,n=%d % tuple D H K n
set layers = list batch norm 1d D call LinearBlock D H p
for _ in range n - 1
begin
append layers call LinearBlock H H p
en... | def MLP(D, n, H, K, p):
if n == 0:
print("Defaulting to linear classifier/regressor")
return nn.Linear(D, K)
else:
print("Using mlp with D=%d,H=%d,K=%d,n=%d"%(D, H, K, n))
layers = [nn.BatchNorm1d(D),
LinearBlock(D, H, p)]
for _ in range(n-1):
... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
function f n
begin
return call helper n n
end function
function helper left right
begin
if not left and not right
begin
return list list
end
set res = list
if left > 0
begin
set last_res = call helper left - 1 right
if last_res
begin
for it in last_res
begin
insert it 0 string (
end
exte... | #! /usr/bin/env python
def f(n):
return helper(n,n)
def helper(left, right):
if not left and not right:
return [[]]
res = []
if left > 0:
last_res = helper(left-1, right)
if last_res:
for it in last_res:
it.insert(0, '(')
res.extend(last_re... | Python | zaydzuhri_stack_edu_python |
import sys
call setrecursionlimit 25000
set cnt = 0
function fuck
begin
global cnt
set cnt = cnt + 1
call fuck
end function | import sys
sys.setrecursionlimit(25000)
cnt = 0
def fuck():
global cnt
cnt +=1
fuck()
| Python | zaydzuhri_stack_edu_python |
function compute A B C
begin
if 4 * power A 2 - 8 * A * B * C <= 0
begin
print 0
end
else
begin
set temp = A * A - 2 * A * B * C
set sqrt_temp = power temp 0.5
set y2 = A + sqrt_temp / B
set y1 = A - sqrt_temp / B
set x2 = power y2 2 / 2 * A
set x1 = power y1 2 / 2 * A
set result1 = x1 + x2 * y2 - y1 / 2
set result2 = ... | def compute(A, B, C):
if 4*pow(A, 2)-8*A*B*C <= 0:
print(0)
else:
temp = A*A-2*A*B*C
sqrt_temp = pow(temp, 0.5)
y2 = (A+sqrt_temp)/B
y1 = (A-sqrt_temp)/B
x2 = pow(y2, 2)/(2*A)
x1 = pow(y1, 2)/(2*A)
result1 = (x1+x2)*(y2-y1)/2
result2 = (pow... | Python | zaydzuhri_stack_edu_python |
import sys
set f = open argv at 1
for x in split read f string at slice 0 : - 1 :
begin
set buzz = list
set x = split x string
set div1 = integer x at 0
set div2 = integer x at 1
for y in range 1 integer x at 2 + 1
begin
set fizz = string
if y % div1 == 0
begin
set fizz = fizz + string F
end
if y % div2 == 0
begin
s... | import sys
f = open(sys.argv[1])
for x in f.read().split('\n')[0:-1]:
buzz = []
x = x.split(' ')
div1 = int(x[0])
div2 = int(x[1])
for y in range(1, int(x[2])+1):
fizz = ''
if (y % div1 == 0):
fizz += 'F'
if (y % div2 == 0):
fizz += 'B'
if (fizz == ''):
fizz = str(y)
buzz.append(fizz)
for y ... | Python | zaydzuhri_stack_edu_python |
function timer_remove_from_group request timer_id
begin
if method == string POST
begin
set dummy_view = call PADSTimerEditView request timer_id
set user_id = call get_session_user_id
if call edit_enabled
begin
set timer = call get_timer
set form_data = call TimerGroupForm POST timer_group_choices=call get_associated_gr... | def timer_remove_from_group(request, timer_id):
if request.method == "POST":
dummy_view = PADSTimerEditView(request, timer_id)
user_id = dummy_view.get_session_user_id()
if dummy_view.edit_enabled():
timer = dummy_view.get_timer()
form_data = TimerGroupForm(
... | Python | nomic_cornstack_python_v1 |
function referencing_cite elem doc
begin
if length content == 1 and is instance content at 0 Str
begin
set match = match string ^(@(?P<tag>(?P<category>[a-zA-Z][\w.-]*):(([a-zA-Z][\w.-]*)|(\d*(\.\d*)*))))$ text
if match
begin
set category = call group string category
if category in defined and defined at category at st... | def referencing_cite(elem, doc):
if len(elem.content) == 1 and isinstance(elem.content[0], Str):
match = re.match(
"^(@(?P<tag>(?P<category>[a-zA-Z][\\w.-]*):"
"(([a-zA-Z][\\w.-]*)|(\\d*(\\.\\d*)*))))$",
elem.content[0].text,
)
if match:
catego... | Python | nomic_cornstack_python_v1 |
comment vim: sw=4 sts=4 et fileencoding=utf8 nomod
string Personal names.
import operator
from sixx.input import InputError
from sixx.text import sortstr
from functools import reduce
set __all__ = list string EnglishSpanishName string SingleName string DecoratedName
function name_method func what=none
begin
string A fu... | # vim: sw=4 sts=4 et fileencoding=utf8 nomod
r'''Personal names.
'''
import operator
from sixx.input import InputError
from sixx.text import sortstr
from functools import reduce
__all__ = ['EnglishSpanishName', 'SingleName', 'DecoratedName']
def name_method(func, what=None):
r'''A function decorator that raises... | Python | zaydzuhri_stack_edu_python |
set fullname = input string Please type your full name (3 words):
set sepname = split fullname
print string First name: + sepname at 0 + string Middle name: + sepname at 1 + string Last name: + sepname at 2 | fullname = input("Please type your full name (3 words): ")
sepname = fullname.split()
print ("First name: " + sepname[0] + "\nMiddle name: " + sepname[1] + "\nLast name: " + sepname[2])
| Python | zaydzuhri_stack_edu_python |
function get_updated_at self
begin
if get data field_datetime_utc
begin
set parsed = parse parser get data field_datetime_utc
set new_format = string format time parsed string %Y-%m-%d %H:%M:%S
set dt_str = string %s UTC % new_format
return parse parser dt_str tzinfos=dict string UTC TZ_UTC
end
end function | def get_updated_at(self):
if self.data.get(self.field_datetime_utc):
parsed = dateutil.parser.parse(self.data.get(self.field_datetime_utc))
new_format = parsed.strftime('%Y-%m-%d %H:%M:%S')
dt_str = '%s UTC' % new_format
return dateutil.parser.parse(dt_str, tzinfo... | Python | nomic_cornstack_python_v1 |
function test_fma_invalid_param_intarray_floatarray_intarray_floatnum_511 self
begin
comment This version is expected to pass.
call fma floatarrayx floatarrayy floatarrayz floatarrayout
comment This is the actual test.
with assert raises TypeError
begin
call fma intarrayx floatarrayy intarrayz floatnumout
end
end funct... | def test_fma_invalid_param_intarray_floatarray_intarray_floatnum_511(self):
# This version is expected to pass.
arrayfunc.fma(self.floatarrayx, self.floatarrayy, self.floatarrayz, self.floatarrayout)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.fma(self.intarrayx, self.floatarrayy... | Python | nomic_cornstack_python_v1 |
function toHTML self pathogenPanelFilename=none minProteinFraction=0.0 pathogenType=string viral sampleIndexFilename=none pathogenIndexFilename=none
begin
string Produce an HTML string representation of the pathogen summary. @param pathogenPanelFilename: If not C{None}, a C{str} filename to write a pathogen panel PNG i... | def toHTML(self, pathogenPanelFilename=None, minProteinFraction=0.0,
pathogenType='viral', sampleIndexFilename=None,
pathogenIndexFilename=None):
"""
Produce an HTML string representation of the pathogen summary.
@param pathogenPanelFilename: If not C{None}, a C{st... | Python | jtatman_500k |
import requests
import re
from bs4 import BeautifulSoup
import time
import multiprocessing as mp
from urllib.request import urljoin
set base_url = string https://morvanzhou.github.io/
function crawl url
begin
comment time.sleep(1)
set html = get requests url
return decode content
end function
function parse html
begin
... | import requests
import re
from bs4 import BeautifulSoup
import time
import multiprocessing as mp
from urllib.request import urljoin
base_url = "https://morvanzhou.github.io/"
def crawl(url):
# time.sleep(1)
html = requests.get(url)
return html.content.decode()
def parse(html):
bsObj = BeautifulSoup(... | Python | zaydzuhri_stack_edu_python |
function test_cx_gate_nondeterministic_default_basis_gates self
begin
set shots = 2000
set circuits = call cx_gate_circuits_nondeterministic final_measure=true
set targets = call cx_gate_counts_nondeterministic shots
set job = execute circuits call QasmSimulator shots=shots
set result = call result
call is_completed re... | def test_cx_gate_nondeterministic_default_basis_gates(self):
shots = 2000
circuits = ref_2q_clifford.cx_gate_circuits_nondeterministic(final_measure=True)
targets = ref_2q_clifford.cx_gate_counts_nondeterministic(shots)
job = execute(circuits, QasmSimulator(), shots=shots)
result... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
from pandas import DataFrame , Series
import matplotlib.pyplot as plot
import pandas as pd
import numpy as np
if __name__ == string __main__
begin
comment 时间序列绘图
set close_px_all = read csv string ./data/stock_px.csv parse_dates=true index_col=0
set close_px = close_px_all at list string AAPL strin... | # coding=utf-8
from pandas import DataFrame, Series
import matplotlib.pyplot as plot
import pandas as pd
import numpy as np
if __name__ == '__main__':
## 时间序列绘图
close_px_all = pd.read_csv('./data/stock_px.csv', parse_dates=True, index_col=0)
close_px = close_px_all[['AAPL', 'MSFT', 'XOM']]
close_px = ... | Python | zaydzuhri_stack_edu_python |
function dict_to_namespace dct
begin
set namespace = call Namespace
for tuple key value in items dct
begin
set name = right strip key string _
if is instance value dict and not ends with key string _
begin
set attribute namespace name call dict_to_namespace value
end
else
begin
set attribute namespace name value
end
en... | def dict_to_namespace(dct):
namespace = Namespace()
for key, value in dct.items():
name = key.rstrip("_")
if isinstance(value, dict) and not key.endswith("_"):
setattr(namespace, name, dict_to_namespace(value))
else:
setattr(namespace, name, value)
return name... | Python | nomic_cornstack_python_v1 |
from ValidationError import ValidationError
class ClienteValidador
begin
function validar self cliente
begin
if not cpf
begin
raise ValidationError
end
end function
end class | from .ValidationError import ValidationError
class ClienteValidador:
def validar(self, cliente):
if not(cliente.cpf):
raise ValidationError | Python | zaydzuhri_stack_edu_python |
function test_make_field__no_items self
begin
set result = call make_field call Mock call Mock list env=call Mock
assert equal string Arguments call astext
end function | def test_make_field__no_items(self):
result = self.chpl_args().make_field(mock.Mock(), mock.Mock(), [],
env=mock.Mock())
self.assertEqual('Arguments\n\n', result.astext()) | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
function r8vec_binary_next n bvec
begin
comment *****************************************************************************80
comment R8VEC_BINARY_NEXT generates the next binary vector.
comment Discussion:
comment The vectors have the order
comment (0,0,...,0),
comment (0,0,...,1),
comme... | #! /usr/bin/env python
#
def r8vec_binary_next ( n, bvec ):
#*****************************************************************************80
#
## R8VEC_BINARY_NEXT generates the next binary vector.
#
# Discussion:
#
# The vectors have the order
#
# (0,0,...,0),
# (0,0,...,1),
# ...
# (1,1,...,1... | Python | zaydzuhri_stack_edu_python |
function win_path_basename path
begin
return split right strip path string \ string \ at - 1
end function | def win_path_basename(path: str) -> str:
return path.rstrip('\\').split('\\')[-1] | Python | nomic_cornstack_python_v1 |
function date_range start end delta_days=1 return_as_strings=false
begin
if end < start
begin
raise call ValueError string end date minor than start date.. Maybe you want to swap them? [ + string start + string , + string end + string ]
end
if call is_string start
begin
set start = call str_to_date start
end
if call is... | def date_range(start, end, delta_days=1, return_as_strings=False):
if end < start:
raise ValueError(
"end date minor than start date.. Maybe you want to swap them? [" + str(start) + ", " + str(end) + "]")
if is_string(start):
start = str_to_date(start)
if is_string(end):
... | Python | nomic_cornstack_python_v1 |
function translate
begin
global sequence
set n = length sequence / 3
set sequence_protein = string
for i in range 0 n
begin
set code = sequence at slice i * 3 : i * 3 + 3 :
set sequence_protein = sequence_protein + tranalate_code at code
end
return sequence_protein
end function | def translate():
global sequence
n = len(sequence) / 3
sequence_protein = ''
for i in range(0, n):
code = sequence[i * 3 : i * 3 + 3]
sequence_protein = sequence_protein + tranalate_code[code]
return sequence_protein | Python | nomic_cornstack_python_v1 |
string 假设一个团队里有 5 名学员,成绩如下表所示。 你可以用 NumPy 统计下这些人在语文、英语、数学中的平均成绩、最小成绩、最大成绩、方差、标准差。 然后把这些人的总成绩排序,得出名次进行成绩输出。 姓名 语文 英语 数学 张飞 66 65 30 关羽 95 85 98 赵云 93 92 96 黄忠 90 88 77 典韦 80 90 90
import numpy as np
set stu_type = call dtype dict string names list string name string chinese string english string math ; string formats li... | """
假设一个团队里有 5 名学员,成绩如下表所示。
你可以用 NumPy 统计下这些人在语文、英语、数学中的平均成绩、最小成绩、最大成绩、方差、标准差。
然后把这些人的总成绩排序,得出名次进行成绩输出。
姓名 语文 英语 数学
张飞 66 65 30
关羽 95 85 98
赵云 93 92 96
黄忠 90 88 77
典韦 80 90 90
"""
import numpy as np
stu_type = np.dtype({
'names': ['name', 'chinese', 'english', '... | Python | zaydzuhri_stack_edu_python |
function add_slider self title row column row_span=1 column_span=1 padx=1 pady=0 min_val=0 max_val=100 step=1 init_val=0
begin
set id = format string Widget{} length keys _widgets
set new_slider = call SliderWidget id title _grid row column row_span column_span padx pady _logger min_val max_val step init_val
call _assi... | def add_slider(self, title, row, column, row_span=1,
column_span=1, padx=1, pady=0,
min_val=0, max_val=100, step=1, init_val=0) -> py_cui.controls.slider.SliderWidget:
id = 'Widget{}'.format(len(self._widgets.keys()))
new_slider = py_cui.controls.slider.SliderWidge... | Python | nomic_cornstack_python_v1 |
function fA self
begin
pass
end function | def fA(self):
pass | Python | nomic_cornstack_python_v1 |
function _filter_entries self entries
begin
set entries = call _filter_entries entries
if _filter_minimum_magnitude
begin
comment Return only entries that have an actual magnitude value, and
comment the value is equal or above the defined threshold.
return list filter lambda entry -> magnitude and magnitude >= _filter_... | def _filter_entries(self, entries):
entries = super()._filter_entries(entries)
if self._filter_minimum_magnitude:
# Return only entries that have an actual magnitude value, and
# the value is equal or above the defined threshold.
return list(
filter(
... | Python | nomic_cornstack_python_v1 |
function _get_or_create_a self _type
begin
string Gets or creates an instance of type <_type>
debug string get_or_create_a: %s % _type
set stack = list call GoCa_Plan self dict _type tuple
while stack
begin
set p = pop stack
if finished
begin
execute p
return call get_a _type
end
for c in call branches
begin
append sta... | def _get_or_create_a(self, _type):
""" Gets or creates an instance of type <_type> """
self.l.debug("get_or_create_a: %s" % _type)
stack = [Manager.GoCa_Plan(self, {_type: ()})]
while stack:
p = stack.pop()
if p.finished:
p.execute()
... | Python | jtatman_500k |
function create_template_metadata src_dir today source_quote_file=none
begin
set metadata = dict string date today ; string review_files call pick_random_files src_dir ; string is_weekday call is_weekday
if source_quote_file
begin
set metadata at string quote = call generate_quote source_quote_file
end
return metadata
... | def create_template_metadata(
src_dir: str, today: str, source_quote_file: Optional[str] = None
) -> Dict[str, Any]:
metadata = {
"date": today,
"review_files": pick_random_files(src_dir),
"is_weekday": is_weekday(),
}
if source_quote_file:
metadata["quote"] = generate_qu... | Python | nomic_cornstack_python_v1 |
function parse_create_course xml_course
begin
set attrs = list string term-code string term-description string subject string course-number string school string department string title string description string credit-hours string distribution-group
set course = call pull_attributes_from_xml xml_course attrs
set course... | def parse_create_course(xml_course):
attrs = [
"term-code",
"term-description",
'subject',
"course-number",
"school",
"department",
"title",
"description",
"credit-hours",
"distribution-group"
]
course = pull_attributes_from_xml(xml_course, attrs)
course["sections"] = []
... | Python | nomic_cornstack_python_v1 |
comment ret=txt[::2] 홀수번째 항들만 추출할 때
print ret | # ret=txt[::2] 홀수번째 항들만 추출할 때
print(ret)
| Python | zaydzuhri_stack_edu_python |
function test_get_all_assets_df_true_with_asset_fields
begin
set asset_fields = list string metrics
assert is instance call get_all_assets asset_fields=asset_fields to_dataframe=true DataFrame
end function | def test_get_all_assets_df_true_with_asset_fields():
asset_fields = ['metrics']
assert isinstance(get_all_assets(asset_fields=asset_fields, to_dataframe=True), DataFrame) | Python | nomic_cornstack_python_v1 |
import sys
comment Recordar que debemos transformar f a otra función g
comment Entradas del algoritmo
comment Esta es la función g
set g = lambda x -> 1 / 2 * 10 - x ^ 3 ^ 1 / 2
comment Aproximación inicial
set p0 = 1.5
comment Tolerancia o epsilon
set TOL = 9.3132e-10
comment Número de iteraciones
set N = 30
comment D... | import sys
# Recordar que debemos transformar f a otra función g
# Entradas del algoritmo
g = lambda x: (1/2)*(10 - x**3)**(1/2) # Esta es la función g
p0 = 1.5 # Aproximación inicial
TOL = 9.3132e-10 # Tolerancia o epsilon
N = 30 # Número de iteraciones
# Digitos de redondeo
digs = 4
rd = lambda a: round(a... | Python | zaydzuhri_stack_edu_python |
comment Given a sentence that consists of some words separated by a single space, and
comment a searchWord, check if searchWord is a prefix of any word in sentence.
comment Return the index of the word in sentence (1-indexed) where searchWord is a
comment prefix of this word. If searchWord is a prefix of more than one ... | # Given a sentence that consists of some words separated by a single space, and
# a searchWord, check if searchWord is a prefix of any word in sentence.
#
# Return the index of the word in sentence (1-indexed) where searchWord is a
# prefix of this word. If searchWord is a prefix of more than one word, return the ... | Python | zaydzuhri_stack_edu_python |
function _write_buffer_to_file self
begin
comment always on CPU
set buffer_tmp_bunch = dict
set buffer_tmp_slice = dict
set shift = - i_steps + 1 % buffer_size
for stats in bunch_stats_to_store
begin
try
begin
set buffer_tmp_bunch at stats = call roll get buffer_bunch at stats shift=shift axis=0
end
except any
begin
... | def _write_buffer_to_file(self):
buffer_tmp_bunch = {} # always on CPU
buffer_tmp_slice = {}
shift = - (self.i_steps + 1 % self.buffer_size)
for stats in self.bunch_stats_to_store:
try:
buffer_tmp_bunch[stats] = np.roll(self.buffer_bunch[stats].get(),
... | Python | nomic_cornstack_python_v1 |
function ranking_rprecision_score y_true y_score k=10
begin
set unique_y = unique y_true
if length unique_y == 1
begin
return call ValueError string The score cannot be approximated.
end
else
if length unique_y > 2
begin
raise call ValueError string Only supported for two relevance levels.
end
set pos_label = unique_y ... | def ranking_rprecision_score(y_true, y_score, k=10):
unique_y = np.unique(y_true)
if len(unique_y) == 1:
return ValueError("The score cannot be approximated.")
elif len(unique_y) > 2:
raise ValueError("Only supported for two relevance levels.")
pos_label = unique_y[1]
n_pos = np.su... | Python | nomic_cornstack_python_v1 |
function remove_from_lib self name
begin
string Remove an object from the bin folder.
call __remove_path join path root_dir string lib name
end function | def remove_from_lib(self, name):
""" Remove an object from the bin folder. """
self.__remove_path(os.path.join(self.root_dir, "lib", name)) | Python | jtatman_500k |
comment !/usr/bin/env python
comment -*-coding:utf-8 -*-
comment Warning :The Hard Way Is Easier
import os
import inspect
from pprint import pprint
comment 获取模块的帮助文档
comment help(os)
comment os模块内具有很多属性与方法,使用一行代码打印os模块下所有的方法名称
comment 参考文章: https://www.itranslater.com/qa/details/2110320005110825984
comment pprint(dir(o... | # !/usr/bin/env python
# -*-coding:utf-8 -*-
# Warning :The Hard Way Is Easier
import os
import inspect
from pprint import pprint
# 获取模块的帮助文档
# help(os)
# os模块内具有很多属性与方法,使用一行代码打印os模块下所有的方法名称
# 参考文章: https://www.itranslater.com/qa/details/2110320005110825984
# pprint(dir(os))
print(dir(os)) # 输出模块内所有属性名称、方法名称
# ... | Python | zaydzuhri_stack_edu_python |
for k in range length word
begin
set newword = word at slice - k : : + word at slice : - k :
print newword
end | for k in range(len(word)):
newword = (word[-k: ] + word[ :-k])
print(newword)
| Python | zaydzuhri_stack_edu_python |
comment Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
comment n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
comment Find two lines, which, together with the x-axis forms a container,
comment such that the container c... | # Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai).
# n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0).
# Find two lines, which, together with the x-axis forms a container,
# such that the container contains the most water.
... | Python | zaydzuhri_stack_edu_python |
import os
call system string clear
comment While Loops
comment make counter var
set counter = 0
while counter <= 10
begin
print string The count is + string counter
set counter = counter + 1
end | import os
os.system("clear")
#################################
# While Loops
#################################
#make counter var
counter = 0
while (counter <= 10):
print("The count is " + str(counter))
counter += 1
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
from CordinateStruct import CordinatesStruct
class Plan
begin
function __init__ self df
begin
set df = df
end function
function display_plan self
begin
print string --------Attraction List -------
print df at string name
print string -------------------------------
set df_num = length df
end functio... | import pandas as pd
from CordinateStruct import CordinatesStruct
class Plan:
def __init__(self, df, ):
self.df = df
def display_plan(self):
print("--------Attraction List -------")
print(self.df["name"])
print("-------------------------------")
df_num = len(self.df)
... | Python | zaydzuhri_stack_edu_python |
function test_implicit_tabulator_split self
begin
set transformer = call SplitTransformer
setup transformer string test dict string dateformat string %Y-%m-%d %H:%M:%S ; string group_order string HOST_NAME HOST_ADDRESS PRIORITY FACILITY TIME DATE MESSAGE
set teststring = string test_host 42.2.53.52 5 4 11:00:24 2012-12... | def test_implicit_tabulator_split(self):
transformer = SplitTransformer()
transformer.setup("test", {
"dateformat" : "%Y-%m-%d %H:%M:%S",
"group_order" : "HOST_NAME HOST_ADDRESS PRIORITY FACILITY TIME DATE MESSAGE"
})
teststring = "test_host\t42.2.53.52\t5\t4\t1... | Python | nomic_cornstack_python_v1 |
function testLogIntoClosedLogFile
begin
set testFile = TEST_LOG_FILE
for tuple met level in tuple tuple string warning WARNING tuple string warn WARNING tuple string fatal FATAL tuple string error ERROR tuple string debug DEBUG tuple string critical CRITICAL tuple string info INFO
begin
if exists path testFile
begin
se... | def testLogIntoClosedLogFile():
testFile = TEST_LOG_FILE
for met, level in (('warning', logging.WARNING),
('warn', logging.WARNING),
('fatal', logging.FATAL),
('error', logging.ERROR),
('debug', logging.DEB... | Python | nomic_cornstack_python_v1 |
string 1. Leer dataset "clase_6_dataset" 2. Aplicar Logistic Regresion 3. Hacer fit con y = w2 *x1 + w1 * x2 + 1 4. Graficar el resultado
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.model_selection im... | '''
1. Leer dataset "clase_6_dataset"
2. Aplicar Logistic Regresion
3. Hacer fit con y = w2 *x1 + w1 * x2 + 1
4. Graficar el resultado
'''
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.model_selection ... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
comment Define model class
comment Parent class
from tensorflow.keras import Model
import tensorflow_probability as tfp
set tfd = distributions
comment Libary for probability distributions in tensorflow
class gauss_reg extends Model
begin
functi... | import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
# Define model class
from tensorflow.keras import Model # Parent class
import tensorflow_probability as tfp
tfd = tfp.distributions
# Libary for probability distributions in tensorflow
class gauss_reg(Model):
def __init__(self, guesses... | Python | zaydzuhri_stack_edu_python |
function which program
begin
function is_exe fpath
begin
string is a regular file and is executable
return is file path fpath and call access fpath X_OK
end function
set tuple fpath _ = split path program
if fpath
begin
if call is_exe program
begin
return program
end
end
else
begin
for path in split environ at string P... | def which(program):
def is_exe(fpath):
"is a regular file and is executable"
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, _ = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os... | Python | nomic_cornstack_python_v1 |
function get_service self _id
begin
set job = call UpstartJob _id bus=bus
set svc = call Service self
set id = _id
set name = call __fix_name _id
try
begin
set state = call get_status at string state
set running = state == string running
end
except Exception as e
begin
set running = false
end
return svc
end function | def get_service(self, _id):
job = UpstartJob(_id, bus=self.bus)
svc = Service(self)
svc.id = _id
svc.name = self.__fix_name(_id)
try:
svc.state = job.get_status()['state']
svc.running = svc.state == 'running'
except Exception as e:
svc... | Python | nomic_cornstack_python_v1 |
function wait_until_displayed self locator timeout=5
begin
try
begin
call until call visibility_of_element_located locator
return true
end
except TimeoutException
begin
return false
end
end function | def wait_until_displayed(self, locator, timeout=5):
try:
WebDriverWait(self.browser, timeout).until(EC.visibility_of_element_located(locator))
return True
except ex.TimeoutException:
return False | Python | nomic_cornstack_python_v1 |
string Repositório para persistencia dos dados referentes ao Environment. Há implementação apenas para inserir, apagar e listar. Não há como atualizar os dados, se necessário usuário deve apagar e inserir um environment novo. Posteriormente pode-se implementar a atualização, mas não é algo tão necessário.
import json
i... | """
Repositório para persistencia dos dados referentes ao Environment.
Há implementação apenas para inserir, apagar e listar.
Não há como atualizar os dados, se necessário usuário deve apagar e inserir um environment novo.
Posteriormente pode-se implementar a atualização, mas não é algo tão necessário.
"""
import json
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
from math import sqrt
function _flip square
begin
return join string / list comprehension s at slice : : - 1 for s in split square string /
end function
function _rotate square
begin
set square = split square string /
set size = length square
return join str... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from math import sqrt
def _flip(square: str) -> str:
return '/'.join([ s[::-1] for s in square.split('/') ])
def _rotate(square: str) -> str:
square = square.split('/')
size = len(square)
return '/'.join([ ''.join([ square[c][r] for c in range(size - 1... | Python | zaydzuhri_stack_edu_python |
function main msg
begin
comment Extract the method into a dictionary
set msg_dict = loads decode call get_body string utf-8
info string Python ServiceBus queue trigger processed message: { msg_dict }
comment Enable a connection with the IoT Hub. The connectionstring for the IoT Hub
comment is preloaded in the Azure Fun... | def main(msg: func.ServiceBusMessage):
# Extract the method into a dictionary
msg_dict = json.loads(msg.get_body().decode("utf-8"))
logging.info(f"Python ServiceBus queue trigger processed message: {msg_dict}")
# Enable a connection with the IoT Hub. The connectionstring for the IoT Hub
#... | Python | nomic_cornstack_python_v1 |
comment a "basic" particle class (mostly used internally)
comment Copyright (C) 2018-2020, John Pormann, Duke University Libraries
import sys
import random
from copy import deepcopy
comment TODO: create a class method .dcopy() to do a deepcopy of data
comment but leave pointers to other arrays, etc
class BaseParticle e... | #
# a "basic" particle class (mostly used internally)
#
# Copyright (C) 2018-2020, John Pormann, Duke University Libraries
#
import sys
import random
from copy import deepcopy
# TODO: create a class method .dcopy() to do a deepcopy of data
# but leave pointers to other arrays, etc
class BaseParticle(object):
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.