code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function classifica_idade a
begin
if a <= 11
begin
return string crianca
end
else
if 12 <= a <= 17
begin
return string adolescente
end
end function | def classifica_idade(a):
if a <= 11:
return 'crianca'
elif 12 <= a <= 17:
return 'adolescente' | Python | zaydzuhri_stack_edu_python |
import pandas as pd
comment Create a dataframe from the input data
set df = call DataFrame list dict string customer_id 1 ; string month 1 ; string amount 40000 dict string customer_id 2 ; string month 1 ; string amount 10000 dict string customer_id 3 ; string month 1 ; string amount 20000 dict string customer_id 1 ; s... | import pandas as pd
# Create a dataframe from the input data
df = pd.DataFrame([
{"customer_id": 1, "month": 1, "amount": 40000},
{"customer_id": 2, "month": 1, "amount": 10000},
{"customer_id": 3, "month": 1, "amount": 20000},
{"customer_id": 1, "month": 2, "amount": 30000},
{"customer_id": 2, "mo... | Python | jtatman_500k |
for i in range 1 11
begin
print i * getal
end | for i in range(1,11):
print(i *getal) | Python | zaydzuhri_stack_edu_python |
function _pre_cancel_hook cls job_id cancel_message
begin
pass
end function | def _pre_cancel_hook(cls, job_id, cancel_message):
pass | Python | nomic_cornstack_python_v1 |
function center_barrier self verbose=false
begin
set tuple reactant_indicator product_indicator = call get_basin_indicators init_path
set n_react = sum reactant_indicator
set n_prod = sum product_indicator
set diff = absolute n_react - n_prod
set delta = integer diff / 2
set basin = string
if n_react > n_prod
begin
co... | def center_barrier( self, verbose=False ):
reactant_indicator, product_indicator = self.get_basin_indicators(self.init_path)
n_react = np.sum(reactant_indicator)
n_prod = np.sum(product_indicator)
diff = np.abs(n_react-n_prod)
delta = int(diff/2)
basin = ""
if ( n... | Python | nomic_cornstack_python_v1 |
function load_testdata collection_name testdata
begin
comment if testdata is a directory, then loop through directory
set files = list
if is directory path testdata
begin
for f in list directory testdata
begin
set p = string %s/%s % tuple testdata f
if string json in f and not is directory path p
begin
append files p
... | def load_testdata(collection_name, testdata):
# if testdata is a directory, then loop through directory
files = []
if os.path.isdir(testdata):
for f in os.listdir(testdata):
p = "%s/%s" % (testdata, f)
if "json" in f and not os.path.isdir(p): files.append(p)
elif os.pat... | Python | nomic_cornstack_python_v1 |
function verify_increasing arr
begin
if length arr < 2
begin
return false
end
set seen = set
set prev = arr at 0
for num in arr
begin
if num in seen or num <= prev
begin
return false
end
add seen num
set prev = num
end
return true
end function
set arr = list 2 3 5 10 15
comment Output: True
print call verify_increasing... | def verify_increasing(arr):
if len(arr) < 2:
return False
seen = set()
prev = arr[0]
for num in arr:
if num in seen or num <= prev:
return False
seen.add(num)
prev = num
return True
arr = [2, 3, 5, 10, 15]
print(verify_increasing(arr)) # Outpu... | Python | jtatman_500k |
set input_str = call raw_input string Enter some text:
set input_str = replace input_str string a string 4
set input_str = replace input_str string b string 8
set input_str = replace input_str string e string 3
set input_str = replace input_str string l string 1
set input_str = replace input_str string o string 0
set i... | input_str = raw_input("Enter some text: ")
input_str = input_str.replace("a", "4")
input_str = input_str.replace("b", "8")
input_str = input_str.replace("e", "3")
input_str = input_str.replace("l", "1")
input_str = input_str.replace("o", "0")
input_str = input_str.replace("s", "5")
input_str = input_str.replace("t", "... | Python | zaydzuhri_stack_edu_python |
function main
begin
comment The X's represent the boundaries of the maze.
comment Reaching state G results in a reward of +1.
comment Reaching state E results in a reward of -1.
comment 4 x 3 maze.
set grid = list string XXXXXX string X GX string X X EX string X X string XXXXXX
comment 10 x 8 maze.
set grid2 = list str... | def main():
# The X's represent the boundaries of the maze.
# Reaching state G results in a reward of +1.
# Reaching state E results in a reward of -1.
grid = [ # 4 x 3 maze.
"XXXXXX",
"X GX",
"X X EX",
"X X",
"XXXXXX"
]
grid2 = [ # 10 x 8 maze.
... | Python | nomic_cornstack_python_v1 |
function to_vector text model idf is_tokenized=false
begin
comment splits the text by space and returns a list of words
if not is_tokenized
begin
set text = split text
end
comment creates an empty vector of 300 dimensions
set vec = zeros 300
comment iterates over the sentence
for word in text
begin
comment checks if th... | def to_vector(text, model, idf, is_tokenized=False):
if not is_tokenized: text= text.split() # splits the text by space and returns a list of words
vec = np.zeros(300) # creates an empty vector of 300 dimensions
for word in text: # iterates over the sentence
if (word in model) & (word in idf): # che... | Python | nomic_cornstack_python_v1 |
function test_no_optionals self
begin
set data = valid_payload
del data at string telephone
del data at string cellphone
del data at string activity_description
del data at string about
del data at string institute
set response = post reverse string contacts data=dumps data content_type=string application/json
assert e... | def test_no_optionals(self):
data = self.valid_payload
del data["telephone"]
del data["cellphone"]
del data["activity_description"]
del data["about"]
del data["institute"]
response = self.client.post(
reverse('contacts'),
data=json.dumps(da... | Python | nomic_cornstack_python_v1 |
function parse_date year datetimestr
begin
set dt = join string / tuple string year datetimestr
return string parse time dt string %Y/%d/%m%Hh%M
end function | def parse_date(year, datetimestr):
dt = '/'.join((str(year), datetimestr))
return datetime.strptime(dt, "%Y/%d/%m%Hh%M") | Python | nomic_cornstack_python_v1 |
class Monitor
begin
string The mouse of the computer.
function __init__ self resolution
begin
set __resolution = resolution
end function
function resolution self
begin
string A helper function the will return the resolution of the monitor. :return: The screen resolution. :rtype: str
return __resolution
end function
fun... | class Monitor:
"""
The mouse of the computer.
"""
def __init__(self, resolution: str) -> None:
self.__resolution = resolution
def resolution(self) -> str:
"""
A helper function the will return the resolution of the monitor.
:return: The screen resolution.
:... | Python | zaydzuhri_stack_edu_python |
comment import modules
import numpy as np
import matplotlib as mpl
call use string Agg
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
class MidpointNormalize extends Normalize
begin
function __init__ self vmin=none vmax=none midpoint=none clip=true
begin
set midpoint = midpoint
call __init__ se... | #########################################################################
#import modules
#########################################################################
import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
class MidpointNormalize... | Python | zaydzuhri_stack_edu_python |
while n < 100
begin
set c = l + n
print c
set n = l
set l = c
end | while n<100:
c=l+n
print(c)
n=l
l=c | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
comment 通过torch.hub(pytorch中专注于迁移学的工具)获得已经训练好的bert-base-chinese模型
set model = load hub string huggingface/pytorch-transformers string model string bert-base-chinese
comment 获得对应的字符映射器, 它将把中文的每个字映射成一个数字
set tokenizer = load hub string huggingface/pytorch-transformers string tokenizer s... | import torch
import torch.nn as nn
# 通过torch.hub(pytorch中专注于迁移学的工具)获得已经训练好的bert-base-chinese模型
model = torch.hub.load('huggingface/pytorch-transformers', 'model', 'bert-base-chinese')
# 获得对应的字符映射器, 它将把中文的每个字映射成一个数字
tokenizer = torch.hub.load('huggingface/pytorch-transformers', 'tokenizer', 'bert-base-chinese'... | Python | zaydzuhri_stack_edu_python |
import speech_recognition as sr
import moviepy.editor as mp
import os
comment Function to convert
comment Pass in the path to the file
function extract file_name
begin
set r = call Recognizer
set clip = call VideoFileClip file_name
set conv_file = string audio
call write_audiofile string audio.wav
with call AudioFile s... | import speech_recognition as sr
import moviepy.editor as mp
import os
# Function to convert
# Pass in the path to the file
def extract(file_name):
r=sr.Recognizer()
clip=mp.VideoFileClip(file_name)
conv_file="audio"
clip.audio.write_audiofile("audio.wav")
with sr.AudioFile("au... | Python | zaydzuhri_stack_edu_python |
function TSSError self layerName
begin
return call TSSError
end function | def TSSError(self, layerName):
return self.getLayer(layerName).TSSError() | Python | nomic_cornstack_python_v1 |
comment Create the two lists
set l1 = set literal string I string You string And string The
set l2 = list string How string I string About string You
comment Find elements that are in second but not in first
set new = set l2 - set l1
comment Create the new list using list concatenation
set l = list new
print l
set a_fi... | # Create the two lists
l1 = {"I", "You", "And","The"}
l2 = ["How", "I", "About", "You"]
# Find elements that are in second but not in first
new = set(l2) - set(l1)
# Create the new list using list concatenation
l = list(new)
print(l)
a_file = open("stop_words.txt", "r")
list_of_lists = []
for line in a_file:
strip... | Python | zaydzuhri_stack_edu_python |
import argparse
import os
import glob
from PIL import Image
import sys
try
begin
import numpy as np
import pyfits as pf
import scipy.ndimage as nd
import pylab as pl
import os
import heapq
from scipy.optimize import leastsq
end
except ImportError
begin
print
string Error: missing one of the libraries (numpy, pyfits, sc... | import argparse
import os
import glob
from PIL import Image
import sys
try:
import numpy as np
import pyfits as pf
import scipy.ndimage as nd
import pylab as pl
import os
import heapq
from scipy.optimize import leastsq
except ImportError:
print
'Error: missing one of the libraries ... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from random import randrange
from time import sleep
from math import floor
set window_width = 540
set window_height = 540
comment 460
set canvas_width = window_width - 80
comment 460
set canvas_height = window_height - 80
set dimension = 21
comment #d4d4d4 = alive
comment #2b2b2b = dead
class conw... | from tkinter import *
from random import randrange
from time import sleep
from math import floor
window_width = 540
window_height = 540
canvas_width = (window_width - 80) # 460
canvas_height = (window_height - 80) # 460
dimension = 21
# #d4d4d4 = alive
# #2b2b2b = dead
class conway:
def __init__(self, root):
... | Python | zaydzuhri_stack_edu_python |
import pickle
import random
from recipe import Recipe
class Vegetarian extends Recipe
begin
function __init__ self url
begin
call __init__ self url
set name = name + string (Transformed to Vegetarian)
comment load scraped data:
comment 4 pages of vegetarian protein recipes
comment 6 pages of meat recipes
comment 2 page... | import pickle
import random
from recipe import Recipe
class Vegetarian(Recipe):
def __init__(self, url):
Recipe.__init__(self, url)
self.name += ' (Transformed to Vegetarian)'
# load scraped data:
# 4 pages of vegetarian protein recipes
# 6 pages of meat recipes
# ... | Python | zaydzuhri_stack_edu_python |
function test_decorator_no_exc self fc event_loop
begin
decorator call count_exceptions fc
function func
begin
yield from sleep 0.0
return 42
end function
assert 42 == yield from call func
assert 0 == _val
end function | def test_decorator_no_exc(self, fc, event_loop):
@aio.count_exceptions(fc)
def func():
yield from asyncio.sleep(0.0)
return 42
assert 42 == (yield from func())
assert 0 == fc._val | Python | nomic_cornstack_python_v1 |
function get_name self
begin
return call x509_extension_get_name x509_ext
end function | def get_name(self):
return m2.x509_extension_get_name(self.x509_ext) | Python | nomic_cornstack_python_v1 |
comment menu system for classifier
import numpy as np
import random
import generator as gener
from cvxopt import solvers
class classifier
begin
function __init__ self rand=none dim=2 threshold=0
begin
set gen = call generator
set dim = dim
set threshold = 0
if rand == none
begin
set weights = call create_weights dim
en... | # menu system for classifier
import numpy as np
import random
import generator as gener
from cvxopt import solvers
class classifier():
def __init__(self, rand=None, dim=2, threshold=0):
gen = gener.generator()
self.dim = dim
self.threshold = 0
if rand == None:
self.wei... | Python | zaydzuhri_stack_edu_python |
comment import the necessary packages
import numpy as np
import argparse
import cv2
import os
import sys
from flask import Flask , flash , jsonify , request , redirect , url_for , render_template
from flask_cors import CORS , cross_origin
from werkzeug.utils import secure_filename
import urllib
import urllib.request
co... | # import the necessary packages
import numpy as np
import argparse
import cv2
import os
import sys
from flask import Flask, flash, jsonify, request, redirect, url_for, render_template
from flask_cors import CORS, cross_origin
from werkzeug.utils import secure_filename
import urllib
import urllib.request
# METHOD #1: ... | Python | zaydzuhri_stack_edu_python |
class Class
begin
set Var = 1
function __init__ self val
begin
set Var = val
end function
end class
print __dict__
print string -------------------------
set object = call Class 2
print __dict__
print string -------------------------
print __dict__ | class Class:
Var = 1
def __init__(self, val):
self.Var = val
print(Class.__dict__)
print("-------------------------")
object = Class(2)
print(Class.__dict__)
print("-------------------------")
print(object.__dict__)
| Python | zaydzuhri_stack_edu_python |
function func x
begin
return power x 3 - 3 * x + 1
end function
comment Here return the value of the function
print string This is The Main Bisection Equation
print string [1;32mX^3 + 3X + 1
set Xo = decimal input string Enter the First Interval Value to the root!
set X1 = decimal input string Enter the Second Interva... | def func(x):
return pow(x, 3) - 3 * x + 1
# Here return the value of the function
print('This is The Main Bisection Equation')
print('\033[1;32mX^3 + 3X + 1')
Xo = float(input('Enter the First Interval Value to the root! '))
X1 = float(input('Enter the Second Interval Value to the root! '))
iter = int... | Python | zaydzuhri_stack_edu_python |
function maxi n m
begin
return n * m - 1 + m * n - 1
end function
set ANS = list
set T = integer input
for l in range T
begin
set tuple N M = map int split input
append ANS call maxi N M
end
for a in ANS
begin
print a
end | def maxi(n, m):
return n*(m-1) + m*(n-1)
ANS = []
T = int(input())
for l in range(T):
N, M = map(int, input().split())
ANS.append(maxi(N, M))
for a in ANS:
print(a)
| Python | zaydzuhri_stack_edu_python |
import subprocess
import pipes
import multiprocessing
import os
set OUTPUTS_DIR = string ./tester/out
set SCORES_DIR = string ./tester/scores
set CASE = 150
set TL = 6.0
function execute_case seed
begin
set input_file_path = string tools/in/ { seed } .txt
with open input_file_path as fin
begin
set output = string { OUT... | import subprocess
import pipes
import multiprocessing
import os
OUTPUTS_DIR = './tester/out'
SCORES_DIR = './tester/scores'
CASE = 150
TL = 6.0
def execute_case(seed):
input_file_path = f'tools/in/{seed:04}.txt'
with open(input_file_path) as fin:
output = f'{OUTPUTS_DIR}/out_{seed:04}'
with pipes.Template().op... | Python | zaydzuhri_stack_edu_python |
function setOutFile self outFilePath
begin
if not exists path directory name path outFilePath
begin
call logger string Could not set outfile path to '%s', % outFilePath + string parent directory does not exist! string error
return false
end
set outFilePath = absolute path path string %s % outFilePath
return false
end f... | def setOutFile(self,outFilePath):
if not os.path.exists(os.path.dirname(outFilePath)):
self.logger("Could not set outfile path to '%s'," % outFilePath
+ "parent directory does not exist!", "error")
return False
self.outFilePath = os.path.abspath(u"%s" % outFilePath)
return False | Python | nomic_cornstack_python_v1 |
function fetch_trial_data self trial **kwargs
begin
try
begin
if multiprocessing
begin
with pool processes=min length arms MAX_NUM_PROCESSES as pool
begin
set records = map deep copy evaluate_arm arms
close pool
end
end
else
begin
set records = list map evaluate_arm arms
end
if is instance records at 0 list
begin
comme... | def fetch_trial_data(self, trial: BaseTrial, **kwargs: Any) -> MetricFetchResult:
try:
if self.multiprocessing:
with Pool(processes=min(len(trial.arms), MAX_NUM_PROCESSES)) as pool:
records = pool.map(copy.deepcopy(self.evaluate_arm), trial.arms)
... | Python | nomic_cornstack_python_v1 |
async function hangman self ctx
begin
set inst = get games id none
if inst is none
begin
set inst = call HangmanGame
set games at id = inst
await call send string A hangman game has started!
end
await call show_game ctx
end function | async def hangman(self, ctx):
inst = self.games.get(ctx.channel.id, None)
if inst is None:
inst = HangmanGame()
self.games[ctx.channel.id] = inst
await ctx.send("A hangman game has started!")
await inst.show_game(ctx) | Python | nomic_cornstack_python_v1 |
import random
class Problem
begin
function __init__ self processing_time_first_dose processing_time_second_dose gap_between_doses
begin
comment assert that all input is valid
assert processing_time_first_dose >= 1
assert processing_time_second_dose >= 1
assert gap_between_doses >= 0
set processing_time_first_dose = pro... | import random
class Problem:
def __init__(self, processing_time_first_dose, processing_time_second_dose, gap_between_doses):
# assert that all input is valid
assert processing_time_first_dose >= 1
assert processing_time_second_dose >= 1
assert gap_between_doses >= 0
self.p... | Python | zaydzuhri_stack_edu_python |
string Plot your time series on individual plots It can be beneficial to plot individual time series on separate graphs as this may improve clarity and provide more context around each time series in your DataFrame. It is possible to create a "grid" of individual graphs by "faceting" each time series by setting the sub... | '''
Plot your time series on individual plots
It can be beneficial to plot individual time series on separate graphs as this may improve clarity and provide more context around each time series in your DataFrame.
It is possible to create a "grid" of individual graphs by "faceting" each time series by setting the subp... | Python | zaydzuhri_stack_edu_python |
function SyntaxTreeContextEvaluator self SyntaxTreeStructure
begin
if SyntaxTreeStructure
begin
if length childs > 0
begin
for leaf in childs
begin
if leaf != string ;
begin
if p_type == string Block
begin
if p_type == string Declare
begin
set actual_scope = actual_scope + 1
end
call SyntaxTreeContextEvaluator leaf
if ... | def SyntaxTreeContextEvaluator(self, SyntaxTreeStructure):
if SyntaxTreeStructure:
if (len(SyntaxTreeStructure.childs) > 0):
for leaf in SyntaxTreeStructure.childs:
if(leaf != ';'):
if(leaf.p_type == 'Block'):
... | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import requests
function find_tags_count link *tags
begin
try
begin
set page = get requests link
end
except any
begin
return dict string status string cant find such website, make sure site URL was entered correctly
end
set soup = call BeautifulSoup content string html.parser
if tags
begin... | from bs4 import BeautifulSoup
import requests
def find_tags_count(link, *tags):
try:
page = requests.get(link)
except:
return {
'status': 'cant find such website, make sure site URL was entered correctly '
}
soup = BeautifulSoup(page.content, "html.parser")
if tag... | Python | zaydzuhri_stack_edu_python |
function test_login_to_see_meterdetails self
begin
set meter = call create meter_name=string testmeter meter_unit=string X
save
call login username=string testuser password=string q2w3E$R%
set url = reverse string api_v1:meter-detail args=list 1
set response = get client url follow=true
assert equal status_code 200
cal... | def test_login_to_see_meterdetails(self):
meter = Meter.objects.create(meter_name='testmeter', meter_unit='X')
meter.save()
self.client.login(username='testuser', password='q2w3E$R%')
url = reverse('api_v1:meter-detail', args=[1])
response = self.client.get(url, follow=True)
... | Python | nomic_cornstack_python_v1 |
function rate_to_mcs rate bw=20 long_gi=true
begin
string Convert bit rate to MCS index. Args: rate (float): bit rate in Mbps bw (int): bandwidth, 20, 40, 80, ... long_gi (bool): True if long GI is used. Returns: mcs (int): MCS index >>> rate_to_mcs(120, bw=40, long_gi=False) 5
if bw not in list 20 40 80 160
begin
rais... | def rate_to_mcs(rate, bw=20, long_gi=True):
"""Convert bit rate to MCS index.
Args:
rate (float): bit rate in Mbps
bw (int): bandwidth, 20, 40, 80, ...
long_gi (bool): True if long GI is used.
Returns:
mcs (int): MCS index
>>> rate_to_mcs(120, bw=40, long_gi=False)
... | Python | jtatman_500k |
function set_checkpoint self binary_hash engine_name checkpoint_name checkpoint_time=none
begin
call set_checkpoint binary_hash engine_name checkpoint_name checkpoint_time
end function | def set_checkpoint(self, binary_hash, engine_name, checkpoint_name, checkpoint_time=None):
self._persistor.set_checkpoint(binary_hash, engine_name, checkpoint_name, checkpoint_time) | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
import pandas as pd
comment Opening Chrome
set driver = call Chrome
comment Going to a e-commerce website
get driver string https://webscraper.io/test-sites/e-commerce/static/
comment Getting the computers element and ... | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
import pandas as pd
# Opening Chrome
driver = webdriver.Chrome()
# Going to a e-commerce website
driver.get("https://webscraper.io/test-sites/e-commerce/static/")
# Getting the computers element and clicking it
driv... | Python | zaydzuhri_stack_edu_python |
function image_height self image_height
begin
set _image_height = image_height
end function | def image_height(self, image_height):
self._image_height = image_height | Python | nomic_cornstack_python_v1 |
function batched_nms boxes scores idxs nms_cfg class_agnostic=false
begin
set nms_cfg_ = copy nms_cfg
if class_agnostic
begin
set boxes_for_nms = boxes
end
else
begin
set max_coordinate = max
set offsets = to idxs boxes * max_coordinate + to tensor 1 boxes
set boxes_for_nms = boxes + offsets at tuple slice : : none
... | def batched_nms(boxes, scores, idxs, nms_cfg, class_agnostic=False):
nms_cfg_ = nms_cfg.copy()
if class_agnostic:
boxes_for_nms = boxes
else:
max_coordinate = boxes.max()
offsets = idxs.to(boxes) * (max_coordinate + torch.tensor(1).to(boxes))
boxes_for_nms = boxes + offsets[... | Python | nomic_cornstack_python_v1 |
function angle self vec2
begin
if type vec2 != Vector
begin
raise call TypeError string Not a vector
end
from math import acos
return call acos dot vec2 / call magnitude * call magnitude
end function | def angle(self, vec2):
if type(vec2) != Vector:
raise TypeError("Not a vector")
from math import acos
return acos(self.dot(vec2) / (self.magnitude() * vec2.magnitude())) | Python | nomic_cornstack_python_v1 |
function build_definitions_example self
begin
string Parse all definitions in the swagger specification.
for tuple def_name def_spec in items get specification string definitions dict
begin
call build_one_definition_example def_name
end
end function | def build_definitions_example(self):
"""Parse all definitions in the swagger specification."""
for def_name, def_spec in self.specification.get('definitions', {}).items():
self.build_one_definition_example(def_name) | Python | jtatman_500k |
function candidate_decider rcand lcand lcand_valid triangulation
begin
set pt1 = points at dest
set pt2 = points at org
set pt3 = points at org
set pt4 = points at dest
set result = lcand_valid and call in_circle pt1 pt2 pt3 pt4
return result
end function | def candidate_decider(rcand, lcand, lcand_valid, triangulation):
pt1 = triangulation.points[triangulation.edges[rcand].dest]
pt2 = triangulation.points[triangulation.edges[rcand].org]
pt3 = triangulation.points[triangulation.edges[lcand].org]
pt4 = triangulation.points[triangulation.edges[lcand].dest]
... | Python | nomic_cornstack_python_v1 |
function plot_field x y u name image_path
begin
set tuple fig ax = call subplots
x label string $x$
y label string $y$
set tuple X Y = call meshgrid x y
set levels = linear space min max 10
set cont = call contourf X Y u levels=levels extend=string both cmap=jet
set cont_bar = call colorbar cont label=format string {} ... | def plot_field(x, y, u, name, image_path):
fig, ax = pyplot.subplots()
pyplot.xlabel('$x$')
pyplot.ylabel('$y$')
X, Y = numpy.meshgrid(x, y)
levels = numpy.linspace(u.min(), u.max(), 10)
cont = pyplot.contourf(X, Y, u,
levels=levels, extend='both', cmap=cm.jet)
cont_bar = fig.col... | Python | nomic_cornstack_python_v1 |
function tunnel1_enable_tunnel_lifecycle_control self
begin
return get pulumi self string tunnel1_enable_tunnel_lifecycle_control
end function | def tunnel1_enable_tunnel_lifecycle_control(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "tunnel1_enable_tunnel_lifecycle_control") | Python | nomic_cornstack_python_v1 |
function _install_elasticsearch
begin
run string wget -qO - http://packages.elasticsearch.org/GPG-KEY-elasticsearch | sudo apt-key add -
run string echo -e 'deb http://packages.elasticsearch.org/elasticsearch/1.7/debian stable main ' | sudo tee -a /etc/apt/sources.list.d/elasticsearch-1.7.list
call sudo string apt-get ... | def _install_elasticsearch():
run('wget -qO - http://packages.elasticsearch.org/GPG-KEY-elasticsearch |'
' sudo apt-key add -')
run("echo -e "
"'deb http://packages.elasticsearch.org/elasticsearch/1.7/debian "
"stable main\n' | sudo tee -a "
"/etc/apt/sources.list.d/elasticsearch... | Python | nomic_cornstack_python_v1 |
comment 1. 定义一个父类初始化几个属性(属性自定义),定义一个子类继承父类的属性,并添加一些属性,在子类定义一个方法,打印出子类所有属性
class Fruit
begin
set color = string red
set taste = string sweet
end class
class Round extends Fruit
begin
set shape = string round
function inquire self
begin
print color taste shape
end function
end class
set apple = round
call inquire
comment... | # 1. 定义一个父类初始化几个属性(属性自定义),定义一个子类继承父类的属性,并添加一些属性,在子类定义一个方法,打印出子类所有属性
class Fruit:
color = 'red'
taste = 'sweet'
class Round(Fruit):
shape = 'round'
def inquire(self):
print(self.color,self.taste,self.shape)
apple = Round()
apple.inquire()
#2. 定义一个父类Computer,定义一个子类继承该父类,添加电脑品牌属性,重写颜色和价格属性,并打印... | Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render , redirect
from models import *
import bcrypt
from django.contrib import messages
comment from datetime import datetime
comment from time import strftime, strptime
comment Create your views here.
function index request
begin
return call render request string login-reg.html
end functi... | from django.shortcuts import render, redirect
from .models import *
import bcrypt
from django.contrib import messages
# from datetime import datetime
# from time import strftime, strptime
# Create your views here.
def index(request):
return render(request, 'login-reg.html')
def display_login(request):
... | Python | zaydzuhri_stack_edu_python |
function number bus_stops
begin
set people_in_bus = 0
for bus_stop in bus_stops
begin
set people_in_bus = people_in_bus + bus_stop at 0 - bus_stop at 1
end
return people_in_bus
end function
print call number list list 10 0 list 3 5 list 5 8
comment Number of people in the bus
comment There is a bus moving in the city, ... | def number(bus_stops):
people_in_bus = 0
for bus_stop in bus_stops:
people_in_bus += (bus_stop[0] - bus_stop[1])
return people_in_bus
print(number([[10,0],[3,5],[5,8]]))
# Number of people in the bus
# There is a bus moving in the city, and it takes and drop some people in each bus stop.
#
# You... | Python | zaydzuhri_stack_edu_python |
function create_controller app name
begin
set name = lower name
set file_dir = join path root_path string controllers
set root_dir_name = base name path root_path
if not exists path file_dir
begin
make directory call Path file_dir parents=true exist_ok=true
end
set file_name = string { name } .py
set class_name = call ... | def create_controller(app, name):
name = name.lower()
file_dir = os.path.join(app.root_path, "controllers")
root_dir_name = os.path.basename(app.root_path)
if not os.path.exists(file_dir):
pathlib.Path(file_dir).mkdir(parents=True, exist_ok=True)
file_name = f"{name}.py"
class_name = con... | Python | nomic_cornstack_python_v1 |
import random
function generate_dictionary n
begin
set dictionary = dict
comment Generate a list of unique random strings as keys
set keys = set
while length keys < n
begin
set key = join string random choices string abcdefghijklmnopqrstuvwxyz k=10
add keys key
end
comment Generate key-value pairs with random values
... | import random
def generate_dictionary(n):
dictionary = {}
# Generate a list of unique random strings as keys
keys = set()
while len(keys) < n:
key = ''.join(random.choices('abcdefghijklmnopqrstuvwxyz', k=10))
keys.add(key)
# Generate key-value pairs with random values
... | Python | greatdarklord_python_dataset |
function _at_value_calc self x=0
begin
set value = 0
for tuple i val in enumerate polynom_list
begin
set value = value + x ^ i * val
end
return value
end function | def _at_value_calc(self, x=0):
value = 0
for i, val in enumerate(self.polynom_list):
value = value + x**i*val
return value | Python | nomic_cornstack_python_v1 |
comment Python 3.5.2
set list1 = list string Google string Runoob 1997 2000
set list2 = list 1 2 3 4 5 6 7
set list3 = list string a string b string c string d
comment 访问列表中的值
comment 列表索引从0开始
print string list1[0]: list1 at 0
print list2 at slice 2 : 5 :
comment 更新列表
comment 你可以对列表的数据项进行修改或更新
set list = list string Go... | # Python 3.5.2
list1 = ['Google', 'Runoob', 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
list3 = ["a", "b", "c", "d"];
# 访问列表中的值
print ("list1[0]: ", list1[0]) # 列表索引从0开始
print ( list2[2:5] )
# 更新列表
# 你可以对列表的数据项进行修改或更新
list = ['Google', 'Runoob', 1997, 2000];
print ("第三个元素为 : ", list[2])
list[2] = 2001
print ("更新后的第... | Python | zaydzuhri_stack_edu_python |
function ST_Touches a b
begin
return call _call_predicate_function string ST_Touches tuple a b
end function | def ST_Touches(a: ColumnOrName, b: ColumnOrName) -> Column:
return _call_predicate_function("ST_Touches", (a, b)) | Python | nomic_cornstack_python_v1 |
function default_allow_privilege_escalation self
begin
return get pulumi self string default_allow_privilege_escalation
end function | def default_allow_privilege_escalation(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "default_allow_privilege_escalation") | Python | nomic_cornstack_python_v1 |
function model_pipeline_run index model params X_train y_train X_test y_test model_name pre_process_time type
begin
set n_jobs = - 1
set n_iter = 100
if model is none
begin
return
end
try
begin
set row = dict string dataset_index index
if type == string classification
begin
set steps = list tuple string classifier mode... | def model_pipeline_run(index, model, params, X_train, y_train, X_test, y_test, model_name, pre_process_time, type):
n_jobs = -1
n_iter = 100
if model is None:
return
try:
row = {"dataset_index": index}
if type == "classification":
steps = [("classifier", model)]
... | Python | nomic_cornstack_python_v1 |
function first_inhibitor self
begin
return firstInhibitor
end function | def first_inhibitor(self):
return self.data.firstInhibitor | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
function objective x y
begin
return x - 0.1 ^ 2 + y - 0.3 ^ 2 + sin x + 0.5 * 2 * sin y * 3 + sigmoid 4
end function
function sigmoid x
begin
set s = 1 / 1 + exp - x
return s
end function
set init_point = uniform - 0.1 0.1 2 - array list 1.5 1.5
print string init_point... | import numpy as np
import matplotlib.pyplot as plt
def objective(x, y):
return (x - 0.1) ** 2 + (y - 0.3) ** 2 + np.sin((x + 0.5) * 2) * np.sin(y * 3) + sigmoid(4)
def sigmoid(x):
s = 1 / (1 + np.exp(-x))
return s
init_point = np.random.uniform(-0.1, 0.1, 2) - np.array([1.5,1.5])
print("init_point",init_po... | Python | zaydzuhri_stack_edu_python |
import string , random
function password n
begin
set s = list printable at slice : 92 :
set check = false
while check == false
begin
set pas = list
extend pas random sample s plen
set check = any generator expression item in list ascii_lowercase for item in pas ? any generator expression item in list ascii_uppercase ... | import string, random
def password(n):
s=list(string.printable[:92])
check=False
while check==False:
pas= []
pas.extend(random.sample(s, plen))
check = any(item in list(string.ascii_lowercase) for item in pas) & any(item in list(string.ascii_uppercase) for item in pas) & any(item in list(string.digits) for it... | Python | zaydzuhri_stack_edu_python |
function getInstanceByName atom
begin
comment print "Getting instance of " + sanitize_symbol(atom.symbol)
set anchor_aam = aam
set standard_name = call sanitize_symbol symbol
set build_function = PSEUDO at standard_name at 0
set args = PSEUDO at standard_name at 1
return call build_function anchor_aam args
end function | def getInstanceByName(atom):
#print "Getting instance of " + sanitize_symbol(atom.symbol)
anchor_aam = atom.aam
standard_name = sanitize_symbol(atom.symbol)
build_function = PSEUDO[standard_name][0]
args = PSEUDO[standard_name][1]
return build_function(anchor_aam, args) | Python | nomic_cornstack_python_v1 |
function __init__ self dbhost=none dbuser=none dbpassword=none dbname=none cache_file=none
begin
comment Get database parameters
if dbhost is none
begin
set dbhost = get environ string PYTOKIO_LMT_HOST
end
if dbuser is none
begin
set dbuser = get environ string PYTOKIO_LMT_USER
end
if dbpassword is none
begin
set dbpas... | def __init__(self, dbhost=None, dbuser=None, dbpassword=None, dbname=None, cache_file=None):
# Get database parameters
if dbhost is None:
dbhost = os.environ.get('PYTOKIO_LMT_HOST')
if dbuser is None:
dbuser = os.environ.get('PYTOKIO_LMT_USER')
if dbpassword is No... | Python | nomic_cornstack_python_v1 |
function setup_remove_content_length monkeypatch enable=true
begin
if not enable
begin
return
end
comment type: ignore
function remove_content_length *args **kwargs
begin
string Mock function to remove `content-length` from response.
set response = call request string get *args timeout=pop kwargs string timeout 30 keyw... | def setup_remove_content_length(monkeypatch: pytest.MonkeyPatch, enable: bool = True) -> None:
if not enable:
return
def remove_content_length(*args, **kwargs): # type: ignore
"""Mock function to remove `content-length` from response."""
response = requests.request("get", *args, timeou... | Python | nomic_cornstack_python_v1 |
import numpy as np
set source_path = string /home/dmonk/Firmware/DTC-firmware/DTC-front/DTC-front.sim/sim_1/behav/modelsim/source.txt
set mif_path = string /home/dmonk/Firmware/DTC-firmware/DTC-front/mifs/
set bram_width = 18
class LogicVector
begin
string Class that simulates a VHDL std_logic_vector with a few extra u... | import numpy as np
source_path = "/home/dmonk/Firmware/DTC-firmware/" \
"DTC-front/DTC-front.sim/sim_1/behav/modelsim/source.txt"
mif_path = "/home/dmonk/Firmware/DTC-firmware/" \
"DTC-front/mifs/"
bram_width = 18
class LogicVector:
"""
Class that simulates a VHDL std_logic_vector... | Python | zaydzuhri_stack_edu_python |
from jsonFileHandler import JsonFileHandler
class ResultRepository extends object
begin
function __init__ self repository
begin
set _repository = repository
end function
function walkResults self
begin
for tuple dirname filename in walk
begin
if not starts with filename string result or not ends with filename string .j... | from jsonFileHandler import JsonFileHandler
class ResultRepository( object ):
def __init__( self, repository ):
self._repository = repository
def walkResults( self ):
for dirname, filename in self._repository.walk():
if not filename.startswith( 'result' ) or not filename.endswith( ... | Python | zaydzuhri_stack_edu_python |
function _collect_peptide_table peptide_table_filename
begin
set peptide_table = read csv peptide_table_filename sep=string , index_col=0 header=0
if name != string peptide_id
begin
raise ValueError
end
if dtype != string int64
begin
raise call ValueError string The index values for peptide_id must be inferred as integ... | def _collect_peptide_table(peptide_table_filename: str):
peptide_table = pd.read_csv(peptide_table_filename, sep=",", index_col=0, header=0)
if peptide_table.index.name != "peptide_id":
raise ValueError
if peptide_table.index.dtype != "int64":
raise ValueError("The index values for peptid... | Python | nomic_cornstack_python_v1 |
function forward self enc_out beam_size=16 nbest=8 lm_weight=0 len_norm=true
begin
set tuple N T D = shape
if N != 1
begin
raise call RuntimeError string Got batch size { N } , now only support one utterance
end
set vocab_size = vocab_size
if beam_size > vocab_size
begin
raise call RuntimeError string Beam size ( { bea... | def forward(self,
enc_out: th.Tensor,
beam_size: int = 16,
nbest: int = 8,
lm_weight: float = 0,
len_norm: bool = True) -> List[Dict]:
N, T, D = enc_out.shape
if N != 1:
raise RuntimeError(
f"Got ... | Python | nomic_cornstack_python_v1 |
function _get_object_to_check python_object
begin
if call ismodule python_object or call isclass python_object or call ismethod python_object or call isfunction python_object or call istraceback python_object or call isframe python_object or call iscode python_object
begin
return python_object
end
try
begin
return __cl... | def _get_object_to_check(python_object):
if (inspect.ismodule(python_object) or
inspect.isclass(python_object) or
inspect.ismethod(python_object) or
inspect.isfunction(python_object) or
inspect.istraceback(python_object) or
inspect.isframe(python_object) o... | Python | nomic_cornstack_python_v1 |
function converte_log_csv nome_arq_log nome_arq_csv=string dados.csv
begin
comment lê arquivo de log
set dados = call le_arquivo nome_arq_log
comment prepara campos
set f = open nome_arq_csv string w+
comment campos='x,y,theta,odom_x,odom_y,odom_theta\n'
comment f.write(campos)
close f
comment salva dados no novo arqui... | def converte_log_csv(nome_arq_log,nome_arq_csv='dados.csv'):
#lê arquivo de log
dados=le_arquivo(nome_arq_log)
#prepara campos
f=open(nome_arq_csv,'w+')
#campos='x,y,theta,odom_x,odom_y,odom_theta\n'
#f.write(campos)
f.close()
#salva dados no novo arquivo
grava_csv(dados,nome_arq_csv) | Python | nomic_cornstack_python_v1 |
function populate_search_index self
begin
call update_index_with simple_list_of_articles
end function | def populate_search_index(self):
self.update_index_with(self.simple_list_of_articles) | Python | nomic_cornstack_python_v1 |
function fetch_data_by_exchange fswym tsym exchange time_to time_frame=string hour
begin
set url = format string https://min-api.cryptocompare.com/data/histo{}?fsym={}&tsym={}&limit=2000&e={}&toTs={} time_frame fswym tsym exchange time_to
set response = get requests url
set soup = call BeautifulSoup content string html... | def fetch_data_by_exchange(fswym, tsym, exchange, time_to, time_frame="hour"):
url = "https://min-api.cryptocompare.com/data/histo{}?fsym={}&tsym={}&limit=2000&e={}&toTs={}".\
format(time_frame, fswym, tsym, exchange, time_to)
response = requests.get(url)
soup = BeautifulSoup(response.content, "html... | Python | nomic_cornstack_python_v1 |
comment 7)Hacer una función que retorne el mcm(mínimo común múltiplo)
comment de 2 números naturales mayores que 0 por el metodo de Euclides
comment Pre: n y m > 0 los numeros introducidos deben ser mayores que 0
comment Post: Entrega el mcm de ambos numeros
comment Complejidad = O(11) + O(6n)
comment Complejidad = O(6... | # 7)Hacer una función que retorne el mcm(mínimo común múltiplo)
# de 2 números naturales mayores que 0 por el metodo de Euclides
#
# Pre: n y m > 0 los numeros introducidos deben ser mayores que 0
# Post: Entrega el mcm de ambos numeros
#
# Complejidad = O(11) + O(6n)
# Complejidad = O(6n) por teorema 2, sin embargo e... | Python | zaydzuhri_stack_edu_python |
function test_gru_forward_and_back
begin
comment Setup
set hidden_len = 1
set input_len = 2
set weight_init_val = 0.5
set x = array list 0.02 - 0.3
set dh = array list 2.1
set init_function = lambda shape -> call full shape weight_init_val
set zero_init = lambda shape -> zeros shape
set gru = gru input_len hidden_len i... | def test_gru_forward_and_back():
# Setup
hidden_len = 1
input_len = 2
weight_init_val = 0.5
x = np.array([0.02, -0.3])
dh = np.array([2.1])
init_function = lambda shape: np.full(shape, weight_init_val)
zero_init = lambda shape : np.zeros(shape)
gru = vanilla_draw.Gru(input_len, hid... | Python | nomic_cornstack_python_v1 |
function __iter__ self
begin
return iterate handlers
end function | def __iter__(self):
return iter(self.handlers) | Python | nomic_cornstack_python_v1 |
import csv
from numpy import random
from numpy import linspace
from matplotlib import pyplot
import pandas as pd
if __name__ == string __main__
begin
set fieldnames = list string StartDate string EndDate string Status string IPAddress string Progress string Duration (in seconds) string Finished string RecordedDate stri... | import csv
from numpy import random
from numpy import linspace
from matplotlib import pyplot
import pandas as pd
if __name__ == "__main__":
fieldnames = ['StartDate', 'EndDate', 'Status', 'IPAddress', 'Progress', 'Duration (in seconds)', 'Finished',
'RecordedDate', 'ResponseId', 'RecipientLastName... | Python | zaydzuhri_stack_edu_python |
string Process GLoVe .txt files and create pickle files for embedding dictionaries
import sys
import pickle
class GloveVectors
begin
set GLOVE_SIZE = 200
function __init__ self file
begin
set file = file
set glove_embeddings = dict
set lib_path = string ../lib/glove/
end function
function make_embeddings self
begin
st... | """
Process GLoVe .txt files and create pickle files for embedding dictionaries
"""
import sys
import pickle
class GloveVectors:
GLOVE_SIZE = 200
def __init__(self, file):
self.file = file
self.glove_embeddings = {}
self.lib_path = '../lib/glove/'
def make_embeddings(self):
... | Python | zaydzuhri_stack_edu_python |
function gen_udp_pkt src=none dst=none payload_len=- 1
begin
set getipaddr = lambda addr -> if expression addr is none then call rand_ipaddr else addr
set sip = call getipaddr src
set dip = call getipaddr dst
set payload = call get_payload payload_len
set pkt = call fuzz call IP src=sip dst=dip / call UDP / payload
com... | def gen_udp_pkt(src=None, dst=None, payload_len=-1):
getipaddr = lambda addr: rand_ipaddr() if addr is None else addr
sip = getipaddr(src)
dip = getipaddr(dst)
payload = get_payload(payload_len)
pkt = fuzz(IP(src=sip, dst=dip)/UDP())/payload
# pkt.show2()
# os.write(2, str(pkt))
return s... | Python | nomic_cornstack_python_v1 |
comment Given 2D array
set array = list list 1 2 3 list 4 5 6 list 7 8 9
comment Initialize the sum variable
set sum = 0
comment Iterate through each row
for row in array
begin
comment Iterate through each element in the row
for element in row
begin
comment Check if the element is greater than 10
if element > 10
begin
... | # Given 2D array
array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Initialize the sum variable
sum = 0
# Iterate through each row
for row in array:
# Iterate through each element in the row
for element in row:
# Check if the element is greater than 10
if element > 10:
# Add the element t... | Python | greatdarklord_python_dataset |
comment list of function used to change the static IP.
import subprocess
comment to clean strings
import re
comment used to name the backup file!
from datetime import datetime
function getInterfaceNames
begin
set CmdLineOutput = check output string netsh interface ipv4 show interfaces shell=true
comment Decode CmdLineO... | ### list of function used to change the static IP.
import subprocess #
import re # to clean strings
from datetime import datetime ## used to name the backup file!
def getInterfaceNames():
CmdLineOutput = subprocess.check_output("netsh interface ipv4 show interfaces", shell=True)
## ... | Python | zaydzuhri_stack_edu_python |
function timedelta_to_sql connection obj
begin
return call string_literal call timedelta_to_str obj
end function | def timedelta_to_sql(connection, obj):
return connection.string_literal(timedelta_to_str(obj)) | Python | nomic_cornstack_python_v1 |
function measurement_at index
begin
if index >= length _results
begin
set index = index - length _results
return _receipts at index
end
else
begin
return _results at index
end
end function | def measurement_at(index):
if index >= len(self._results):
index -= len(self._results)
return self._receipts[index]
else:
return self._results[index] | Python | nomic_cornstack_python_v1 |
function __init__ self crypto_controller **kwargs
begin
call __init__ keyword kwargs
set crypto_controller = crypto_controller
end function | def __init__(self, crypto_controller, **kwargs):
super(CryptoBulkEntryTransformer, self).__init__(**kwargs)
self.crypto_controller = crypto_controller | Python | nomic_cornstack_python_v1 |
from objects import *
from settings import *
import numpy as np
from collections import OrderedDict
string left : 判定に使用されていない残された手牌(34状態) result : 実際にどの組み合わせで手牌が分割されたかを表すリスト [ (2,2), (10,11,12), ... , ] stamp : stamp[0]は面子の数、stamp[1]は雀頭の数、stamp[2]はターツの数 naki : 鳴きの種類に関わらず、鳴いた牌を [(...), (...), ] の形でまとめる
class WinningAnal... | from .objects import *
from .settings import *
import numpy as np
from collections import OrderedDict
"""
left : 判定に使用されていない残された手牌(34状態)
result : 実際にどの組み合わせで手牌が分割されたかを表すリスト [ (2,2), (10,11,12), ... , ]
stamp : stamp[0]は面子の数、stamp[1]は雀頭の数、stamp[2]はターツの数
naki : 鳴きの種類に関わらず、鳴いた牌を [(...), (...), ] の形でまとめる
"""... | Python | zaydzuhri_stack_edu_python |
comment use the legacy module it's pretty great
from driver import Driver
from Adafruit_MotorHAT import Adafruit_MotorHAT , Adafruit_DCMotor
import time
if __name__ == string __main__
begin
set driver = call Driver
set start = time
while 1
begin
print string time elapsed: + string time - start
set motor = lmotor
run FO... | from driver import Driver # use the legacy module it's pretty great
from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor
import time
if __name__ == "__main__":
driver = Driver()
start = time.time()
while 1:
print("time elapsed: "+str(time.time()-start))
motor = driver.lmotor
... | Python | zaydzuhri_stack_edu_python |
function distributions_EMD d1 d2
begin
return call wasserstein_distance call get_probs call get_probs / length call get_probs
end function | def distributions_EMD(d1, d2):
return ss.wasserstein_distance(d1.get_probs(), d2.get_probs()) / len(d1.get_probs()) | Python | nomic_cornstack_python_v1 |
function test_string_encoding self
begin
set renderer = call Renderer string_encoding=string foo
assert equal string_encoding string foo
end function | def test_string_encoding(self):
renderer = Renderer(string_encoding="foo")
self.assertEqual(renderer.string_encoding, "foo") | Python | nomic_cornstack_python_v1 |
comment Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
string Overall complexity is O(n^2) Calculate Slope: Every time we select a point and traverse others, calculate their slopes and add the result to map. (map in Python is implemented with Hash, so the complexity ... | # Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
'''
Overall complexity is O(n^2)
Calculate Slope:
Every time we select a point and traverse others, calculate their slopes and add the result to map.
(map in Python is implemented with Hash, so the complexity for inser... | Python | zaydzuhri_stack_edu_python |
function get_barcode self
begin
comment self.lockedstart()
while true
begin
try
begin
set tuple timestamp barcode = get barcodes true 1
if timestamp > time - 5
begin
return barcode
end
end
except Empty
begin
return string abc
end
end
end function | def get_barcode(self):
# self.lockedstart()
while True:
try:
timestamp, barcode = self.barcodes.get(True, 1)
if timestamp > time.time() - 5:
return barcode
except Empty:
return 'abc' | Python | nomic_cornstack_python_v1 |
function update_state_fn flat_state state_update_tensors
begin
call assert_compatible flat_state_spec flat_state
set state = call pack_sequence_as internal_structure at string state flat_state
set state_update_tensors = call pack_sequence_as internal_structure at string state_update_tensors state_update_tensors
set upd... | def update_state_fn(flat_state, state_update_tensors):
py_utils.assert_compatible(flat_state_spec, flat_state)
state = tf.nest.pack_sequence_as(internal_structure['state'], flat_state)
state_update_tensors = tf.nest.pack_sequence_as(
internal_structure['state_update_tensors'], state_update_t... | Python | nomic_cornstack_python_v1 |
function count_list_items list_of_strings
begin
set counts = dict
end function | def count_list_items(list_of_strings):
counts = {}
| Python | iamtarun_python_18k_alpaca |
function getOptions self section=none
begin
set opts = list
set __opts = call getOptions self string Definition opts
if section is none
begin
set sections = sections self
end
else
begin
set sections = list section
end
comment Get the options of all jails.
set parse_status = true
for sec in sections
begin
set jail = ca... | def getOptions(self, section=None):
opts = []
self.__opts = ConfigReader.getOptions(self, "Definition", opts)
if section is None:
sections = self.sections()
else:
sections = [ section ]
# Get the options of all jails.
parse_status = True
for sec in sections:
jail = JailReader(sec, basedir=self.... | Python | nomic_cornstack_python_v1 |
function download_documents item_list output_path
begin
if not exists path output_path
begin
make directories output_path
end
set downloaded = list
set items = call get_all
for item in items
begin
set md = call metadata
set fname = join path output_path call galaxy_name md at string alveo:metadata at string dc:identif... | def download_documents(item_list, output_path):
if not os.path.exists(output_path):
os.makedirs(output_path)
downloaded = []
items = item_list.get_all()
for item in items:
md = item.metadata()
fname = os.path.join(output_path, galaxy_name(md['alveo:metadata']['dc:identifier'], ... | Python | nomic_cornstack_python_v1 |
function request self request
begin
if not connected
begin
info string eBusd not connected
return
end
acquire _lock
try
begin
call send encode request
debug format string REQUEST: {0} request
end
except Exception as e
begin
release _lock
close self
warning format string error sending request: {0} => {1} request e
retur... | def request(self, request):
if not self.connected:
self.logger.info("eBusd not connected")
return
self._lock.acquire()
try:
self._sock.send(request.encode())
self.logger.debug("REQUEST: {0}".format(request))
except Exception as e:
... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
comment Combining and Merging datasets
set df1 = call DataFrame dict string key list string b string b string a string c string a string a string b ; string data1 range 7
set df2 = call DataFrame dict string key list string a string b string d ; string data2 range 3
print df1
prin... | import pandas as pd
import numpy as np
# Combining and Merging datasets
df1 = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'],
'data1': range(7)})
df2 = pd.DataFrame({'key': ['a', 'b', 'd'],
'data2': range(3)})
print(df1)
print()
print(df2)
print(pd.merge(df1,df2))
pr... | Python | zaydzuhri_stack_edu_python |
function add_action self icon_path text callback enabled_flag=true add_to_menu=true add_to_toolbar=true status_tip=none whats_this=none parent=none
begin
set icon = call QIcon icon_path
set action = call QAction icon text parent
call connect callback
call setEnabled enabled_flag
if status_tip is not none
begin
call set... | def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
... | Python | nomic_cornstack_python_v1 |
import math
function euclidean_distance point1 point2
begin
string Calculates the euclidean distance between two points
set distance = 0
end function | import math
def euclidean_distance(point1, point2):
'''
Calculates the euclidean distance between two points
'''
distance = 0
| Python | flytech_python_25k |
function edit_distance str1 str2 reconstruct_answer=false method=call Levinshtein swap_case_on_mismatch=true
begin
set method = if expression method is none then call Levinshtein else method
return call align str1 str2 reconstruct_answer method swap_case_on_mismatch
end function | def edit_distance(str1, str2, reconstruct_answer=False, method=alignments.Levinshtein(),
swap_case_on_mismatch=True):
method = alignments.Levinshtein() if method is None else method
return align(str1, str2, reconstruct_answer, method, swap_case_on_mismatch) | Python | nomic_cornstack_python_v1 |
function gm_mads_evi_rainfall ds
begin
set dc = call Datacube app=string training
set ds = ds / 10000
set ds = rename dict string nir_1 string nir_wide ; string nir_2 string nir
set ds1 = call sel time=call slice string 2019-01 string 2019-06
set ds2 = call sel time=call slice string 2019-07 string 2019-12
set chirps =... | def gm_mads_evi_rainfall(ds):
dc = datacube.Datacube(app='training')
ds = ds / 10000
ds = ds.rename({'nir_1':'nir_wide', 'nir_2':'nir'})
ds1 = ds.sel(time=slice('2019-01', '2019-06'))
ds2 = ds.sel(time=slice('2019-07', '2019-12'))
chirps = []
chpclim = []
for m in range(1,13):
... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.