code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function _check_method_allowed self method
begin
if upper method in options or upper method == string OPTIONS
begin
return true
end
raise call make_error string method_not_allowed method=upper method
end function | def _check_method_allowed(self, method):
if method.upper() in self.options or (
method.upper() == "OPTIONS"):
return True
raise self.make_error("method_not_allowed", method=method.upper()) | Python | nomic_cornstack_python_v1 |
function generate_query_start_times self starting_time
begin
if starting_time is none
begin
set query_starting_times = none
set query_ending_times = none
info string Query start times: None
end
else
begin
set query_starting_times = list
set query_ending_times = list
set dtime = _plot_end - starting_time
if dtime > qu... | def generate_query_start_times(self, starting_time):
if starting_time is None:
query_starting_times = None
query_ending_times = None
logging.info(f'Query start times: None')
else:
query_starting_times = []
query_ending_times = []
dt... | Python | nomic_cornstack_python_v1 |
import turtle
set Padme = call Turtle
call bgcolor string black
comment Sharpness & thikness of the printed lines
call speed 10
set b = list string blue string yellow string red string white string orange
for i in range 149
begin
for a in b
begin
call color a
call forward i * 0.3
call right 8
end
end
call done | import turtle
Padme=turtle.Turtle()
turtle.bgcolor("black")
#Sharpness & thikness of the printed lines
turtle.speed(10)
b=["blue","yellow","red","white","orange"]
for i in range (149):
for a in b:
Padme.color(a)
Padme.forward(i*0.3)
Padme.right(8)
turtle.done() | Python | zaydzuhri_stack_edu_python |
import argparse
set parser = call ArgumentParser
call add_argument string -f string --fahrenheit default=100 help=string fahrenheit
comment parser.add_argument('-C',"--celcius",default=0.6,help='celcus')
set args = call parse_args
set F = fahrenheit
set c = celcius | import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-f',"--fahrenheit",default=100,help='fahrenheit')
#parser.add_argument('-C',"--celcius",default=0.6,help='celcus')
args=parser.parse_args()
F=args.fahrenheit
c = args.celcius
| Python | zaydzuhri_stack_edu_python |
function _plot self
begin
comment Read results
set path = openmc_dir / string statepoint. { _batches } .h5
set tuple x1 y1 _ = call read_results string openmc path
if code == string serpent
begin
set path = other_dir / string input_det0.m
end
else
begin
set path = other_dir / string outp
end
set tuple x2 y2 sd = call r... | def _plot(self):
# Read results
path = self.openmc_dir / f'statepoint.{self._batches}.h5'
x1, y1, _ = read_results('openmc', path)
if self.code == 'serpent':
path = self.other_dir / 'input_det0.m'
else:
path = self.other_dir / 'outp'
x2, y2, sd = r... | Python | nomic_cornstack_python_v1 |
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import col
import matplotlib.pyplot as plt
from itertools import combinations
import itertools
import numpy as np
from pprint import pprint
from itertools import chain
from operator import add
from math import sqrt
from pyspa... | from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.functions import col
import matplotlib.pyplot as plt
from itertools import combinations
import itertools
import numpy as np
from pprint import pprint
from itertools import chain
from operator import add
from math import sqrt
from pyspa... | Python | zaydzuhri_stack_edu_python |
string From Vista to Python - Visualization of reachable sets This example code reads JSON files exported from Vista and perform visualizations
comment Data Handling
import json
import numpy as np
import math
import base64
comment Bokeh libraries
from bokeh.layouts import column
from bokeh.io import curdoc
from bokeh.p... | """ From Vista to Python - Visualization of reachable sets
This example code reads JSON files exported from Vista and perform visualizations
"""
# Data Handling
import json
import numpy as np
import math
import base64
# Bokeh libraries
from bokeh.layouts import column
from bokeh.io import curdoc
from bokeh.plotting i... | Python | zaydzuhri_stack_edu_python |
function hierarical_clustering p_df method=string average
begin
set pdf_values = values
call fill_diagonal pdf_values 0
set pdf_values_1_d = call matrix_to_squareform pdf_values
set cluster_matrix = call linkage pdf_values_1_d method
return cluster_matrix
end function | def hierarical_clustering(p_df, method="average"):
pdf_values = p_df.values
np.fill_diagonal(pdf_values, 0)
pdf_values_1_d = matrix_to_squareform(pdf_values)
cluster_matrix = linkage(pdf_values_1_d, method)
return cluster_matrix | Python | nomic_cornstack_python_v1 |
function _extract_shape shape
begin
if string , not in shape
begin
return list
end
set shape_arr = list
for s in split shape string ,
begin
set s = strip s
if not s
begin
return list
end
if string : in s
begin
set s = split s string : at 0
end
set s = replace s string ! string
if not is digit s
begin
return list
en... | def _extract_shape(shape):
if "," not in shape:
return []
shape_arr = []
for s in shape.split(","):
s = s.strip()
if not s:
return []
if ":" in s:
s = s.split(":")[0]
s = s.replace("!", "")
i... | Python | nomic_cornstack_python_v1 |
comment funcion para encontrar el r2 ajustado
function adj_r2 x y
begin
set r2 = score reg x y
set n = shape at 0
set p = shape at 1
set adjusted_r2 = 1 - 1 - r2 * n - 1 / n - p - 1
return adjusted_r2
end function
call adj_r2 84 2 | # funcion para encontrar el r2 ajustado
def adj_r2(x,y):
r2 = reg.score(x,y)
n = x.shape[0]
p = x.shape[1]
adjusted_r2 = 1-(1-r2)*(n-1)/(n-p-1)
return adjusted_r2
adj_r2(84, 2) | Python | zaydzuhri_stack_edu_python |
function checkGameOver self
begin
set directions = list string UP string DOWN string LEFT string RIGHT
set counter = 0
comment Try all moves and count non-moves
for direction in directions
begin
set test_grid = deep copy self
call slide direction
if test_grid == self
begin
set counter = counter + 1
end
end
return count... | def checkGameOver(self):
directions = ['UP', 'DOWN', 'LEFT', 'RIGHT']
counter = 0
# Try all moves and count non-moves
for direction in directions:
test_grid = deepcopy(self)
test_grid.slide(direction)
if test_grid == self:
counter += ... | Python | nomic_cornstack_python_v1 |
import heapq
class MedianFinder extends object
begin
function __init__ self
begin
set s = 0
set l = 0
set maxheap = list
set minheap = list
end function
function addNum self num
begin
set s = s + num
set l = l + 1
call heappush maxheap num
set temp = call heappop maxheap
call heappush minheap - temp
if length maxheap... | import heapq
class MedianFinder(object):
def __init__(self):
self.s = 0
self.l = 0
self.maxheap = []
self.minheap = []
def addNum(self, num):
self.s += num
self.l += 1
heapq.heappush(self.maxheap, num)
temp = heapq.heappop(self... | Python | zaydzuhri_stack_edu_python |
function auth_headers api_key bearer_token signing_key
begin
comment type: (str, str, str) -> dict
set nonce = hexadecimal
set timestamp = call iso_timestamp
set payload = bytes string { api_key } { bearer_token } { timestamp } { nonce } string utf-8
set key = call fromhex signing_key
set signature = hexadecimal
set au... | def auth_headers(api_key, bearer_token, signing_key):
# type: (str, str, str) -> dict
nonce = os.urandom(NONCE_SIZE).hex()
timestamp = iso_timestamp()
payload = bytes(f"{api_key}{bearer_token}{timestamp}{nonce}", "utf-8")
key = bytes.fromhex(signing_key)
signature = hmac.new(key, payload, dig... | Python | nomic_cornstack_python_v1 |
import re
from gensim import models , corpora
import nltk
comment You only need to do this once when you start running
comment nltk.download('stopwords')
comment nltk.download('punkt')
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import spacy
import gensim
imp... | import re
from gensim import models, corpora
import nltk
# You only need to do this once when you start running
# nltk.download('stopwords')
# nltk.download('punkt')
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import spacy
import gensim
import pandas as pd
... | Python | zaydzuhri_stack_edu_python |
function push_back self item
begin
call enqueue item
end function | def push_back(self, item):
self.enqueue(item) | Python | nomic_cornstack_python_v1 |
function find_add self coordinator index
begin
if index >= length _controllers
begin
return add self call IUController _hass coordinator index
end
return _controllers at index
end function | def find_add(self, coordinator: "IUCoordinator", index: int) -> IUController:
if index >= len(self._controllers):
return self.add(IUController(self._hass, coordinator, index))
return self._controllers[index] | Python | nomic_cornstack_python_v1 |
function addCoordset self coords label=none
begin
if _coords is none
begin
return call setCoords coords
end
set n_atoms = _n_atoms
set atoms = coords
try
begin
set coords = if expression has attribute coords string _getCoordsets then call _getCoordsets else call getCoordsets
end
except AttributeError
begin
pass
end
try... | def addCoordset(self, coords, label=None):
if self._coords is None:
return self.setCoords(coords)
n_atoms = self._n_atoms
atoms = coords
try:
coords = (atoms._getCoordsets()
if hasattr(coords, '_getCoordsets') else
ato... | Python | nomic_cornstack_python_v1 |
comment @lc app=leetcode id=92 lang=python3
comment [92] Reverse Linked List II
comment https://leetcode.com/problems/reverse-linked-list-ii/description/
comment algorithms
comment Medium (37.21%)
comment Likes: 1842
comment Dislikes: 121
comment Total Accepted: 243K
comment Total Submissions: 651.3K
comment Testcase E... | #
# @lc app=leetcode id=92 lang=python3
#
# [92] Reverse Linked List II
#
# https://leetcode.com/problems/reverse-linked-list-ii/description/
#
# algorithms
# Medium (37.21%)
# Likes: 1842
# Dislikes: 121
# Total Accepted: 243K
# Total Submissions: 651.3K
# Testcase Example: '[1,2,3,4,5]\n2\n4'
#
# Reverse a lin... | Python | zaydzuhri_stack_edu_python |
comment pylint: disable=W0622
async function create_websocket_server sock filter=none
begin
string A more low-level form of open_websocket_server. You are responsible for closing this websocket.
set ws = call Websocket
await call start_server sock filter=filter
return ws
end function | async def create_websocket_server(sock, filter=None): # pylint: disable=W0622
"""
A more low-level form of open_websocket_server.
You are responsible for closing this websocket.
"""
ws = Websocket()
await ws.start_server(sock, filter=filter)
return ws | Python | jtatman_500k |
function DebugMenuProviderMixin_on_init self
begin
call BaseMenuProviderMixin_on_init self
comment Define the core object
set activeMenuReference = call init_from_dict dict string top_level_menu none ; string actions_dict dict ; string menu_provider_obj none
end function | def DebugMenuProviderMixin_on_init(self):
BaseMenuProviderMixin.BaseMenuProviderMixin_on_init(self)
# Define the core object
self.activeMenuReference = PhoUIContainer.init_from_dict({'top_level_menu': None, 'actions_dict': {}, 'menu_provider_obj': None}) | Python | nomic_cornstack_python_v1 |
function frequently_bought_together_config self
begin
return get pulumi self string frequently_bought_together_config
end function | def frequently_bought_together_config(self) -> Optional[pulumi.Input['GoogleCloudRetailV2ModelFrequentlyBoughtTogetherFeaturesConfigArgs']]:
return pulumi.get(self, "frequently_bought_together_config") | Python | nomic_cornstack_python_v1 |
function _conn_redis self
begin
return call Redis host=_REDIS_DB_HOST port=_REDIS_DB_PORT db=0 decode_responses=true
end function | def _conn_redis(self) -> Redis:
return Redis(host=self._REDIS_DB_HOST, port=self._REDIS_DB_PORT, db=0,decode_responses=True) | Python | nomic_cornstack_python_v1 |
function async_trigger_discovery hass discovered_devices
begin
for tuple formatted_mac device in items discovered_devices
begin
call async_create_flow hass DOMAIN context=dict string source SOURCE_INTEGRATION_DISCOVERY data=dict CONF_NAME alias ; CONF_HOST host ; CONF_MAC formatted_mac
end
end function | def async_trigger_discovery(
hass: HomeAssistant,
discovered_devices: dict[str, SmartDevice],
) -> None:
for formatted_mac, device in discovered_devices.items():
discovery_flow.async_create_flow(
hass,
DOMAIN,
context={"source": config_entries.SOURCE_INTEGRATION_D... | Python | nomic_cornstack_python_v1 |
from fractions import *
from itertools import product
set mem = dict
function p k colors
begin
if tuple k colors in mem
begin
return mem at tuple k colors
end
if sum colors == 50
begin
return call Fraction k == sum generator expression color != 10 for color in colors
end
else
begin
set num_zeros = sum generator expres... | from fractions import *
from itertools import product
mem = {}
def p(k, colors):
if (k, colors) in mem:
return mem[(k, colors)]
if sum(colors) == 50:
return Fraction(k == sum(color != 10 for color in colors))
else:
num_zeros = sum(color == 0 for color in colors)
result = 0... | Python | zaydzuhri_stack_edu_python |
function login_required func
begin
decorator wraps func
function wrapper *args **kwargs
begin
if string username in session
begin
return call func *args keyword kwargs
end
else
begin
call flash string You must be logged in to access that page. string danger
return call redirect call url_for string login
end
end functio... | def login_required(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if 'username' in session:
return func(*args, **kwargs)
else:
flash("You must be logged in to access that page.", 'danger')
return redirect(url_for('login'))
return wrapper | Python | nomic_cornstack_python_v1 |
function save_model model
begin
comment ***
comment Please remove the comment to enable model save.
comment However, it will overwrite the baseline model we provided.
comment ***
save string model/model.h5
print string Model Saved Successfully.
end function | def save_model(model):
# ***
# Please remove the comment to enable model save.
# However, it will overwrite the baseline model we provided.
# ***
model.save("model/model.h5")
print("Model Saved Successfully.") | Python | nomic_cornstack_python_v1 |
function visualize_semantic_segmentation_2d semantic_segmentation_2d ontology void_class_id=255 image=none alpha=0.3 debug=false
begin
set tuple height width = shape
comment Convert colormap to (num_classes, 3), where num_classes includes VOID and last entry is color for VOID
set colormap = call ontology_to_viz_colorma... | def visualize_semantic_segmentation_2d(
semantic_segmentation_2d, ontology, void_class_id=255, image=None, alpha=0.3, debug=False
):
height, width = semantic_segmentation_2d.shape
# Convert colormap to (num_classes, 3), where num_classes includes VOID and last entry is color for VOID
colormap = ontolog... | Python | nomic_cornstack_python_v1 |
function _load_hyper_transformer self table_name
begin
set dtypes = call get_dtypes table_name
set pii_fields = call _get_pii_fields table_name
set transformers_dict = call _get_transformers dtypes pii_fields
return call HyperTransformer field_transformers=transformers_dict
end function | def _load_hyper_transformer(self, table_name):
dtypes = self.get_dtypes(table_name)
pii_fields = self._get_pii_fields(table_name)
transformers_dict = self._get_transformers(dtypes, pii_fields)
return HyperTransformer(field_transformers=transformers_dict) | Python | nomic_cornstack_python_v1 |
function forward self x
begin
set out = none
comment TODO: Implement the max pooling forward pass. #
comment Hint: #
comment 1) You may implement the process with loops #
set H = shape at 2
set W = shape at 3
set H_out = integer H - kernel_size / stride + 1
set W_out = integer W - kernel_size / stride + 1
set out = zer... | def forward(self, x):
out = None
#############################################################################
# TODO: Implement the max pooling forward pass. #
# Hint: #
# 1) Yo... | Python | nomic_cornstack_python_v1 |
function start_tag self tagname options hsdoptions
begin
comment opens with equal?
set equalsign = get hsdoptions HSDATTR_EQUAL false
if options
begin
if _defattrib and length options == 1 and _defattrib in options
begin
set optstr = string [ + options at _defattrib + string ]
end
else
begin
set optlist = list comprehe... | def start_tag(self, tagname, options, hsdoptions):
equalsign = hsdoptions.get(HSDATTR_EQUAL, False) # opens with equal?
if options:
if (self._defattrib and len(options) == 1
and self._defattrib in options):
optstr = " [" + options[self._defattrib] + "]"
... | Python | nomic_cornstack_python_v1 |
function ResampleTiles label_raster offsets_fp
begin
if call splitext offsets_fp at 1 != string .csv
begin
print string Error (ResampleTiles): Input offsets_fp must be path to csv.
exit 0
end
set tiles = list
with open offsets_fp string r+ newline=string as csvfile
begin
set csvreader = reader csvfile delimiter=string... | def ResampleTiles(label_raster, offsets_fp):
if os.path.splitext(offsets_fp)[1] != '.csv':
print("Error (ResampleTiles): Input offsets_fp must be path to csv.")
sys.exit(0)
tiles = []
with open(offsets_fp, 'r+', newline='\n') as csvfile:
csvreader = csv.reader(csvfile, delimite... | Python | nomic_cornstack_python_v1 |
import torchvision
import torch
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
set BATCH_SIZE = 64
set transform = call Compose list call ToTensor
set train_set = call MNIST root=string ./data train=true download=true transform=transform
set train_loader = call DataLoader ... | import torchvision
import torch
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
BATCH_SIZE = 64
transform = transforms.Compose([transforms.ToTensor()])
train_set = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
train_loader = to... | Python | zaydzuhri_stack_edu_python |
function conv3x3 in_planes out_planes stride=1 dilation=1
begin
return conv 2d in_planes out_planes kernel_size=3 stride=stride padding=dilation dilation=dilation bias=false
end function | def conv3x3(in_planes, out_planes, stride=1, dilation=1):
return nn.Conv2d(
in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, dilation=dilation, bias=False
) | Python | nomic_cornstack_python_v1 |
function dateprocess
begin
comment 从文件中加载数据
set fr = open string G:\corpus\yunhanoutput.txt string r encoding=string utf
set fw2 = open string G:\corpus\yunhanfirst.txt string w encoding=string utf
for line in read lines fr
begin
comment 返回移除字符串头尾指定的字符生成的新字符串
set line = strip line
comment 以 '\t' 切割字符串
set listFromLine ... | def dateprocess():
# 从文件中加载数据
fr = open('G:\corpus\yunhanoutput.txt', 'r', encoding="utf")
fw2 = open('G:\corpus\yunhanfirst.txt', 'w', encoding="utf")
for line in fr.readlines():
# 返回移除字符串头尾指定的字符生成的新字符串
line = line.strip()
# 以 '\t' 切割字符串
listFromLine = line.split('\t')
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import arcpy
import datetime
class Toolbox extends object
begin
function __init__ self
begin
string Define the toolbox (the name of the toolbox is the name of the .pyt file).
set label = string Trees
set alias = string Trees
comment List of tool classes associated with this toolbox
set too... | # -*- coding: utf-8 -*-
import arcpy
import datetime
class Toolbox(object):
def __init__(self):
"""Define the toolbox (the name of the toolbox is the name of the
.pyt file)."""
self.label = "Trees"
self.alias = "Trees"
# List of tool classes associated with t... | Python | zaydzuhri_stack_edu_python |
set num = input
print integer num at 0 + integer num at - 1 | num = input()
print(int(num[0])+ int(num[-1])) | Python | zaydzuhri_stack_edu_python |
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input , Output , State
from web.utils import app
from web.utils import nav
class Home
begin
string The Home module acts as the website's homepage where basic graphs appear.
functi... | import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
from web.utils import app
from web.utils import nav
class Home:
"""The Home module acts as the website's homepage where basic graphs appear.
"""
... | Python | zaydzuhri_stack_edu_python |
function index request
begin
set context = dict string video_search video_search
return call render request string dproject/index.html context
end function | def index(request):
context = {'video_search': video_search}
return render(request, 'dproject/index.html', context) | Python | nomic_cornstack_python_v1 |
import numpy as np
import cifar10
import timer
set dir = string datasets/cifar-10-batches-py
set tuple X_train y_train X_test y_test = call load_CIFAR10 dir
comment Subsample to save on time/space
set num_training = 5000
set num_validation = 1000
set num_test = 1000
comment Our validation set will be num_validation poi... | import numpy as np
import cifar10
import timer
dir = 'datasets/cifar-10-batches-py'
X_train, y_train, X_test, y_test = cifar10.load_CIFAR10(dir)
# Subsample to save on time/space
num_training = 5000
num_validation = 1000
num_test = 1000
# Our validation set will be num_validation points from the original
# training... | Python | zaydzuhri_stack_edu_python |
comment Used to test stuff
from Poker_Bot import Game_State
from deuces import Card
from deuces import Deck
import numpy as np
set gs = call Game_State
set deck = call Deck
call set_player_cards call draw 2
call set_opponent_cards call draw 2
call set_flop call draw 3
call append_action string B
call append_action stri... | # Used to test stuff
from Poker_Bot import Game_State
from deuces import Card
from deuces import Deck
import numpy as np
gs = Game_State()
deck = Deck()
gs.set_player_cards(deck.draw(2))
gs.set_opponent_cards(deck.draw(2))
gs.set_flop(deck.draw(3))
gs.append_action('B')
gs.append_action('B')
gs.print_player_cards()
... | Python | zaydzuhri_stack_edu_python |
function _element self n
begin
comment convert DOM namedNodeMap to SAX attributes
set nnm = attributes
set attrs = dict
for a in values nnm
begin
set attrs at nodeName = value
end
comment handle element
set name = nodeName
call startElement name call AttributesImpl attrs
call _from_dom firstChild
call endElement name
... | def _element(self, n):
## convert DOM namedNodeMap to SAX attributes
nnm = n.attributes
attrs = {}
for a in nnm.values():
attrs[a.nodeName] = a.value
## handle element
name = n.nodeName
self._cont_handler.startElement(name, AttributesImpl(attrs))
... | Python | nomic_cornstack_python_v1 |
function is_final_boss self x y
begin
return structure at x at y == string b
end function | def is_final_boss(self, x, y):
return self.structure[x][y] == 'b' | Python | nomic_cornstack_python_v1 |
class Student
begin
function __init__ self name
begin
set name = name
set marks = list
end function
function average self
begin
set number = length marks
if number == 0
begin
return 0
end
else
begin
set total = sum marks
return total / number
end
end function
end class
function create_student
begin
comment Ask the use... | class Student:
def __init__(self, name):
self.name = name
self.marks = []
def average(self):
number = len(student.marks)
if number == 0:
return 0
else:
total = sum(student.marks)
return total / number
def create_student():
# Ask... | Python | zaydzuhri_stack_edu_python |
function tag_word lx wd
begin
set taggings = list
set tagset = list string P string A
set tag_verbs = list string I string T
if wd in function_words
begin
for tag in function_words_tags
begin
if tag at 0 == wd
begin
append taggings tag at 1
end
end
end
comment Checks if the word is tagged in the lexicon
for tag in tag... | def tag_word (lx,wd):
taggings = []
tagset = ["P", "A"]
tag_verbs = ["I", "T"]
if wd in function_words:
for tag in function_words_tags:
if tag[0] == wd:
taggings.append(tag[1])
for tag in tagset: #Checks if the word is tagged in the l... | Python | nomic_cornstack_python_v1 |
function standalone_html self
begin
set SIMPLE_HTML = call Template string <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <style> {{ css }} </style> </head> <body> <link href="{{bootstrap4_css_url}}" rel="stylesheet"/> <link href="{{font_awesome_url}}" rel="stylesheet"/> <link href="{{bootstrap_table_css_url}}" r... | def standalone_html(self) -> str:
SIMPLE_HTML = jinja2.Template("""<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
{{ css }}
</style>
</head>
<body>
<link href="{{bootstrap4_c... | Python | nomic_cornstack_python_v1 |
function get_nec self
begin
return 0
end function | def get_nec(self):
return 0 | Python | nomic_cornstack_python_v1 |
function writeAminoFasta fastaInfo outputAminoFile
begin
set newRecs = list comprehension call SeqRecord call Seq f at 2 protein id=f at 0 name=f at 0 description=f at 1 for f in fastaInfo
comment Write new records as FASTA
return write SeqIO newRecs outputAminoFile string fasta
end function | def writeAminoFasta(fastaInfo, outputAminoFile):
newRecs = [SeqRecord(Seq(f[2], IUPAC.protein),
id=f[0],
name=f[0],
description=f[1]) for f in fastaInfo]
# Write new records as FASTA
return SeqIO.write(newRecs, outputAminoFile,'fasta') | Python | nomic_cornstack_python_v1 |
function app_command_line self
begin
return get pulumi self string app_command_line
end function | def app_command_line(self) -> Optional[str]:
return pulumi.get(self, "app_command_line") | Python | nomic_cornstack_python_v1 |
comment encoding: UTF-8
import os | # encoding: UTF-8
import os | Python | jtatman_500k |
function fit self X y=none **params
begin
if is instance parms at string center tuple tuple list
begin
set _means = parms at string center
end
if is instance parms at string scale tuple tuple list
begin
set _stds = parms at string scale
end
if means is none and parms at string center
begin
set _means = mean X
end
else
... | def fit(self,X,y=None, **params):
if isinstance(self.parms["center"],(tuple,list)): self._means = self.parms["center"]
if isinstance(self.parms["scale"], (tuple,list)): self._stds = self.parms["scale"]
if self.means is None and self.parms["center"]: self._means = X.mean()
else: ... | Python | nomic_cornstack_python_v1 |
import win32print
comment Getting the name of the default printer
set printer_name = call GetDefaultPrinter
print printer_name
comment Let me examine if the code works
comment 1. Imported win32print
comment 2. Got and printed the name of the default printer
comment Executing code...
comment Code has been fixed! | import win32print
# Getting the name of the default printer
printer_name = win32print.GetDefaultPrinter()
print(printer_name)
# Let me examine if the code works
# 1. Imported win32print
# 2. Got and printed the name of the default printer
# Executing code...
# Code has been fixed!
| Python | flytech_python_25k |
function get_pic
begin
with open directory name path absolute path path __file__ + string \data.json string r as test
begin
set test = load json test
end
set pic = test at string button_pic
return pic
end function | def get_pic() -> str:
with open(os.path.dirname(os.path.abspath(__file__))+'\\data.json', 'r') as test:
test = json.load(test)
pic = test['button_pic']
return pic | Python | nomic_cornstack_python_v1 |
function parse text
begin
set ret = call Docstring
if not text
begin
return ret
end
set text = call cleandoc text
set match = search string ^: text flags=M
if match
begin
set desc_chunk = text at slice : start match :
set meta_chunk = text at slice start match : :
end
else
begin
set desc_chunk = text
set meta_chunk... | def parse(text):
ret = Docstring()
if not text:
return ret
text = inspect.cleandoc(text)
match = re.search('^:', text, flags=re.M)
if match:
desc_chunk = text[:match.start()]
meta_chunk = text[match.start():]
else:
desc_chunk = text
meta_chunk = ''
p... | Python | nomic_cornstack_python_v1 |
if operator == string +
begin
print num1 + num2
end
else
if operator == string -
begin
print num1 - num2
end
else
if operator == string *
begin
print num1 * num2
end
else
begin
print num1 / num2
end | if operator == "+":
print(num1 + num2)
elif operator == "-":
print(num1 - num2)
elif operator == "*":
print(num1 * num2)
else:
print(num1/num2) | Python | zaydzuhri_stack_edu_python |
from math import e , pow
import matplotlib.pyplot as plt
import numpy as np
comment Variant 12:
comment f(x, y) = dy/dx = x*y^2 + 3 * x * y
function __exactY x c
begin
string x: current x value c: precalculated c value equal to c = y0 / (pow(e, 1.5 * x0 * x0) * (3 + y0))
set tmp = power e 1.5 * x * x
return 3 * c * tmp... | from math import e, pow
import matplotlib.pyplot as plt
import numpy as np
# Variant 12:
# f(x, y) = dy/dx = x*y^2 + 3 * x * y
def __exactY(x, c):
"""
x: current x value
c: precalculated c value equal to c = y0 / (pow(e, 1.5 * x0 * x0) * (3 + y0))
"""
tmp = pow(e, 1.5 * x * x)
return ... | Python | zaydzuhri_stack_edu_python |
function SetWeight *args **kwargs
begin
return call Font_SetWeight *args keyword kwargs
end function | def SetWeight(*args, **kwargs):
return _gdi_.Font_SetWeight(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
function get_files filepath
begin
set all_files = list
for tuple root dirs files in walk filepath
begin
set files = glob glob join path root string *.json
for f in files
begin
append all_files absolute path path f
end
end
return all_files
end function | def get_files(filepath):
all_files = []
for root, dirs, files in os.walk(filepath):
files = glob.glob(os.path.join(root,'*.json'))
for f in files :
all_files.append(os.path.abspath(f))
return all_files | Python | nomic_cornstack_python_v1 |
import unittest
class TestFactorize extends TestCase
begin
function test_wrong_types_raise_exception self
begin
string Проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError. Тестовый набор входных данных: 'string', 1.5
set cases = tuple string string 1.5
for case in cases
begin... | import unittest
class TestFactorize(unittest.TestCase):
def test_wrong_types_raise_exception(self):
"""
Проверяет, что передаваемый в функцию аргумент типа float или str вызывает исключение TypeError.
Тестовый набор входных данных: 'string', 1.5
"""
cases = ('string', 1.... | Python | zaydzuhri_stack_edu_python |
function clients self protocol=none groups=none
begin
set groups = call check_parameters_for_validity groups string group call groups
set retval = list
if string world in groups
begin
set q = filter group == string world
set retval = retval + list q
end
if string dev in groups
begin
set q = filter group == string dev
... | def clients(self, protocol=None, groups=None):
groups = self.check_parameters_for_validity(groups, "group", self.groups())
retval = []
if "world" in groups:
q = self.query(Client).filter(Client.group == 'world')
retval += list(q)
if 'dev' in groups:
q = self.query(Client).filter(Clien... | Python | nomic_cornstack_python_v1 |
function cmd_server_load self
begin
string Generate statistics regarding how many requests were processed by each downstream server.
set servers = default dictionary int
for line in _valid_lines
begin
set servers at server_name = servers at server_name + 1
end
return servers
end function | def cmd_server_load(self):
"""Generate statistics regarding how many requests were processed by
each downstream server.
"""
servers = defaultdict(int)
for line in self._valid_lines:
servers[line.server_name] += 1
return servers | Python | jtatman_500k |
comment Write your code above 👆
with open string file1.txt as file1
begin
set file_1_data = read lines file1
end
with open string file2.txt as file2
begin
set file_2_data = read lines file2
end
set result = list comprehension integer num for num in file_1_data if num in file_2_data
print result | # Write your code above 👆
with open("file1.txt") as file1:
file_1_data = file1.readlines()
with open("file2.txt") as file2:
file_2_data = file2.readlines()
result = [int(num) for num in file_1_data if num in file_2_data]
print(result)
| Python | zaydzuhri_stack_edu_python |
function count_even_before_odd arr
begin
set count = 0
for num in arr
begin
if num % 2 == 0
begin
set count = count + 1
end
else
begin
break
end
end
return count
end function
comment Test the function
set arr = list 3 5 2 5 1
set result = call count_even_before_odd arr
comment Output: 1
print result | def count_even_before_odd(arr):
count = 0
for num in arr:
if num % 2 == 0:
count += 1
else:
break
return count
# Test the function
arr = [3, 5, 2, 5, 1]
result = count_even_before_odd(arr)
print(result) # Output: 1
| Python | jtatman_500k |
function configure_screenshots scenario
begin
set auto_capture_screenshots = false
end function | def configure_screenshots(scenario):
world.auto_capture_screenshots = False | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
comment -*- coding:utf-8 -*-
comment Authour:Dreamer
comment Tmie:2018.6.22
function test1
begin
print string ----test1----
print num
print string ----test2----
end function
function test2
begin
try
begin
print string ----test1-1----
call test1
print string ----test2-2----
end
except any
begin... | #!/usr/bin/python3
# -*- coding:utf-8 -*-
# Authour:Dreamer
# Tmie:2018.6.22
def test1():
print("----test1----")
print(num)
print("----test2----")
def test2():
try:
print("----test1-1----")
test1()
print("----test2-2----")
except:
print("----test2异常----")
prin... | Python | zaydzuhri_stack_edu_python |
string 9-1: Restaurant
string Make a class called Restaurant. The __init__() method for Restaurant should store two attributes: a restaurant_name and a cuisine_type. Make a method called describe_restaurant() that prints these two pieces of information, and a method called open_restaurant() that prints a message indica... | """9-1: Restaurant"""
"""Make a class called Restaurant. The __init__() method for Restaurant should store two
attributes: a restaurant_name and a cuisine_type. Make a method called describe_restaurant()
that prints these two pieces of information, and a method called open_restaurant() that prints
a message indicating ... | Python | zaydzuhri_stack_edu_python |
function adjust self
begin
set pos = pos
set _start = tuple pos at 0 + left - 1 pos at 1 + 1 + top
set _end = tuple pos at 0 + width - 1 - right pos at 1 + top + height
end function | def adjust(self) -> None:
pos = self.parent.pos
self._start = (pos[0] + self.left - 1, pos[1] + 1 + self.top)
self._end = (
pos[0] + self.parent.width - 1 - self.right,
pos[1] + self.top + self.height,
) | Python | nomic_cornstack_python_v1 |
import boto3
import matplotlib.pyplot as plt
set dynamodb = call resource string dynamodb
set table = call Table string IMU_Data
comment Function to return the x,y and z values as a list of float values in order to plot them
function split_axes data
begin
comment Before splitting the data into x,y,z axes it must be con... | import boto3
import matplotlib.pyplot as plt
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('IMU_Data')
#Function to return the x,y and z values as a list of float values in order to plot them
def split_axes(data):
#Before splitting the data into x,y,z axes it must be converted to float values
... | Python | zaydzuhri_stack_edu_python |
string This module is used to accept user input. It can control the number of books and authors to scrape. It will use book_scraper and author_scraper to get the information and then store them into database. It can accept a JSON file to update or insert into existing database. It can export existing books/authors to a... | """
This module is used to accept user input. It can control the number of
books and authors to scrape. It will use book_scraper and author_scraper
to get the information and then store them into database. It can accept a
JSON file to update or insert into existing database. It can export
existing books/authors to... | Python | zaydzuhri_stack_edu_python |
function deletePackage self pid
begin
set p = call getPackage pid
if not p
begin
return
end
set oldorder = packageorder
set root = root
for pyfile in call cachedFiles
begin
if packageid == pid
begin
call abortDownload
end
end
comment TODO: delete child packages
comment TODO: delete folder
call deletePackage pid
call re... | def deletePackage(self, pid):
p = self.getPackage(pid)
if not p: return
oldorder = p.packageorder
root = p.root
for pyfile in self.cachedFiles():
if pyfile.packageid == pid:
pyfile.abortDownload()
# TODO: delete child packages
# TOD... | Python | nomic_cornstack_python_v1 |
function _preload self
begin
set images = list
for image_fn in filenames
begin
comment load images
set image = open imageLoc + image_fn + string .jpg
comment avoid too many opened files bug
append images copy image
close image
end
end function | def _preload(self):
self.images = []
for image_fn in self.filenames:
# load images
image = Image.open(self.imageLoc + image_fn + '.jpg')
# avoid too many opened files bug
self.images.append(image.copy())
image.close() | Python | nomic_cornstack_python_v1 |
function polyCut *args caching=true constructionHistory=true cutPlaneCenter=none cutPlaneCenterX=0.0 cutPlaneCenterY=0.0 cutPlaneCenterZ=0.0 cutPlaneHeight=0.0 cutPlaneRotate=none cutPlaneRotateX=0.0 cutPlaneRotateY=0.0 cutPlaneRotateZ=0.0 cutPlaneSize=none cutPlaneWidth=0.0 cuttingDirection=string deleteFaces=false e... | def polyCut(*args, caching: bool=True, constructionHistory: bool=True, cutPlaneCenter:
Union[List[float, float, float], bool]=None, cutPlaneCenterX: Union[float,
bool]=0.0, cutPlaneCenterY: Union[float, bool]=0.0, cutPlaneCenterZ: Union[float,
bool]=0.0, cutPlaneHeight: Union[float, ... | Python | nomic_cornstack_python_v1 |
string For a tab delineated file with rows of: FILENAME MD5SUM Check that each file matches the needed MD5SUM
import logging
import subprocess
import sys
set infile = argv at 1
function check_md5sum filename md5sum
begin
debug string Checking file %s matches %s % tuple filename md5sum
set current_md5sum = split check o... | """
For a tab delineated file with rows of:
FILENAME\tMD5SUM
Check that each file matches the needed MD5SUM
"""
import logging
import subprocess
import sys
infile = sys.argv[1]
def check_md5sum(filename, md5sum):
logging.debug("Checking file %s matches %s" % (filename, md5sum))
current_md5sum = subprocess.c... | Python | zaydzuhri_stack_edu_python |
function add_Tab self tab_name
begin
set tab = call QWidget
set sizePolicy = call QSizePolicy Expanding Expanding
call setHorizontalStretch 0
call setVerticalStretch 0
call setHeightForWidth call hasHeightForWidth
call setSizePolicy sizePolicy
call setObjectName string tab
set gridLayout = call QGridLayout tab
call set... | def add_Tab(self, tab_name):
self.tab = QtWidgets.QWidget()
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tab.sizePolicy().hasHeightForWidth())
sel... | Python | nomic_cornstack_python_v1 |
function _load_content_from_file self local_artifact_path
begin
pass
end function | def _load_content_from_file(self, local_artifact_path):
pass | Python | nomic_cornstack_python_v1 |
function download_poster link filename
begin
try
begin
set poster = url open link
set output = open filename string wb
write output read poster
close output
end
except any
begin
return false
end
return true
end function | def download_poster(link,filename):
try:
poster=urllib2.urlopen(link)
output = open(filename,'wb')
output.write(poster.read())
output.close()
except:
return False
return True | Python | nomic_cornstack_python_v1 |
import requests
import pandas as pd
import sqlalchemy as sa
from sqlalchemy.exc import IntegrityError
import os
from time import sleep
from fetch_wazirx import postgres_conn_str
set postgres_engine = call create_engine postgres_conn_str
function main
begin
set api_key = get environ string EXCHANGE_RATE_API_KEY
set url ... | import requests
import pandas as pd
import sqlalchemy as sa
from sqlalchemy.exc import IntegrityError
import os
from time import sleep
from fetch_wazirx import postgres_conn_str
postgres_engine = sa.create_engine(postgres_conn_str)
def main():
api_key = os.environ.get("EXCHANGE_RATE_API_KEY")
url = f"https:... | Python | zaydzuhri_stack_edu_python |
function percentiles cdf_fun percentiles search_start_value=none search_increment_value=0.8 search_probability_convergence=0.03
begin
assert all
set values = list nan * length percentiles
comment TODO Find better initialization of last_value.
if search_start_value is none
begin
set last_value = - 25.0 + 273.15
end
else... | def percentiles(cdf_fun, percentiles,
search_start_value=None, search_increment_value=0.8,
search_probability_convergence=0.03):
assert np.logical_and(percentiles < 1, percentiles > 0).all()
values = [math.nan] * len(percentiles)
# TODO Find better initialization of last_val... | Python | nomic_cornstack_python_v1 |
comment By submitting this assignment, all team members agree to the following:
comment “Aggies do not lie, cheat, or steal, or tolerate those who do”
comment “I have not given or received any unauthorized aid on this assignment”
comment Names: Josh Wood
comment Justin Compton
comment Braden Alexander
comment Troy Hays... | # By submitting this assignment, all team members agree to the following:
# “Aggies do not lie, cheat, or steal, or tolerate those who do”
# “I have not given or received any unauthorized aid on this assignment”
#
# Names: Josh Wood
# Justin Compton
# Braden Alexander
# Troy Hays
# Course/Section: ENGR 102-522
... | Python | zaydzuhri_stack_edu_python |
from abc import ABCMeta , abstractmethod
import datetime
class AbstractTaste
begin
function __init__ self sweetness=0.0 sourness=0.0 saltiness=0.0 bitterness=0.0 savory=0.0
begin
call __init__
set bitterness = bitterness
set saltiness = saltiness
set savory = savory
set sourness = sourness
set sweetness = sweetness
end... | from abc import ABCMeta, abstractmethod
import datetime
class AbstractTaste(metaclass=ABCMeta):
def __init__(self, sweetness=0.0, sourness=0.0, saltiness=0.0, bitterness=0.0, savory=0.0):
super().__init__()
self.bitterness = bitterness
self.saltiness = saltiness
self.savory = savor... | Python | zaydzuhri_stack_edu_python |
string How many ways are there for a taxi driver to get from the top left of a grid city to the bottom right? The city is exactly 10 blocks in each direction, all streets are two ways, and you know the city well enough that you'd balk if the driver actually went drove away from the goal - so never up or left, only righ... | """How many ways are there for a taxi driver to get from the top left
of a grid city to the bottom right? The city is exactly 10 blocks in
each direction, all streets are two ways, and you know the city well
enough that you'd balk if the driver actually went drove away from the
goal - so never up or left, only right an... | Python | zaydzuhri_stack_edu_python |
function define_overlap_operations self
begin
set _d_i = lambda q -> call roll q - 1 axis=- 1 - q
set _d_j = lambda q -> call roll q - 1 axis=- 2 - q
end function | def define_overlap_operations(self):
self._d_i = lambda q:np.roll(q,-1,axis=-1) - q
self._d_j = lambda q:np.roll(q,-1,axis=-2) - q | Python | nomic_cornstack_python_v1 |
function get_user_data_by_id self user_id
begin
return dictionary get __users user_id none
end function | def get_user_data_by_id(self, user_id: str) -> entity.EntityDesignInfo:
return dict(self.__users.get(user_id, None)) | Python | nomic_cornstack_python_v1 |
function append self element
begin
set temp = call Node element
set size = size + 1
if call isEmpty
begin
set head = temp
set tail = temp
end
else
begin
set right = temp
set tail = temp
end
end function | def append(self, element):
temp = Node(element)
self.size += 1
if self.isEmpty():
self.head = temp
self.tail = temp
else:
self.tail.right = temp
self.tail = temp | Python | nomic_cornstack_python_v1 |
comment Word - Break : Leetcode - 139
class Solution
begin
function wordBreak self s wordDict
begin
set wordSet = set wordDict
set a = list false * length s + 1
set a at 0 = true
for i in range length s
begin
for j in range i + 1 length s + 1
begin
if s at slice i : j : in wordSet and a at i == true
begin
set a at j =... | # Word - Break : Leetcode - 139
class Solution:
def wordBreak(self, s:str, wordDict):
wordSet = set(wordDict)
a = [False] * (len(s) + 1)
a[0] = True
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
if s[i:j] in wordSet and a[i] == True:
... | Python | zaydzuhri_stack_edu_python |
string 164 Maximum Gap Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements. You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integ... | """
164 Maximum Gap
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Return 0 if the array contains less than 2 elements.
You may assume all elements in the array are non-negative integers and fit in the 32-bit si... | Python | zaydzuhri_stack_edu_python |
function test_raw_dat_arb_name self
begin
set arbitrary_name = string my_trace.dat
move string trace.dat arbitrary_name
set trace = call FTrace arbitrary_name
assert true has attribute trace string sched_switch
assert true length data_frame > 0
end function | def test_raw_dat_arb_name(self):
arbitrary_name = "my_trace.dat"
shutil.move("trace.dat", arbitrary_name)
trace = trappy.FTrace(arbitrary_name)
self.assertTrue(hasattr(trace, "sched_switch"))
self.assertTrue(len(trace.sched_switch.data_frame) > 0) | Python | nomic_cornstack_python_v1 |
import pygame
call init
set w = 500
set h = 500
set r = 50
set x = w / 2 - r
set y = h / 2 - r
set vx = 0
set vy = 0
set v = 500
set screen = call set_mode list w h
call set_caption string Primer - pygame
set bg = load image string assets/images/bg.jpg
set origShip = load image string assets/images/ship.png
set origShi... | import pygame
pygame.init()
w = 500
h = 500
r = 50
x = w / 2 - r
y = h / 2 - r
vx = 0
vy = 0
v = 500
screen = pygame.display.set_mode([w, h])
pygame.display.set_caption("Primer - pygame")
bg = pygame.image.load("assets/images/bg.jpg")
origShip = pygame.image.load("assets/images/ship.png")
origShip = pygame.transform... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from rbm import RBM
class ARBM
begin
function __init__ self n_visible n_hidden n_adaptive sample_visible=false learning_rate=0.01 momentum=0.95 cdk_level=1
begin
print string ARBM:
print format string Number of visible units: {} n_visible format string Number of hidden units: {} n_hidden format strin... | import numpy as np
from rbm import RBM
class ARBM:
def __init__(
self,
n_visible,
n_hidden,
n_adaptive,
sample_visible=False,
learning_rate=0.01,
momentum=0.95,
cdk_level=1,
):
print("ARBM:")
print(
... | Python | zaydzuhri_stack_edu_python |
import pygame
call init
set display_width = 800
set display_height = 600
set gameDisplay = call set_mode tuple display_width display_height
call set_caption string Card test
set black = tuple 0 0 0
set white = tuple 0 255 0
set clock = call Clock
set crashed = false
set carImg = load image string ./sprites/cards/2C.png... | import pygame
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Card test')
black = (0,0,0)
white = (0,255,0)
clock = pygame.time.Clock()
crashed = False
carImg = pygame.image.load('./sprites/c... | Python | zaydzuhri_stack_edu_python |
function test_url_helper_kwarg
begin
set urlh = call URLHelper
set args = list
set kwargs = dict string foo string bar
set url = call build_url *args keyword kwargs
assert url == string https://archive.gemini.edu/jsonsummary/notengineering/NotFail/foo=bar
end function | def test_url_helper_kwarg():
urlh = URLHelper()
args = []
kwargs = {"foo": "bar"}
url = urlh.build_url(*args, **kwargs)
assert url == "https://archive.gemini.edu/jsonsummary/notengineering/NotFail/foo=bar" | Python | nomic_cornstack_python_v1 |
for item in listShapes
begin
print call toString
print string Area: + string call area
print string Perimeter: + string call perimeter
end | for item in listShapes:
print(item.toString())
print("Area: " + str(item.area()))
print("Perimeter: " + str(item.perimeter()))
| Python | zaydzuhri_stack_edu_python |
comment import libraries
import pandas as pd
from sklearn import tree
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
comment load the dataset
set df = read csv string data.csv
comment separate the feature columns from the target column
set X = drop df string medical_cond... | # import libraries
import pandas as pd
from sklearn import tree
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
# load the dataset
df = pd.read_csv('data.csv')
# separate the feature columns from the target column
X = df.drop('medical_condition', axis=1)
y = df['medical... | Python | iamtarun_python_18k_alpaca |
from selenium import webdriver
from selenium.webdriver.common import keys
import requests
from bs4 import BeautifulSoup as bs
import time
import os
set search_input = input string Type defect here:
set output_path_directory = input string Crete a folder:
set output_path_directory = get current directory + string / + ou... | from selenium import webdriver
from selenium.webdriver.common import keys
import requests
from bs4 import BeautifulSoup as bs
import time
import os
search_input = input('Type defect here:')
output_path_directory = input('Crete a folder:')
output_path_directory = os.getcwd()+'/'+output_path_directory
if not os.path... | Python | zaydzuhri_stack_edu_python |
comment Filtering out strings without letter 'a'
set filtered_words = list comprehension word for word in words if string a in word
comment Print the filtered list
print filtered_words
comment Output: ['apple', 'banana', 'grape'] | # Filtering out strings without letter 'a'
filtered_words = [word for word in words if 'a' in word]
# Print the filtered list
print(filtered_words)
# Output: ['apple', 'banana', 'grape'] | Python | jtatman_500k |
string 小明去超市购买水果,账单如下 苹果 32.8 香蕉 22 葡萄 15.5
set info1 = dict string 苹果 32.8 ; string 香蕉 22 ; string 葡萄 15.5
string 小明,小刚去超市里购买水果 小明购买了苹果,草莓,香蕉,小刚购买了葡萄,橘子,樱桃, 请从下面的描述的字典中,计算每个人花费的金额,并写入到money字段里。 以姓名做key,value仍然是字典
comment 水果和单价
set friuts = dict string 苹果 12.3 ; string 草莓 4.5 ; string 香蕉 6.3 ; string 葡萄 5.8 ; string 橘子... | '''
小明去超市购买水果,账单如下
苹果 32.8
香蕉 22
葡萄 15.5
'''
info1={"苹果":32.8,"香蕉":22,"葡萄":15.5}
'''
小明,小刚去超市里购买水果
小明购买了苹果,草莓,香蕉,小刚购买了葡萄,橘子,樱桃,
请从下面的描述的字典中,计算每个人花费的金额,并写入到money字段里。
以姓名做key,value仍然是字典
'''
friuts = {"苹果":12.3,"草莓":4.5,"香蕉":6.3,"葡萄":5.8,"橘子":6.4,"樱桃":15.8}# 水果和单价
info = {
"小明": {"fruits":{"苹果":4, "草莓":13,"香蕉" :10}... | Python | zaydzuhri_stack_edu_python |
comment This Python 3 environment comes with many helpful analytics libraries installed
comment It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
comment For example, here's several helpful packages to load in
from __future__ import division
import matplotlib.pyplot as plt
import ... | # This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
impo... | Python | zaydzuhri_stack_edu_python |
function retrieve_token filename
begin
with open filename string r as f
begin
set token = read line f
return token
end
end function | def retrieve_token(filename):
with open(filename, 'r') as f:
token = f.readline()
return token | Python | nomic_cornstack_python_v1 |
function arm_up self
begin
assert connected
assert connected
call run_forever speed_sp=900
while not is_pressed
begin
sleep 0.01
end
call stop stop_action=string brake
call beep
end function | def arm_up(self):
assert self.touch_sensor.connected
assert self.arm_motor.connected
self.arm_motor.run_forever(speed_sp=900)
while not self.touch_sensor.is_pressed:
time.sleep(0.01)
self.arm_motor.stop(stop_action="brake")
ev3.Sound.beep() | Python | nomic_cornstack_python_v1 |
function prepareSentimentDataset df sentcol=string sentiment listcol=string token labelthreshold_pos=1 labelthreshold_neg=- 1 keep_neutral=false train_ratio=1
begin
if not keep_neutral
begin
set data = df at call logical_or loc at tuple slice : : sentcol >= labelthreshold_pos loc at tuple slice : : sentcol <= lab... | def prepareSentimentDataset(df,sentcol='sentiment',listcol='token',labelthreshold_pos = 1,labelthreshold_neg = -1,\
keep_neutral = False,train_ratio = 1):
if not keep_neutral:
data = df[np.logical_or(df.loc[:,sentcol]>=labelthreshold_pos,df.loc[:,sentcol]<=labelthresh... | Python | nomic_cornstack_python_v1 |
import sqlite3
from utilityfuncs import *
from prettytable import from_db_cursor
function VRates
begin
string Function to view rates. Loads rate values from the database file into a prettytable object and prints the prettytable table so formed.
print string Current Rates are:
set sections = list string Membership_Fees ... | import sqlite3
from utilityfuncs import *
from prettytable import from_db_cursor
def VRates():
'''
Function to view rates.
Loads rate values from the database file into a prettytable object and prints the prettytable table so formed.
'''
print("Current Rates are:\n")
sections = ["Membership_Fe... | 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.