code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function verify_fields self payload response
begin
set primary_column = call get_primary_key
set filters = dict name get json name
set db_entity = first filter by query keyword filters
for tuple key value in items payload
begin
if is instance value Iterable and not is instance value str
begin
pass
end
else
if has attri... | def verify_fields(self, payload, response):
primary_column = self.get_primary_key()
filters = {primary_column.name: response.json.get(primary_column.name)}
db_entity = self.schema.Meta.model.query.filter_by(**filters).first()
for key, value in payload.items():
if isinstance(v... | Python | nomic_cornstack_python_v1 |
async function fetch_async self
begin
return await call fetch_async
end function | async def fetch_async(self) -> "DomainConfigMessagingServiceInstance":
return await self._proxy.fetch_async() | Python | nomic_cornstack_python_v1 |
function __init__ self size
begin
set array = list
set size = size
set position = - 1
end function | def __init__(self, size: int):
self.array = []
self.size = size
self.position = -1 | Python | nomic_cornstack_python_v1 |
function get_logs self upload_id token
begin
set tuple data _ headers = json self string post string / { upload_id } /logs token
return tuple data headers
end function | def get_logs(self, upload_id: str, token: str) -> Tuple[dict, dict]:
data, _, headers = self.json('post', f'/{upload_id}/logs', token)
return data, headers | Python | nomic_cornstack_python_v1 |
function debug_paused self
begin
call emit call SIGNAL string debug_paused
end function | def debug_paused(self):
self.emit(QtCore.SIGNAL("debug_paused")) | Python | nomic_cornstack_python_v1 |
from datetime import date
set ano = year
set maior = 0
set menor = 0
for c in range 1 8
begin
set a = integer input format string Digite o {}° ano de nascimento: c
set atual = ano - a
if atual <= 18
begin
set maior = maior + 1
end
else
begin
set menor = menor + 1
end
end
print format string De 7, {} são maiores de idad... | from datetime import date
ano = date.today().year
maior = 0
menor = 0
for c in range(1, 8):
a = int(input('Digite o {}° ano de nascimento:'.format(c)))
atual = ano - a
if atual <= 18:
maior += 1
else:
menor += 1
print('De 7, {} são maiores de idade'.format(maior))
print('E {} são menores... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Nov 6 20:43:55 2018 @author: Trajan
import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge , Lasso
from sklearn.svm import SVR
from config import config
from Parameters impor... | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 6 20:43:55 2018
@author: Trajan
"""
import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge, Lasso
from sklearn.svm import SVR
from config import config
from Param... | Python | zaydzuhri_stack_edu_python |
import argparse
import logging
import math
import pathlib
from typing import Tuple
import numpy
import pandas
import sklearn.metrics as metrics
import torch
import torch.cuda as cuda
import tqdm
from scripts.v1 import model
from scripts.v1 import xval
set LOGGER = call getLogger __name__
set COMPUTE_DEVICE = device if ... | import argparse
import logging
import math
import pathlib
from typing import Tuple
import numpy
import pandas
import sklearn.metrics as metrics
import torch
import torch.cuda as cuda
import tqdm
from scripts.v1 import model
from scripts.v1 import xval
LOGGER = logging.getLogger(__name__)
COMPUTE_DEVICE = torch.de... | Python | zaydzuhri_stack_edu_python |
function compute_angle map_id padding_ratio=padding_ratio map_size=map_size sep=sep freq=freq f_dust=f_dust lMax=lMax lMin=lMin l_step=l_step FWHM=FWHM noise_power=noise_power slope=slope delensing_fraction=delensing_fraction useQU=useQU N_bias=N_bias
begin
comment Step 1, create actual B-mode map
comment maximum ell f... | def compute_angle(map_id,padding_ratio=a.padding_ratio,map_size=a.map_size,sep=a.sep,freq=a.freq,\
f_dust=a.f_dust,lMax=a.lMax,lMin=a.lMin,l_step=a.l_step,FWHM=a.FWHM,noise_power=a.noise_power,\
slope=a.slope,delensing_fraction=a.delensing_fraction,useQU=a.useQU,N_bias=a.N_bias):
... | Python | nomic_cornstack_python_v1 |
function increment_number_served self number
begin
set number_served = number_served + number
end function | def increment_number_served(self,number):
self.number_served+=number | Python | nomic_cornstack_python_v1 |
set sum_of_cubes = 0
set num = integer input string Enter a positive integer:
while num > 0
begin
set digit = num % 10
set sum_of_cubes = sum_of_cubes + digit ^ 3
set num = num // 10
end
print string Sum of cubes of all digits: sum_of_cubes | sum_of_cubes = 0
num = int(input("Enter a positive integer: "))
while num > 0:
digit = num % 10
sum_of_cubes += digit ** 3
num //= 10
print("Sum of cubes of all digits:", sum_of_cubes)
| Python | jtatman_500k |
function get_loader module_or_name
begin
if module_or_name in modules
begin
set module_or_name = modules at module_or_name
if module_or_name is none
begin
return none
end
end
if is instance module_or_name ModuleType
begin
set module = module_or_name
set loader = get attribute module string __loader__ none
if loader is ... | def get_loader(module_or_name):
if module_or_name in sys.modules:
module_or_name = sys.modules[module_or_name]
if module_or_name is None:
return None
if isinstance(module_or_name, ModuleType):
module = module_or_name
loader = getattr(module, '__loader__', None)
... | Python | nomic_cornstack_python_v1 |
import datetime
function convert_epoch_to_datetime epoch
begin
comment Convert milliseconds to seconds
set epoch_seconds = epoch / 1000
comment Create a datetime object from the epoch time
set dt = call utcfromtimestamp epoch_seconds
comment Get the date and time components
set year = year
set month = month
set day = d... | import datetime
def convert_epoch_to_datetime(epoch):
# Convert milliseconds to seconds
epoch_seconds = epoch / 1000
# Create a datetime object from the epoch time
dt = datetime.datetime.utcfromtimestamp(epoch_seconds)
# Get the date and time components
year = dt.year
month = dt.month
... | Python | greatdarklord_python_dataset |
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from scipy import optimize , special
set rcParams at string errorbar.capsize = 3
set rcParams at string lines.linewidth = 3
set rcParams at string lines.markersize = 10
set rcParams at string figure.figsize = tuple 6 * 1 + square root 5 / 2 6
set rcP... | import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
from scipy import optimize, special
plt.rcParams["errorbar.capsize"] = 3
plt.rcParams["lines.linewidth"] = 3
plt.rcParams["lines.markersize"] = 10
plt.rcParams["figure.figsize"] = (6*(1+np.sqrt(5))/2,6)
plt.rcParams["figure.dpi"] = 200
plt.rcParams[... | Python | zaydzuhri_stack_edu_python |
import os , sys
import numpy as np
from gensec.modules import *
from ase.io.trajectory import Trajectory
from ase.io import read , write
import shutil
class Known
begin
string Handling of the known structures Class for keeping of already known structures in order to avoid repetative calculations and generate unique str... | import os, sys
import numpy as np
from gensec.modules import *
from ase.io.trajectory import Trajectory
from ase.io import read, write
import shutil
class Known:
""" Handling of the known structures
Class for keeping of already known structures
in order to avoid repetative calculations
and gener... | Python | zaydzuhri_stack_edu_python |
from gamelib import *
set game = call Game 800 600 string The Smurfs 60
set bk = call Image string maze.png game
set title = call Image string logo.png game
set y = y - 200
set story = call Image string story.png game
call resizeBy - 40
set y = y + 100
set howtoplay = call Image string howtoplay.png game
call resizeBy ... | from gamelib import*
game = Game(800,600,"The Smurfs",60)
bk = Image("maze.png",game)
title = Image("logo.png",game)
title.y -= 200
story = Image("story.png",game)
story.resizeBy(-40)
story.y += 100
howtoplay = Image("howtoplay.png",game)
howtoplay.resizeBy(-40)
howtopla... | Python | zaydzuhri_stack_edu_python |
import requests
import time
from reddit_scraper import models
import re
from django.utils import timezone
comment connect to reddit api
set REDDIT_USERNAME = string
set REDDIT_PASSWORD = string
set APP_ID = string
set APP_SECRET = string
set base_url = string https://www.reddit.com/
set data = dict string grant_typ... | import requests
import time
from reddit_scraper import models
import re
from django.utils import timezone
#connect to reddit api
REDDIT_USERNAME = ''
REDDIT_PASSWORD = ''
APP_ID = ''
APP_SECRET = ''
base_url = 'https://www.reddit.com/'
data = {'grant_type': 'password', 'username': REDDIT_USERNAME, 'password': REDDIT_P... | Python | zaydzuhri_stack_edu_python |
function new_revision self migrator
begin
set revision_name : str = input string Revision Name:
set description_input : str = input string Add a description? Y/[N]: or string N
set description : Optional at str = none
if lower description_input == string y
begin
set description = input string Revision Description:
end
... | def new_revision(self, migrator: DBMigrator):
revision_name: str = input(f"Revision Name: ")
description_input: str = input(f"Add a description? Y/[N]: ") or "N"
description: Optional[str] = None
if description_input.lower() == "y":
description = input(f"Revision Description:... | Python | nomic_cornstack_python_v1 |
function test_redis_processes host
begin
comment Redis server
assert length filter user=string redis comm=string redis-server == 1
comment Redis Sentinel
assert length filter user=string redis comm=string redis-sentinel == 1
end function | def test_redis_processes(host):
# Redis server
assert len(host.process.filter(user='redis', comm='redis-server')) == 1
# Redis Sentinel
assert len(host.process.filter(user='redis', comm='redis-sentinel')) == 1 | Python | nomic_cornstack_python_v1 |
function log_noise_model self x y pflip
begin
return log pflip * sum x != y + log 1.0 - pflip * sum x == y
end function | def log_noise_model(self, x, y, pflip):
return np.log(pflip)*np.sum(x != y) + np.log(1.0-pflip)*np.sum(x == y) | Python | nomic_cornstack_python_v1 |
function ButtonSet InterfaceItemPath Value ButtonName InitiallyDisabled=0
begin
pass
end function | def ButtonSet(InterfaceItemPath: str, Value: Any, ButtonName: str, InitiallyDisabled: int = 0) -> None:
pass | Python | nomic_cornstack_python_v1 |
string Author: Tony Hammack Date: 6 May 2018 Version 1.0 Contact: hammack.tony@gmail.com This is script receives user input to find a baby name. Thanks to Arul John to compile the baby names. I am using the most popular girls and boys names from 2016. You can find that repository at: https://github.com/aruljohn/popular... | '''
Author: Tony Hammack
Date: 6 May 2018
Version 1.0
Contact: hammack.tony@gmail.com
This is script receives user input to find a baby name.
Thanks to Arul John to compile the baby names. I am using the most popular girls and boys names from
2016.
You can find that repository at: https://github.com/aruljohn/popul... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function findWords self board words
begin
string 单词搜索2:https://leetcode-cn.com/problems/word-search-ii/ :type board: List[List[str]] :type words: List[str] :rtype: List[str]
function dfs x y cur_word cur_node board
begin
if string # in cur_node
begin
append result cur_word
end
set tu... | class Solution(object):
def findWords(self, board, words):
"""
单词搜索2:https://leetcode-cn.com/problems/word-search-ii/
:type board: List[List[str]]
:type words: List[str]
:rtype: List[str]
"""
def dfs(x, y, cur_word, cur_node, board):
if '#' in cur... | Python | zaydzuhri_stack_edu_python |
string When planning a vacation, it's very important to know exactly how much you're going to spend.
function hotel_cost nights
begin
return 140 * nights
end function
function plane_ride_cost city
begin
if city == string Charlotte
begin
return 183
end
else
if city == string Tampa
begin
return 220
end
else
if city == st... | """When planning a vacation, it's very important to know exactly how much you're going to spend."""
def hotel_cost(nights):
return 140 * nights;
def plane_ride_cost(city):
if (city == "Charlotte"):
return 183;
elif (city == "Tampa"):
return 220;
elif (city == "Pittsburgh"):
ret... | Python | zaydzuhri_stack_edu_python |
function displayProcs procs
begin
set proc_format = string %-10s %-7s %-24s %-30s / %-30s %-12s %-12s
print proc_format % tuple string Host string Cores string Memory string Job string Frame string Start string Runtime
for proc in procs
begin
print proc_format % tuple split name string / at 0 string %0.2f % reserved_co... | def displayProcs(procs):
proc_format = "%-10s %-7s %-24s %-30s / %-30s %-12s %-12s"
print(proc_format % ("Host", "Cores", "Memory", "Job", "Frame", "Start", "Runtime"))
for proc in procs:
print(proc_format % (proc.data.name.split("/")[0],
"%0.2f" % proc.data.reserved_cor... | Python | nomic_cornstack_python_v1 |
function testCreateStoresNamespaceDescriptions self
begin
set values = list tuple string username/namespace string A namespace description
set list tuple objectID path = call create values
set tag = call one
set value = call one
assert equal string A namespace description value
end function | def testCreateStoresNamespaceDescriptions(self):
values = [(u'username/namespace', u'A namespace description')]
[(objectID, path)] = self.namespaces.create(values)
tag = getTags(paths=[u'fluiddb/namespaces/description']).one()
value = getTagValues([(objectID, tag.id)]).one()
self... | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder , StandardScaler
function pre_na df
begin
set cols = list columns
for col in cols
begin
if dtype == int or dtype == float
begin
fill missing df at col value=mean df at col inplace=t... | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
def pre_na(df):
cols = list(df.columns)
for col in cols:
if df[col].dtype == int or df[col].dtype == float:
df[col].fillna(value = df[... | Python | zaydzuhri_stack_edu_python |
function get_gti_lengths gti
begin
return flatten diff np gti axis=1
end function | def get_gti_lengths(gti):
return np.diff(gti, axis=1).flatten() | Python | nomic_cornstack_python_v1 |
function get_xyz
begin
comment rospy.init_node('closest_xyz', anonymous=True)
set data = call wait_for_message string fiducial_transforms FiducialTransformArray
if length transforms >= 1
begin
print string Detecting fiducials
set x = x
set y = y
set z = z
print x y z
return tuple x y z
end
end function | def get_xyz():
#rospy.init_node('closest_xyz', anonymous=True)
data = rospy.wait_for_message("fiducial_transforms", FiducialTransformArray)
if len(data.transforms) >= 1:
print("Detecting fiducials")
x = data.transforms[0].transform.translation.x
y = data.transforms[0].transform.trans... | Python | nomic_cornstack_python_v1 |
class Cat
begin
function __init__ self pos itens
begin
set pos = pos
set itens = itens
set moves = call setup_moves
end function
function setup_moves self
begin
set moves = dict
set moves at string up = string 0 -1
set moves at string down = string 0 1
set moves at string left = string -1 0
set moves at string right =... | class Cat:
def __init__(self, pos, itens):
self.pos = pos
self.itens = itens
self.moves = self.setup_moves()
def setup_moves(self):
moves = {}
moves['up'] = "0 -1"
moves['down'] = "0 1"
moves['left'] = "-1 0"
moves['right'] = "1 0"
retur... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment In[1]:
from pandas import Series
set Series1 = call Series list 1 2 3 4 5
set Series2 = call Series list 100 200 300 400 500
Series1 + Series2
comment In[2]:
from pandas import Series
set Series1 = call Series list 1 2 3 4 5
set Series2 = call Series list 100 200 300 400 500 600 700
Series... | # coding: utf-8
# In[1]:
from pandas import Series
Series1 = Series([1, 2, 3, 4, 5])
Series2 = Series([100, 200, 300, 400, 500])
Series1 + Series2
# In[2]:
from pandas import Series
Series1 = Series([1, 2, 3, 4, 5])
Series2 = Series([100, 200, 300, 400, 500, 600, 700])
Series1 + Series2
# In[3]:
from pandas ... | Python | zaydzuhri_stack_edu_python |
function header_ax s x=0.5 y=0.5 fontsize=30 ax=none **kwargs
begin
if ax is none
begin
set tuple f ax = call subplots
end
call text x y s fontsize=fontsize ha=string center va=string center keyword kwargs
axis string off
return ax
end function | def header_ax(s, x=.5, y=.5, fontsize=30, ax=None, **kwargs):
if ax is None:
f, ax = plt.subplots()
ax.text(x, y, s, fontsize=fontsize, ha='center', va='center', **kwargs)
ax.axis('off')
return ax | Python | nomic_cornstack_python_v1 |
function logout
begin
return call jsonify dict string msg string Logged out.
end function | def logout():
return jsonify({'msg': 'Logged out.'}) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import func
import sys
set track_length = 3900
set filename = string Times.csv
set df = read csv filename
print string Type "help" to see available commands
set user_input = upper input string
while true
begin
drop df filter regex=string Unnamed: axis=1 inplace=true
if user_input == string HELP
begi... | import pandas as pd
import func
import sys
track_length = 3900
filename = 'Times.csv'
df = pd.read_csv(filename)
print('Type "help" to see available commands')
user_input = input('').upper()
while True:
df.drop(df.filter(regex="Unnamed: "), axis=1, inplace=True)
if user_input == 'HELP':
df.drop(df.filt... | Python | zaydzuhri_stack_edu_python |
function clip_output original warped mode cval clip
begin
if not clip
begin
return
end
set min_val = call nanmin original
set max_val = call nanmax original
set nan_cval = call isnan cval
if mode == string constant
begin
if nan_cval
begin
set preserve_cval = true
end
else
begin
set preserve_cval = min_val <= cval <= ma... | def clip_output(original, warped, mode, cval, clip):
if not clip:
return
min_val = np.nanmin(original)
max_val = np.nanmax(original)
nan_cval = np.isnan(cval)
if mode == 'constant':
if nan_cval:
preserve_cval = True
else:
preserve_cval = min_val <= cv... | Python | nomic_cornstack_python_v1 |
function maskS2clouds image
begin
set orig = image
set qa = select image string pixel_qa
set cloudBitMask = 1 ? 10
set cirrusBitMask = 1 ? 11
set mask = call And call eq 0
return call copyProperties orig call propertyNames
end function | def maskS2clouds(image):
orig = image
qa = image.select('pixel_qa')
cloudBitMask = 1 << 10
cirrusBitMask = 1 << 11
mask = qa.bitwiseAnd(cloudBitMask).eq(0) \
.And(qa.bitwiseAnd(cirrusBitMask).eq(0))
return (image.updateMask(mask).copyProperties(orig, orig.propertyNames())) | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python3
import datetime
print string Problem:
print string Write a Python program to display the current date and time.
print string Solution
print now | #! /usr/bin/env python3
import datetime
print("Problem:\n")
print(" Write a Python program to display the current date and time.\n")
print("Solution\n")
print(datetime.datetime.now())
| Python | zaydzuhri_stack_edu_python |
class Stack
begin
function __init__ self
begin
set item = list
end function
function push self val
begin
append item val
end function
function pop self
begin
try
begin
return pop item
end
except IndexError
begin
print string Stack is empty
end
end function
function top self
begin
try
begin
return item at - 1
end
excep... | class Stack:
def __init__(self):
self.item = []
def push(self,val):
self.item.append(val)
def pop(self):
try: return self.item.pop()
except IndexError: print('Stack is empty')
def top(self):
try:
return self.item[-1]
except IndexError: pri... | Python | zaydzuhri_stack_edu_python |
comment activity = input("Ko tu gribētu šodien darīt? ")
comment if "kino" not in activity.casefold(): #.casefold priekš upper un lowercase burtiem!
comment print("Bet es gribu iet uz kino!")
set name = input string Kā Tevi sauc?
set age = integer input format string Cik Tev gadi, {0}? name
comment if age > 18 and age ... | # activity = input("Ko tu gribētu šodien darīt? ")
#
# if "kino" not in activity.casefold(): #.casefold priekš upper un lowercase burtiem!
# print("Bet es gribu iet uz kino!")
name = input("Kā Tevi sauc? ")
age = int(input("Cik Tev gadi, {0}? ".format(name)))
#if age > 18 and age < 31:
if 18 <= age < 31:... | Python | zaydzuhri_stack_edu_python |
function create project
begin
string :param project: :return:
set source_path = call get_source_path
if not source_path
begin
return call COMPONENT list list
end
set output_slug = string components/plotly/plotly.min.js
set output_path = join path output_directory output_slug
return call COMPONENT includes=list call WE... | def create(project: 'projects.Project') -> COMPONENT:
"""
:param project:
:return:
"""
source_path = get_source_path()
if not source_path:
return COMPONENT([], [])
output_slug = 'components/plotly/plotly.min.js'
output_path = os.path.join(project.output_directory, output_slug)
... | Python | jtatman_500k |
function _append_rupt_aspect_ratio element rupt_aspect_ratio
begin
set rar = call Element NRML04_RUPT_ASPECT_RATIO
set text = string rupt_aspect_ratio
append element rar
end function | def _append_rupt_aspect_ratio(element, rupt_aspect_ratio):
rar = etree.Element(NRML04_RUPT_ASPECT_RATIO)
rar.text = str(rupt_aspect_ratio)
element.append(rar) | Python | nomic_cornstack_python_v1 |
function main
begin
string NAME dipole_plat.py DESCRIPTION gives paleolatitude from given inclination, assuming GAD field SYNTAX dipole_plat.py [command line options]<filename OPTIONS -h prints help message and quits -i allows interactive entry of latitude -f file, specifies file name on command line
if string -h in ar... | def main():
"""
NAME
dipole_plat.py
DESCRIPTION
gives paleolatitude from given inclination, assuming GAD field
SYNTAX
dipole_plat.py [command line options]<filename
OPTIONS
-h prints help message and quits
-i allows interactive entry of latitude
-... | Python | jtatman_500k |
function __init__ self database table_name primary_id=none primary_type=none primary_increment=none auto_create=false
begin
set db = database
set name = call normalize_table_name table_name
set _table = none
set _columns = none
set _indexes = list
set _primary_id = if expression primary_id is not none then primary_id ... | def __init__(
self,
database,
table_name,
primary_id=None,
primary_type=None,
primary_increment=None,
auto_create=False,
):
self.db = database
self.name = normalize_table_name(table_name)
self._table = None
self._columns = None
... | Python | nomic_cornstack_python_v1 |
import math
import json
print directory math
set x = string { "name":"John", "age":30, "city":"New York"}
set y = loads x
print y at string city | import math
import json
print (dir(math))
x = '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)
print (y["city"]) | Python | zaydzuhri_stack_edu_python |
function trigger self username project branch **build_params
begin
string Trigger new build and return a summary of the build.
set method = string POST
set url = format string /project/{username}/{project}/tree/{branch}?circle-token={token} username=username project=project branch=branch token=api_token
if build_params... | def trigger(self, username, project, branch, **build_params):
"""Trigger new build and return a summary of the build."""
method = 'POST'
url = ('/project/{username}/{project}/tree/{branch}?'
'circle-token={token}'.format(
username=username, project=project,
... | Python | jtatman_500k |
function pop_string self length
begin
return pop self string %us % length
end function | def pop_string(self, length):
return self.pop("%us" % length) | Python | nomic_cornstack_python_v1 |
function parse_feed_args argparams arglines
begin
set args = dict
for p in argparams
begin
set ps = split p string = 1
if length ps != 2
begin
raise call ConfigError string Bad feed argument in config: + p
end
set args at ps at 0 = ps at 1
end
for p in arglines
begin
set ps = split p none 1
if length ps != 2
begin
rai... | def parse_feed_args(argparams, arglines):
args = {}
for p in argparams:
ps = p.split("=", 1)
if len(ps) != 2:
raise ConfigError("Bad feed argument in config: " + p)
args[ps[0]] = ps[1]
for p in arglines:
ps = p.split(None, 1)
if len(ps) != 2:
raise ConfigError("Bad argument line in config: " + p)
a... | Python | nomic_cornstack_python_v1 |
from __future__ import annotations
from typing import *
from dataclasses import dataclass , field
from pathlib import Path
import os , sys
decorator dataclass
class DeepsumoYlData
begin
string Class that parses deepsumo_yl prediction output data. Parameters ---------- Attributes ---------- predictedSites : Dictionary p... | from __future__ import annotations
from typing import *
from dataclasses import dataclass, field
from pathlib import Path
import os, sys
@dataclass
class DeepsumoYlData:
"""Class that parses deepsumo_yl prediction output data.
Parameters
----------
Attributes
----------
predict... | Python | zaydzuhri_stack_edu_python |
function preprocess_data data st_net_spec patch_size=51
begin
set s = time
set reuse = AUTO_REUSE
comment Network info
set layer_params = call layerO tuple 1 1 1 string valid
set preprocessing_mode = string ST
if psi1 and psi2 and phi
begin
print string Will perform Scattering...
set psi1 = call fst3d_psi_factory psi1
... | def preprocess_data(data, st_net_spec, patch_size=51):
s = time.time()
reuse = tf.AUTO_REUSE
# Network info
layer_params = layerO((1,1,1), 'valid')
preprocessing_mode = 'ST'
if st_net_spec.psi1 and st_net_spec.psi2 and st_net_spec.phi:
print('Will perform Scattering...')
psi... | Python | nomic_cornstack_python_v1 |
function initialise_conversation_model self
begin
set conversation = call ConversationSystem
comment Set all as alive
for name in string abcde
begin
call addKnowledge list format string {0}-alive name
end
comment And set the requires
call convertPresentToRequires string {0}-alive
end function | def initialise_conversation_model(self):
self.conversation = model.conversation.ConversationSystem()
#
# Set all as alive
for name in 'abcde':
self.conversation.addKnowledge(['{0}-alive'.format(name)])
#
# And set the requires
self.conversation.convert... | Python | nomic_cornstack_python_v1 |
function set_modal_body self
begin
set _modal_body at slice : : = body
end function | def set_modal_body(self,):
self._modal_body[:] = self.body | Python | nomic_cornstack_python_v1 |
import Image
function fold_spiral move_direction line_length
begin
global z
for i in call xrange line_length
begin
call move_direction
call putpixel tuple x y call getpixel tuple z 0
set z = z + 1
end
end function
function move_right
begin
global x
set x = x + 1
end function
function move_down
begin
global y
set y = y ... | import Image
def fold_spiral(move_direction, line_length):
global z
for i in xrange(line_length):
move_direction()
spiral.putpixel((x,y), wire.getpixel((z, 0)))
z += 1
def move_right():
global x
x += 1
def move_down():
global y
y += 1
def move_left():
global x
... | Python | zaydzuhri_stack_edu_python |
function convert_lng_from_degrees value
begin
assert is instance value tuple int float
if value > 180
begin
raise call ValueError string Lattitude in degrees can't be greater than 180
end
else
if value < 0
begin
raise call ValueError string Lattitude in degrees can't be lesser than 0
end
return if expression value < 18... | def convert_lng_from_degrees(value):
assert (isinstance(value, (int, float)))
if value > 180:
raise ValueError("Lattitude in degrees can't be greater than 180")
elif value < 0:
raise ValueError("Lattitude in degrees can't be lesser than 0")
return value if value < 180 else 180 - value | Python | nomic_cornstack_python_v1 |
function get_element self text level=0
begin
set soup = call BeautifulSoup string <soup><fake_root>%s</fake_root></soup> % text string html.parser
return call PrettyElement next_element level
end function | def get_element(self, text, level=0):
soup = BeautifulSoup(
"<soup><fake_root>%s</fake_root></soup>" % text, "html.parser"
)
return PrettyElement(soup.fake_root.next_element, level) | Python | nomic_cornstack_python_v1 |
function pr_error string
begin
call pr_level string ERROR string
end function
function pr_warn string
begin
call pr_level string WARN string
end function
function pr_info string
begin
call pr_level string INFO string
end function
function pr_debug string
begin
call pr_level string DEBUG string
end function | def pr_error(string):
pr_level("ERROR", string)
def pr_warn(string):
pr_level("WARN", string)
def pr_info(string):
pr_level("INFO", string)
def pr_debug(string):
pr_level("DEBUG", string)
| Python | zaydzuhri_stack_edu_python |
string Main python script running all of the bits of code
from overhead import *
function main
begin
set str_list = call txt
print str_list
set code_num = 0
for item in str_list
begin
set code_str = string code { code_num }
set locals at code_str = call Code item
print string Composition of { string locals at code_str ... | '''
Main python script running all of the bits of code
'''
from overhead import *
def main():
str_list = dp.fileReader('codes.txt').txt()
print(str_list)
code_num = 0
for item in str_list:
code_str = f'code{code_num}'
locals()[code_str] = dp.Code(item)
... | Python | zaydzuhri_stack_edu_python |
comment ------------------------------------------------------------------------ #
comment Title: Assignment 09
comment Description: Working with Modules
comment ChangeLog (Who,When,What):
comment RRoot,1.1.2030,Created script
comment RRoot,1.1.2030,Added pseudo-code to start assignment 9
comment Molly Weaver, 03/13/21... | # ------------------------------------------------------------------------ #
# Title: Assignment 09
# Description: Working with Modules
# ChangeLog (Who,When,What):
# RRoot,1.1.2030,Created script
# RRoot,1.1.2030,Added pseudo-code to start assignment 9
# Molly Weaver, 03/13/21, Added code to complete assignmen... | Python | zaydzuhri_stack_edu_python |
async function on_triggered self message
begin
print string This function should be overrated
pass
end function | async def on_triggered(self, message: Message):
print("This function should be overrated")
pass | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sat May 26 11:09:15 2018 @author: Alex
function gcdIter a b
begin
string a, b: positive integers returns: a positive integer, the greatest common divisor of a & b.
comment Your code here
if a < b
begin
set gcd = a
end
else
begin
set gcd = b
e... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 26 11:09:15 2018
@author: Alex
"""
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
if a < b:
gcd = a
else:
gcd =... | Python | zaydzuhri_stack_edu_python |
set s = string a b cc
set q = split s string
print q | s = " a b cc"
q = s.split(" ")
print(q) | Python | zaydzuhri_stack_edu_python |
function is_identity self
begin
if scalar_vector
begin
return all call isclose array call tile list 1.0 0.0 0.0 0.0 tuple shape at 0 1 axis=1
end
return all call isclose array call tile list 0.0 0.0 0.0 1.0 tuple shape at 0 1 axis=1
end function | def is_identity(self) -> np.ndarray:
if self.scalar_vector:
return np.all(np.isclose(self.array, np.tile([1., 0., 0., 0.], (self.array.shape[0], 1))), axis=1)
return np.all(np.isclose(self.array, np.tile([0., 0., 0., 1.], (self.array.shape[0], 1))), axis=1) | Python | nomic_cornstack_python_v1 |
comment hart_barcode.py
import Image , ImageStat
import pdb
import sys
import logging
class BarcodeException extends Exception
begin
string Raised if barcode not properly interpreted
pass
end class
function hart_barcode image x y w h
begin
string read a vertical barcode on a hart ballot, as in getbarcode in PILB
set wh... | # hart_barcode.py
import Image, ImageStat
import pdb
import sys
import logging
class BarcodeException(Exception):
"Raised if barcode not properly interpreted"
pass
def hart_barcode(image,x,y,w,h):
"""read a vertical barcode on a hart ballot, as in getbarcode in PILB"""
whites_list = []
blacks_list... | Python | zaydzuhri_stack_edu_python |
function call self *args
begin
return call *args
end function | def call(self, *args):
return self[tuple(map(self.map.transform, args))](*args) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sun Aug 8 15:47:14 2021 @author: jjw12
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
set first_3d = figure
set first_axes = call axes projection=string 3d
call set_xlabel string X axis
call set_ylabel string Y axis
call set_zla... | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 8 15:47:14 2021
@author: jjw12
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
first_3d = plt.figure()
first_axes = plt.axes(projection='3d')
first_axes.set_xlabel('X axis')
first_axes.set_ylabel('Y axis')
first_axes.set_... | Python | zaydzuhri_stack_edu_python |
function open_new_account cls
begin
print string That is great news, welcome!
execute my_cursor string INSERT INTO client_info(forename, surname, title, mobile_number, password, income) VALUES (%s, %s, %s, %s, %s, %s) tuple call get_first_name call get_last_name call get_title call get_mobile_number call get_new_passwo... | def open_new_account(cls):
print('\nThat is great news, welcome!\n')
my_cursor.execute(
"INSERT INTO client_info(forename, surname, title, mobile_number, password, income) "
"VALUES (%s, %s, %s, %s, %s, %s)",
(
NewAccount.get_first_name(),
... | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template , redirect
from forms import SubmitForm
import xlsxwriter
import time
import datetime as dt
from datetime import date , datetime
from dateutil.relativedelta import relativedelta
import email , smtplib , ssl
from email import encoders
from email.mime.base import MIMEBase
from em... | from flask import Flask, render_template, redirect
from forms import SubmitForm
import xlsxwriter
import time
import datetime as dt
from datetime import date, datetime
from dateutil.relativedelta import relativedelta
import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
f... | Python | zaydzuhri_stack_edu_python |
function price_per_person df
begin
if integer df at string minimum_nights >= 1 and integer df at string guests_included >= 1
begin
return integer df at string price_num * integer df at string minimum_nights + integer df at string cleaning_fee_num / integer df at string minimum_nights * integer df at string guests_inclu... | def price_per_person(df):
if int(df['minimum_nights'])>=1 and int(df['guests_included'])>=1:
return int((df['price_num']*int(df['minimum_nights'])+int(df['cleaning_fee_num']))/(int(df['minimum_nights'])*int(df['guests_included'])))
else: # ignore the missing minimum_nights and guests_included data
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
set files = input
set out = output at 0
function split_exon_fraction files out
begin
set sample_list = list
for file in files
begin
set name = split file string / at 3
set results = dict
set equal = false
for line in open file
begin
if string == in line
begin
set equal = true
end
if not equal
begi... | import pandas as pd
files = snakemake.input
out = snakemake.output[0]
def split_exon_fraction(files, out):
sample_list = []
for file in files:
name = file.split('/')[3]
results = {}
equal = False
for line in open(file):
if '==' in line:
equal = True
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator , FormatStrFormatter
call use string ./tickstyle
with call context string ./tickstyle
begin
set x1 = linear space 0 1 11
set y1 = list 0.52 0.55 0.57 0.6 0.62 0.63 0.6 0.59 0.58 0.54 0.53
set tuple fig ax2 = call subplots n... | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
plt.style.use('./tickstyle')
with plt.style.context(('./tickstyle')):
x1 = np.linspace(0, 1, 11)
y1 = [0.52, 0.55, 0.57, 0.60, 0.62, 0.63, 0.60, 0.59, 0.58, 0.54, 0.53]
fig, (ax2) = plt.sub... | Python | zaydzuhri_stack_edu_python |
for i in A
begin
set total = total + i
end
set average = total / 10
print average | for i in A:
total+= i
average= total/10
print(average)
| Python | zaydzuhri_stack_edu_python |
function put_attributes self domain_or_name item_name attributes replace=true expected_value=none
begin
set tuple domain domain_name = call get_domain_and_name domain_or_name
set params = dict string DomainName domain_name ; string ItemName item_name
call _build_name_value_list params attributes replace
if expected_val... | def put_attributes(self, domain_or_name, item_name, attributes,
replace=True, expected_value=None):
domain, domain_name = self.get_domain_and_name(domain_or_name)
params = {'DomainName' : domain_name,
'ItemName' : item_name}
self._build_name_value_li... | Python | nomic_cornstack_python_v1 |
function __get_tabsize__ self
begin
return call textctrl_info_t_get_tabsize self
end function | def __get_tabsize__(self):
return _ida_kernwin.textctrl_info_t_get_tabsize(self) | Python | nomic_cornstack_python_v1 |
function test_ttl_by_name
begin
set my_column = call Column Timestamp
class Model extends BaseModel
begin
class Meta
begin
set ttl = dict string column string expiry
end class
set id = call Column Integer hash_key=true
set expiry = my_column
end class
assert ttl at string column is my_column
end function | def test_ttl_by_name():
my_column = Column(Timestamp)
class Model(BaseModel):
class Meta:
ttl = {"column": "expiry"}
id = Column(Integer, hash_key=True)
expiry = my_column
assert Model.Meta.ttl["column"] is my_column | Python | nomic_cornstack_python_v1 |
function policy_head self X num_possible_moves reg momentum=0.99 epsilon=0.001
begin
set conv_block = call convolutional_block X num_filters=NEURAL_NETWORKS at string num_filters_policy kernel_size=1 momentum=momentum epsilon=epsilon reg_strength=reg
set flatten = flatten conv_block
set policy = call dense num_possible... | def policy_head(self, X, num_possible_moves, reg, momentum=0.99, epsilon=0.001):
conv_block = self.convolutional_block(
X,
num_filters=config.NEURAL_NETWORKS['num_filters_policy'],
kernel_size=1,
momentum=momentum,
epsilon=epsilon,
reg_stre... | Python | nomic_cornstack_python_v1 |
function read_decoder_files self
begin
comment read the main ISA tables
comment read_isa_
call read_decoder_instruction_file
set all_iforms = call add_iform_indices
call remove_deleted
comment Read the other decoder format tables.
set nts = dict
set ntlufs = dict
for f in decoder_input_files
begin
set lines = read li... | def read_decoder_files(self):
# read the main ISA tables
self.read_decoder_instruction_file() # read_isa_
self.all_iforms = self.add_iform_indices()
self.remove_deleted()
# Read the other decoder format tables.
nts = {}
ntlufs = {}
for f in self.files.de... | Python | nomic_cornstack_python_v1 |
function thin_strength_label self label_matrix
begin
set strength_binary_image = list
set thin_dataframe = list
set thin_binary_labels = list
for tuple i file in enumerate label_matrix
begin
if file is not none
begin
append strength_binary_image zeros shape + file
set thin_binary = call label_thin file
set prop = li... | def thin_strength_label(self, label_matrix):
strength_binary_image = []
thin_dataframe = []
thin_binary_labels = []
for i, file in enumerate(label_matrix):
if file is not None:
strength_binary_image.append(np.zeros(file.shape) + file)
... | Python | nomic_cornstack_python_v1 |
function get_all_attribute_names self
begin
set client = redis_client
set keys = keys client format string {0}{1}at{1}* prefix divider
set attr_names = set list
set thing = compile format string {0}at{0}(.*) divider
for key in keys
begin
set match = search key
if match
begin
add attr_names call groups at 0
end
end
retu... | def get_all_attribute_names(self):
client = self.redis_client
keys = client.keys('{0}{1}at{1}*'.format(self.prefix, self.divider))
attr_names = set([])
thing = re.compile(r'{0}at{0}(.*)'.format(self.divider))
for key in keys:
match = thing.search(key)
if m... | Python | nomic_cornstack_python_v1 |
function register_action function name arguments
begin
set reg_name = lower name
assert reg_name not in ACTIONS msg format string Action {} already registered reg_name
set ACTIONS at reg_name = tuple function arguments
end function | def register_action(function, name, arguments):
reg_name = name.lower()
assert reg_name not in ACTIONS, "Action {} already registered".format(reg_name)
ACTIONS[reg_name] = (function, arguments) | Python | nomic_cornstack_python_v1 |
function __init__ __self__ load_balancer_id security_group_id dry_run=none
begin
set __self__ string load_balancer_id load_balancer_id
set __self__ string security_group_id security_group_id
if dry_run is not none
begin
set __self__ string dry_run dry_run
end
end function | def __init__(__self__, *,
load_balancer_id: pulumi.Input[str],
security_group_id: pulumi.Input[str],
dry_run: Optional[pulumi.Input[bool]] = None):
pulumi.set(__self__, "load_balancer_id", load_balancer_id)
pulumi.set(__self__, "security_group_id", secu... | Python | nomic_cornstack_python_v1 |
import cv2
set detect_face = 0
set detect_eye = 0
set detect_smile = 0
set face_cascade = call CascadeClassifier string C:\haarcascade_frontalcatface.xml
set eye_cascade = call CascadeClassifier string C:\haarcascade_eye_tree_eyeglasses.xml
set smile_cascade = call CascadeClassifier string C:\haarcascade_smile.xml
set ... | import cv2
detect_face=0
detect_eye = 0
detect_smile=0
face_cascade = cv2.CascadeClassifier("C:\haarcascade_frontalcatface.xml")
eye_cascade = cv2.CascadeClassifier("C:\haarcascade_eye_tree_eyeglasses.xml")
smile_cascade= cv2.CascadeClassifier("C:\haarcascade_smile.xml")
cap = cv2.VideoCapture(0)
while 1:
ret, img ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from io import StringIO
class LZWCode
begin
set __autor = format string {}{}{} string |-*****-***-| | string Piotr Bęc string | |-*****-***-|
function __init__ self
begin
set char_arr_size = 0
set tuple encoded_word decoded_code = tuple list 0
set tuple char_arr char_arr_invert = tuple di... | # -*- coding: utf-8 -*-
from io import StringIO
class LZWCode:
__autor = '{}{}{}'.format("|-*****-***-|\n| ", "Piotr Bęc", " |\n|-*****-***-|")
def __init__(self):
self.char_arr_size = 0
self.encoded_word, self.decoded_code = [], 0
self.char_arr, self.char_arr_invert = {}, {}
d... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set site = call Driver
end function | def __init__(self):
self.site = Driver() | Python | nomic_cornstack_python_v1 |
function replace_e s
begin
comment Create an empty output string
set output = string
end function
comment Iterate through the input string | def replace_e(s):
# Create an empty output string
output = ''
# Iterate through the input string | Python | flytech_python_25k |
function check_circular_prime_not_efficient_for_sparse_list n prime_list
begin
set circ_prime_list = list n
set circular_prime_flag = true
set str_n = string n
set length_n = length str_n
if length_n > 1
begin
set str_n2 = str_n + str_n
for j in range length_n - 1
begin
set str_n2 = str_n2 at slice 1 : :
set x = inte... | def check_circular_prime_not_efficient_for_sparse_list(n, prime_list):
circ_prime_list = [n]
circular_prime_flag = True
str_n = str(n)
length_n = len(str_n)
if length_n > 1:
str_n2 = str_n + str_n
for j in range(length_n-1):
str_n2 = str_n2[1:]
x = int(str_n2[... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Feb 18 13:15:37 2021 @author: Pascal
import pandas as pd
class Standardization
begin
function __init__ self df_total
begin
set df_total = df_total
end function
comment Functions for getting mean and std of each feature
function calculate_Standardization self
begin
fun... | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 18 13:15:37 2021
@author: Pascal
"""
import pandas as pd
class Standardization:
def __init__(self, df_total):
self.df_total = df_total
#Functions for getting mean and std of each feature
def calculate_Standardization(self):
def mean_EAR(... | Python | zaydzuhri_stack_edu_python |
function solve_case final_state
begin
set move_list = list
set current_state = list
for i in range length final_state
begin
append current_state 0
end
while call is_done current_state final_state == false
begin
set tuple current_state move = call find_move current_state final_state
append move_list move
end
end funct... | def solve_case(final_state):
move_list = []
current_state = []
for i in range(len(final_state)):
current_state.append(0)
while is_done(current_state, final_state) == False:
current_state, move = find_move(current_state, final_state)
move_list.append(move) | Python | zaydzuhri_stack_edu_python |
function from_dict self dictionary
begin
return call from_dict _capsule dictionary
end function | def from_dict(self, dictionary):
return _settings_lib.from_dict(self._capsule, dictionary) | Python | nomic_cornstack_python_v1 |
import numpy as np
function augment_with_periodic_bc points values domain
begin
string Augment the data to create periodic boundary conditions. Parameters ---------- points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) The points defining the regular grid in n dimensions. values : array_like, shape (m1, ... | import numpy as np
def augment_with_periodic_bc(points, values, domain):
"""
Augment the data to create periodic boundary conditions.
Parameters
----------
points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, )
The points defining the regular grid in n dimensions.
values :... | Python | zaydzuhri_stack_edu_python |
function is_mine self id
begin
if is instance id DomainSpecificString
begin
return call is_mine id
end
else
begin
return call is_mine_id id
end
end function | def is_mine(self, id: Union[str, DomainSpecificString]) -> bool:
if isinstance(id, DomainSpecificString):
return self._hs.is_mine(id)
else:
return self._hs.is_mine_id(id) | Python | nomic_cornstack_python_v1 |
function _prepare_app_env self app test_mode
begin
if test_mode
begin
comment In test mode, set a BRIEFCASE_MAIN_MODULE environment variable
comment to override the module at startup
info string Starting test_suite... prefix=app_name
return dict string env dict string BRIEFCASE_MAIN_MODULE call main_module test_mode
en... | def _prepare_app_env(self, app: AppConfig, test_mode: bool):
if test_mode:
# In test mode, set a BRIEFCASE_MAIN_MODULE environment variable
# to override the module at startup
self.logger.info("Starting test_suite...", prefix=app.app_name)
return {
... | Python | nomic_cornstack_python_v1 |
comment Here if the function needs to take the size of pizza, Then that parameter must come befor parameter *toppings
function make_pizza size *toppings
begin
string Summarize our Pizza
print string Making a pizza of { size } -inch and following topping:
for topping in toppings
begin
print string - { topping }
end
end ... | def make_pizza(size, *toppings): # Here if the function needs to take the size of pizza, Then that parameter must come befor parameter *toppings
"""Summarize our Pizza"""
print(f"\nMaking a pizza of {size}-inch and following topping: ")
for topping in toppings:
print(f"- {topping}")
# I have create... | Python | zaydzuhri_stack_edu_python |
function make_tree self data classes featureNames maxlevel=- 1 level=0
begin
set nData = length data
set nFeatures = length data at 0
try
begin
featureNames
end
except any
begin
set featureNames = featureNames
end
comment List the possible classes
set newClasses = list
for aclass in classes
begin
if count newClasses a... | def make_tree(self,data,classes,featureNames,maxlevel=-1,level=0):
nData = len(data)
nFeatures = len(data[0])
try:
self.featureNames
except:
self.featureNames = featureNames
# List the possible classes
newClasses = []
for aclass in classes:
if newClasses.count(aclass)==0:
newClasses.... | Python | nomic_cornstack_python_v1 |
comment 这个是紧接着类型注解的讲解
import inspect
from inspect import Parameter
from functools import update_wrapper , wraps
function check fn
begin
function wrapper *args **kwargs
begin
set sig = signature fn
set params = parameters
set values = list values params
set flag = true
comment 这里判断的事位置参数,要是传参用的关键字,这里就进不来,判断不了,所以还需要判断下kw... | #这个是紧接着类型注解的讲解
import inspect
from inspect import Parameter
from functools import update_wrapper,wraps
def check(fn):
def wrapper(*args,**kwargs):
sig = inspect.signature(fn)
params = sig.parameters
values = list(params.values())
flag = True
for i,x in enumerate(args): #这里... | Python | zaydzuhri_stack_edu_python |
function import_csv filename
begin
set data_to_analyse = dict correct list ; fixed list ; repeat list ; wrong list
with open filename string r as file
begin
set csvreader = dict reader file fieldnames=keys data_to_analyse
for row in csvreader
begin
append data_to_analyse at correct integer row at correct
append dat... | def import_csv(filename: str) -> dict:
data_to_analyse = {correct: [], fixed: [], repeat: [], wrong: []}
with open(filename, 'r') as file:
csvreader = csv.DictReader(file, fieldnames=data_to_analyse.keys())
for row in csvreader:
data_to_analyse[correct].append(int(row[correct]))
... | Python | nomic_cornstack_python_v1 |
async function download_file self file_id dest
begin
string Download a file to local disk. :param dest: a path or a ``file`` object
set f = await call getFile file_id
try
begin
set d = if expression is instance dest IOBase then dest else open dest string wb
set tuple session request = call download tuple _token f at st... | async def download_file(self, file_id, dest):
"""
Download a file to local disk.
:param dest: a path or a ``file`` object
"""
f = await self.getFile(file_id)
try:
d = dest if isinstance(dest, io.IOBase) else open(dest, 'wb')
session, request = a... | Python | jtatman_500k |
comment !/usr/bin/python
set val = input string Enter a value:
set dict = dict
for index in range 2 val
begin
set dict at index = index * index
end | #!/usr/bin/python
val = input("Enter a value: ")
dict = {}
for index in range(2,val):
dict[index] = index*index | Python | zaydzuhri_stack_edu_python |
class Restaurant
begin
string An attempt to model a restaurant
function __init__ self restaurant_name cuisine_type
begin
string Initializing name and age attributes
set name = restaurant_name
set cuisine = cuisine_type
end function
function describe_restaurant self
begin
comment Describes the restaurant name and cuisin... | class Restaurant():
"""An attempt to model a restaurant"""
def __init__(self,restaurant_name,cuisine_type):
"""Initializing name and age attributes"""
self.name = restaurant_name
self.cuisine = cuisine_type
def describe_restaurant(self):
# Describes the restaurant name... | Python | zaydzuhri_stack_edu_python |
import numpy as np
function prepro img down_sample_factor=2
begin
comment crop
set img = img at tuple slice 150 : 300 : slice 150 : 450 :
comment downsample image
set img = img at tuple slice : : down_sample_factor slice : : down_sample_factor slice : :
comment remove color
set img = mean np img axis=2
if max ... | import numpy as np
def prepro(img, down_sample_factor=2):
img = img[150:300, 150:450] # crop
img = img[::down_sample_factor, ::down_sample_factor, :] # downsample image
img = np.mean(img, axis=2) # remove color
if np.max(img) > 1:
img /= 255. # scale between 0 and 1
return img.astype(np.float)... | Python | zaydzuhri_stack_edu_python |
string madLib.py Richard Burke 2/20/16 This program manipulates lists. Enduser enters the parts of speech requested and the program will insert them into a mad lib.
comment Set up a list which gets the words later get inserted as the enduser inputs them.
set wordList = list
comment Incoming words!
set adjec = call raw... | """ madLib.py
Richard Burke
2/20/16
This program manipulates lists.
Enduser enters the parts of speech requested and the program will
insert them into a mad lib.
"""
#Set up a list which gets the words later get inserted as the enduser inputs them.
wordList = [
]
#Incoming words!
adjec = raw... | Python | zaydzuhri_stack_edu_python |
function data_augmentation im_list mode=string standard tag=false params=none im_size=224 filemode=string local mean_RGB=none
begin
if mean_RGB is none
begin
set mean_RGB = array list 107.59348955 112.1047813 80.9982362
end
else
begin
set mean_RGB = array mean_RGB
end
set rot_ang = list 0 90 180 270
set batch = list
i... | def data_augmentation(im_list, mode='standard', tag=False, params=None, im_size=224,
filemode='local', mean_RGB=None):
if mean_RGB is None:
mean_RGB = np.array([107.59348955, 112.1047813, 80.9982362])
else:
mean_RGB = np.array(mean_RGB)
rot_ang = [0, 90, 180, 270]
... | 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.