code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import re
from parsers.LineParser import LineParser
from parsers.RegexpBuilder import RegexpBuilder
class ShParser extends LineParser
begin
function __init__ self
begin
call __init__ self
end function
function parseLine self line
begin
assert line
set rb = call RegexpBuilder
set cmdTextRegexp = string (?P<text>.*)
set ... | import re
from parsers.LineParser import LineParser
from parsers.RegexpBuilder import RegexpBuilder
class ShParser(LineParser):
def __init__(self):
LineParser.__init__(self)
def parseLine(self, line):
assert line
rb = RegexpBuilder()
cmdTextRegexp = r'(?P<text>.*)'
regexpSource = rb.startsWith('sh') +... | Python | zaydzuhri_stack_edu_python |
import io
import xml.etree.ElementTree as xml
from collections import Iterator
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
function get_pdf_pages filepath
begin
with open filepath st... | import io
import xml.etree.ElementTree as xml
from collections import Iterator
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
def get_pdf_pages(filepath: str):
with open(filepath... | Python | zaydzuhri_stack_edu_python |
string Global and local Scopes Scopes and Namespaces When an object is assigned to a variable # a = 10 that variable points to some object and we say that the variable (name) is bound to that object That object can be accessed using that name in various parts of our code # ### I can't reference that (a) just anywhere i... | """ Global and local Scopes
Scopes and Namespaces
When an object is assigned to a variable # a = 10
that variable points to some object
and we say that the variable (name) is bound to that object
That object can be accessed using that name in various parts of our code... | Python | jtatman_500k |
function csrf_token
begin
return call jsonify dict string token call generate_csrf_token
end function | def csrf_token():
return api_util.jsonify({
'token': view_helpers.generate_csrf_token()
}) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import re
function is_board_valid board
begin
set M = length board
set N = length board at 0
if M is not N
begin
return false
end
comment check duplicates in cols and rows
for i in range 0 M
begin
set rows = list 0 * 9
set cols = list 0 * 9
set row = i
for j in range 0 M
begin
set val = in... | #!/usr/bin/env python3
import re
def is_board_valid(board):
M = len(board)
N = len(board[0])
if M is not N:
return False
# check duplicates in cols and rows
for i in range(0, M):
rows = [0] * 9
cols = [0] * 9
row = i
for j in range(0, M):
val =... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
import traceback
import re
function gethtmlText url code=string utf-8
begin
comment print("text1")
try
begin
set r = get requests url
call raise_for_status
set encoding = code
comment print("text2")
return text
end
except ConnectionError
begin
return string
end
end functio... | import requests
from bs4 import BeautifulSoup
import traceback
import re
def gethtmlText(url, code="utf-8"):
#print("text1")
try:
r = requests.get(url)
r.raise_for_status()
r.encoding = code
#print("text2")
return r.text
except requests.exceptions.ConnectionError:... | Python | zaydzuhri_stack_edu_python |
import numpy
set A = list 0 1 2 3 4 5 6 7 8
set B = list 5 10 10 10 15
set C = list 0 1 2 4 6 8
set D = list 6 7 11 12 13 15
set E = list 9 0 0 3 3 3 6 6 | import numpy
A = [0,1,2,3,4,5,6,7,8]
B = [5,10,10,10,15]
C = [0,1,2,4,6,8]
D = [6,7,11,12,13,15]
E = [9,0,0,3,3,3,6,6]
| Python | zaydzuhri_stack_edu_python |
function addVertexInfluence self *args
begin
return call VertexInfluenceSet_addVertexInfluence self *args
end function | def addVertexInfluence(self, *args):
return _osgAnimation.VertexInfluenceSet_addVertexInfluence(self, *args) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string This is the state class
from models.base_model import BaseModel , Base
from sqlalchemy import Column , Integer , String , DateTime , ForeignKey
from sqlalchemy.orm import relationship
import os
class State extends BaseModel Base
begin
string This is the class for State Attributes: name:... | #!/usr/bin/python3
"""This is the state class"""
from models.base_model import BaseModel, Base
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship
import os
class State(BaseModel, Base):
"""This is the class for State
Attributes:
name: input nam... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import torch
import torch.nn as nn
import gym
set LR = 0.01
set GAMMA = 0.95
set DISPLAY_REWARD_THRESHOLD = 400
set ENV_NAME = string CartPole-v0
set RENDER = false
class Net extends Module
begin
function __init__ self s_dim a_dim
begin
call __init__
set fc1 = linear s_dim 30
call normal_ 0 0.1
set f... | import numpy as np
import torch
import torch.nn as nn
import gym
LR = 0.01
GAMMA = 0.95
DISPLAY_REWARD_THRESHOLD = 400
ENV_NAME = 'CartPole-v0'
RENDER = False
class Net(nn.Module):
def __init__(self, s_dim, a_dim):
super(Net, self).__init__()
self.fc1 = nn.Linear(s_dim, 30)
... | Python | zaydzuhri_stack_edu_python |
function GetPartitions self request global_params=none
begin
set config = call GetMethodConfig string GetPartitions
return call _RunMethod config request global_params=global_params
end function | def GetPartitions(self, request, global_params=None):
config = self.GetMethodConfig('GetPartitions')
return self._RunMethod(
config, request, global_params=global_params) | Python | nomic_cornstack_python_v1 |
function readfile self fname
begin
if is file path fname
begin
try
begin
set data = call genfromtxt fname dtype=str delimiter=string ,
end
except any
begin
return list
end
set numcols = shape at - 1
try
begin
set date = array list comprehension call _set_date_ d for d in data at tuple slice : : 0
end
except any
beg... | def readfile(self,fname):
if os.path.isfile(fname):
try:
data = np.genfromtxt(fname,dtype = str, delimiter = ',')
except:
return []
numcols = data.shape[-1]
try:
date = np.array([self._set_date_(d) for d in data[:,0]... | Python | nomic_cornstack_python_v1 |
function sec2hms seconds
begin
set tuple hours seconds = divide mod seconds 60 ^ 2
set tuple minutes seconds = divide mod seconds 60
return tuple integer hours integer minutes seconds
end function | def sec2hms(seconds):
hours, seconds = divmod(seconds, 60**2)
minutes, seconds = divmod(seconds, 60)
return int(hours), int(minutes), seconds | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
comment snake.py
comment Darío Lumbreras
comment Marzo 27, 2013
import cairo
import gobject
import gtk
import random
class Snake
begin
function __init__ self delta rows cols
begin
set delta = delta
set rows = rows
set cols = cols
set width = delta * rows
set height... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# snake.py
# Darío Lumbreras
# Marzo 27, 2013
import cairo
import gobject
import gtk
import random
class Snake:
def __init__(self, delta, rows, cols):
self.delta = delta
self.rows = rows
self.cols = cols
self.width = self.delta * self.rows
self.he... | Python | zaydzuhri_stack_edu_python |
import os
import json
import re
import codecs
import sys
set input_file = argv at 1
set output_file = argv at 2
set measurement_units = list string ft string sqft string meter string mt string sq string feet string meters string mts
function contains_url input
begin
set res = find all string https?://[^\s]* input
if le... | import os
import json
import re
import codecs
import sys
input_file = sys.argv[1]
output_file = sys.argv[2]
measurement_units = ['ft','sqft','meter','mt','sq','feet','meters','mts']
def contains_url(input):
res = re.findall('https?://[^\s]*',input);
if(len(res)>0):
return True
else:
return False
def conv... | Python | zaydzuhri_stack_edu_python |
function integrate_axis_py obj **kwargs
begin
comment import the helper functions
import hlr_utils
comment set up for working through data
set o_descr = call get_descr obj
if o_descr == string number or o_descr == string list
begin
raise call RuntimeError string Must provide a SOM of a SO to the function.
end
else
begi... | def integrate_axis_py(obj, **kwargs):
# import the helper functions
import hlr_utils
# set up for working through data
o_descr = hlr_utils.get_descr(obj)
if o_descr == "number" or o_descr == "list":
raise RuntimeError("Must provide a SOM of a SO to the function.")
# Go on
else:
... | Python | nomic_cornstack_python_v1 |
function evaluate_random_function f x y
begin
if f at 0 == string x
begin
return x
end
else
if f at 0 == string y
begin
return y
end
else
if f at 0 == string sin_pi
begin
return sin pi * call evaluate_random_function f at 1 x y
end
else
if f at 0 == string cos_pi
begin
return cos pi * call evaluate_random_function f at... | def evaluate_random_function(f, x, y):
if f[0]=="x":
return x
elif f[0]=="y":
return y
elif f[0]=="sin_pi":
return sin(pi*evaluate_random_function(f[1],x,y))
elif f[0]=="cos_pi":
return cos(pi*evaluate_random_function(f[1],x,y))
elif f[0]=="prod":
return ... | Python | nomic_cornstack_python_v1 |
comment Write a function `req_to_json(filename)`
comment that takes in the name of a `requirements.txt` file
comment and converts it to json.
import json
function req_to_json filename
begin
with open filename string r as file_object
begin
set lines = read lines file_object
comment print(lines)
set dictionary = dict
fo... | # Write a function `req_to_json(filename)`
# that takes in the name of a `requirements.txt` file
# and converts it to json.
import json
def req_to_json(filename):
with open(filename, 'r') as file_object:
lines = file_object.readlines()
# print(lines)
dictionary = {}
for line in ... | Python | zaydzuhri_stack_edu_python |
function getNodesToWatch self passiveNodes thinNodes
begin
if not passiveNodes
begin
return dict
end
set passiveNodeNames = sorted keys passiveNodes
set thinNodeNames = sorted keys thinNodes
comment distribute thin nodes in round-robin fashion to passive nodes
set nodesToWatch = dictionary comprehension node : dict f... | def getNodesToWatch(self, passiveNodes, thinNodes):
if not passiveNodes:
return {}
passiveNodeNames = sorted(passiveNodes.keys())
thinNodeNames = sorted(thinNodes.keys())
# distribute thin nodes in round-robin fashion to passive nodes
nodesToWatch = {
no... | Python | nomic_cornstack_python_v1 |
function my_enumerate my_list
begin
string Our version of the enumerate function. https://docs.python.org/dev/library/functions.html#enumerate This function takes a list, and returns a nested list, where each inner list contains the index and the element of the original list at that index. Arguments: my_list (list): A ... | def my_enumerate(my_list):
"""Our version of the enumerate function.
https://docs.python.org/dev/library/functions.html#enumerate
This function takes a list, and returns a nested list, where each
inner list contains the index and the element of the original
list at that index.
Argume... | Python | zaydzuhri_stack_edu_python |
function _articles_filter name
begin
set exclude = tuple string de string des string au string aux string en string le string la string les string et string un string une string du string à
set produit = lower name
set produit = split produit string
for e in exclude
begin
for x in produit
begin
if x in e
begin
try
begi... | def _articles_filter(name):
exclude = ("de", "des", "au", "aux", 'en', "le",
"la", "les", "et", "un", "une", "du", "à")
produit = name.lower()
produit = produit.split(" ")
for e in exclude:
for x in produit:
if x in e:
... | Python | nomic_cornstack_python_v1 |
function comment_on_sha owner repo comment sha path token=none
begin
set url = format string https://api.github.com/repos/{owner}/{repo}/commits/{sha}/comments owner=owner repo=repo sha=sha
if token is none
begin
set token = call get_github_auth at 1
end
set headers = dict string Authorization format string token {} to... | def comment_on_sha(owner, repo, comment, sha, path, token=None):
url = "https://api.github.com/repos/{owner}/{repo}/commits/{sha}/comments".format(
owner=owner, repo=repo, sha=sha
)
if token is None:
token = get_github_auth()[1]
headers = {
'Authorization': 'token {}'.format(tok... | Python | nomic_cornstack_python_v1 |
import random
import matplotlib.pyplot as plt
import csv
import numpy as np
set numberOfGenerations = 5000
set populationSize = 50
set tournamentSize = 2
comment mRs = [0.01, 0.02, 0.05, 0.1, 0.5, 0.75]
set mutationRate = 0.75
comment -range to +range
set numRange = 2
comment Ss = [1e-3, 1e-2, 1e-1, 1, 10]
set sigma = ... | import random
import matplotlib.pyplot as plt
import csv
import numpy as np
numberOfGenerations = 5000
populationSize = 50
tournamentSize = 2
# mRs = [0.01, 0.02, 0.05, 0.1, 0.5, 0.75]
mutationRate = 0.75
numRange = 2 # -range to +range
# Ss = [1e-3, 1e-2, 1e-1, 1, 10]
sigma = 0.01
def createSamples():
x = np.a... | Python | zaydzuhri_stack_edu_python |
function normalUpdate y Sigma m0 V0 A=none
begin
set y = call _process_observations y
set tuple N Dy = shape
set Dx = length m0
assert ndim == 2 and shape at 0 == shape at 1 == Dy msg string Sigma must be Dy x Dy covariance
assert ndim == 2 and shape at 0 == shape at 1 == Dx msg string V0 must be Dx x Dx covariance
ass... | def normalUpdate(y, Sigma, m0, V0, A=None):
y = _process_observations(y)
N, Dy = y.shape
Dx = len(m0)
assert Sigma.ndim == 2 and Sigma.shape[0] == Sigma.shape[1] == Dy, \
'Sigma must be Dy x Dy covariance'
assert V0.ndim == 2 and V0.shape[0] == V0.shape[1] == Dx, \
'V0 must be Dx x Dx covariance'
as... | Python | nomic_cornstack_python_v1 |
function fetch_MTurk
begin
set data = values
return call Bunch X=as type data at tuple slice : : slice 0 : 2 : string object y=2 * as type data at tuple slice : : 2 float
end function | def fetch_MTurk():
data = _get_as_pd('https://www.dropbox.com/s/f1v4ve495mmd9pw/EN-TRUK.txt?dl=1',
'similarity', header=None, sep=" ").values
return Bunch(X=data[:, 0:2].astype("object"),
y=2 * data[:, 2].astype(np.float)) | Python | nomic_cornstack_python_v1 |
import os
import yaml
import click
import shutil
import subprocess
from click import echo
from port.server import create_app
from port.compile import build_site
from port.host import host_site , unhost_site
from port.fs import FileManager
set base = expand user path string ~/.port
function site_config site_name
begin
s... | import os
import yaml
import click
import shutil
import subprocess
from click import echo
from port.server import create_app
from port.compile import build_site
from port.host import host_site, unhost_site
from port.fs import FileManager
base = os.path.expanduser('~/.port')
def site_config(site_name):
path = os.... | Python | zaydzuhri_stack_edu_python |
function get_course_info
begin
set letter = get args string letter
set number = get args string number
if letter is none or number is none
begin
call abort 400
end
set r = call find_one dict string letter letter ; string number number dict string _id false
if r is not none
begin
return call jsonify r
end
call abort 404... | def get_course_info():
letter = request.args.get('letter')
number = request.args.get('number')
if (letter is None) or (number is None):
abort(400)
r = mongo_client.catalog.courses.find_one({"letter": letter,
"number": number},
... | Python | nomic_cornstack_python_v1 |
class User
begin
function __init__ self name age address
begin
set name = name
set age = age
set address = address
end function
function __str__ self
begin
return string Name: + name + string , Age: + string age + string , Address: + address
end function
end class
class UsersDB
begin
function __init__ self
begin
set us... | class User:
def __init__(self, name, age, address):
self.name = name
self.age = age
self.address = address
def __str__(self):
return "Name: "+ self.name + ", Age: "+ str(self.age) +", Address: "+ self.address
class UsersDB:
def __init__(self):
self.users = []
... | Python | iamtarun_python_18k_alpaca |
function product self product
begin
set _product = product
end function | def product(self, product):
self._product = product | Python | nomic_cornstack_python_v1 |
function gnews self
begin
set feed_url = call get_feed
set feed_data = parse feedparser feed_url
print string
set type_tiny = call Shortener
for data in feed_data at string items
begin
set tiny_url = call short data at string link
comment tiny_url = tinyurl.create_one(data["link"])
print string [33m + data at string t... | def gnews(self):
feed_url = self.get_feed()
feed_data = feedparser.parse(feed_url)
print("")
type_tiny = pyshorteners.Shortener()
for data in feed_data["items"]:
tiny_url = type_tiny.tinyurl.short(data["link"])
#tiny_url = tinyurl.create_one(data["link"])
print('\033[33m' + data["title"] + " : " + St... | Python | nomic_cornstack_python_v1 |
function upload message_data bot
begin
set r = call Request url=string http://api.imgur.com/2/upload.xml
call add_data url encode dict string key string c65c4bc475794794df87407bc1e89789 ; string image message_data at string parsed
try
begin
set response = url open r
end
except URLError
begin
return string Trouble uploa... | def upload(message_data, bot):
r = urllib2.Request(url='http://api.imgur.com/2/upload.xml')
r.add_data(urllib.urlencode({'key' : 'c65c4bc475794794df87407bc1e89789','image' : message_data["parsed"]}))
try:
response = urllib2.urlopen(r)
except urllib2.URLError:
return "Trouble uploading image."
try:
root = Ele... | Python | nomic_cornstack_python_v1 |
for tuple i x in enumerate read
begin
set t = t + x
set a at i + 1 = t
end
print max generator expression i - min a at min n i * d a at n - a at max 0 n - i * d // b for i in range n + 3 ? 1 | for i, x in enumerate(read()):
t += x
a[i + 1] = t
print(max(i - min(a[min(n, i * d)], (a[n] - a[max(0, n - i * d)])) // b for i in range(n + 3 >> 1)))
| Python | jtatman_500k |
function update_compliance_task self id name=none module_name=none schedule=none scope=none enabled=none
begin
string **Description** Update an existing compliance task. **Arguments** - id: the id of the compliance task to be updated. - name: The name of the task e.g. 'Check Docker Compliance'. - module_name: The name ... | def update_compliance_task(self, id, name=None, module_name=None, schedule=None, scope=None, enabled=None):
'''**Description**
Update an existing compliance task.
**Arguments**
- id: the id of the compliance task to be updated.
- name: The name of the task e.g. 'Chec... | Python | jtatman_500k |
import abc
import numpy as np
from scipy.special import expit
from scipy.optimize import fmin_bfgs
from sklearn.gaussian_process.kernels import RBF , WhiteKernel
class ContextualBanditAlgorithm extends object
begin
set __metaclass__ = ABCMeta
decorator abstractmethod
function select_arm self context
begin
pass
end func... | import abc
import numpy as np
from scipy.special import expit
from scipy.optimize import fmin_bfgs
from sklearn.gaussian_process.kernels import RBF, WhiteKernel
class ContextualBanditAlgorithm(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def select_arm(self, context):
pass
@abc.a... | Python | zaydzuhri_stack_edu_python |
from __future__ import unicode_literals
from django.shortcuts import render , redirect
import random
set charStr = string ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
function randWord
begin
set word = string
for i in range 0 random integer 8 16
begin
set word = word + charStr at random integer 0 length charSt... | from __future__ import unicode_literals
from django.shortcuts import render,redirect
import random
charStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def randWord():
word = ""
for i in range(0,random.randint(8,16)):
word += charStr[random.randint(0,len(charStr)-1)]
return word
def in... | Python | zaydzuhri_stack_edu_python |
comment testing pandas out here
string pandas documentation - "https://pandas.pydata.org/pandas-docs/stable/" pandas course on pluralsight (PANDAS FUNDAMENTALS) folder pandas_learning
comment OVERVIEW
comment data input and output
comment indexing and filtering data
comment working with groups
comment creating plots
co... | # testing pandas out here
"""
pandas documentation - "https://pandas.pydata.org/pandas-docs/stable/"
pandas course on pluralsight (PANDAS FUNDAMENTALS)
folder pandas_learning
"""
# OVERVIEW
# data input and output
# indexing and filtering data
# working with groups
# creating plots
# GETTING STARTED
"""... | Python | zaydzuhri_stack_edu_python |
function solve self lam
begin
string Solves the GFL for a fixed value of lambda.
if penalty == string dp
begin
return call solve_dp lam
end
if penalty == string gfl
begin
return call solve_gfl lam
end
if penalty == string gamlasso
begin
return call solve_gfl lam
end
raise exception format string Unknown penalty type: {... | def solve(self, lam):
'''Solves the GFL for a fixed value of lambda.'''
if self.penalty == 'dp':
return self.solve_dp(lam)
if self.penalty == 'gfl':
return self.solve_gfl(lam)
if self.penalty == 'gamlasso':
return self.solve_gfl(lam)
raise Exce... | Python | jtatman_500k |
from csv import DictReader
import collections
import numpy as np
string This module is always available. It provides access to the load data functions.
function load_train_data
begin
string Load training data. :return: input data as numpy array
set fp = open string ../Files/train.csv string rt
set train = dict reader f... | from csv import DictReader
import collections
import numpy as np
"""
This module is always available. It provides access to the
load data functions.
"""
def load_train_data():
"""
Load training data.
:return: input data as numpy array
"""
fp = open("../Files/train.csv", "rt")
train = DictRead... | Python | zaydzuhri_stack_edu_python |
comment encoding: utf-8
comment SSH批量管理工具
comment Version: 1.1 2016/05
comment Author: YT
comment 更新说明:优化处理逻辑,采用单进程
from multiprocessing import Process
import os
import time
import thread
import paramiko
from datetime import datetime
comment --------------initial all constants and variables-------------
comment cmds = ... | # encoding: utf-8
################################################################
# SSH批量管理工具
# Version: 1.1 2016/05
# Author: YT
# 更新说明:优化处理逻辑,采用单进程
################################################################
from multiprocessing import Process
import os
import time
import thread
import paramiko
from datetime i... | Python | zaydzuhri_stack_edu_python |
function get_units self
begin
set result = list
for elements in call _get_results_list
begin
append result elements at 3
end
return result
end function | def get_units(self) -> List[str]:
result = []
for elements in self._get_results_list():
result.append(elements[3])
return result | Python | nomic_cornstack_python_v1 |
function get self vim_uuid=none
begin
set endpoint = format string {}/osm/admin/v1/vim_accounts/{} get OSM_COMPONENTS string NBI-API vim_uuid
set headers = dict string Authorization format string Bearer {} bearer_token ; string Accept string application/json
set response = get __client endpoint headers
return response
... | def get(self, vim_uuid=None):
endpoint = '{}/osm/admin/v1/vim_accounts/{}'.format(self.OSM_COMPONENTS.get('NBI-API'), vim_uuid)
headers = {"Authorization": "Bearer {}".format(self.bearer_token), "Accept": "application/json"}
response = self.__client.get(endpoint, headers)
return response | Python | nomic_cornstack_python_v1 |
function _exch self i j
begin
set tuple pq at i pq at j = tuple pq at j pq at i
set qp at pq at i = i
set qp at pq at j = j
end function | def _exch(self, i, j):
self.pq[i], self.pq[j] = self.pq[j], self.pq[i]
self.qp[self.pq[i]] = i
self.qp[self.pq[j]] = j | Python | nomic_cornstack_python_v1 |
function upload apikey picture resize=none rotation=string 00 noexif=false callback=none
begin
string prepares post for regular upload :param str apikey: Apikey needed for Autentication on picflash. :param str/tuple/list picture: Path to picture as str or picture data. If data a tuple or list with the file name as str ... | def upload(apikey, picture, resize=None, rotation='00', noexif=False,
callback=None):
"""
prepares post for regular upload
:param str apikey: Apikey needed for Autentication on picflash.
:param str/tuple/list picture: Path to picture as str or picture data. \
If data a tuple or list ... | Python | jtatman_500k |
comment !/usr/bin/python
import writeNote , midiNote , random
comment ----------------------------------------------------------------------
comment Input : Number of Tracks, Number of notes, Number of songs in population
comment Output: initialized list with population of songs
comment --------------------------------... | #!/usr/bin/python
import writeNote, midiNote, random
#----------------------------------------------------------------------
# Input : Number of Tracks, Number of notes, Number of songs in population
# Output: initialized list with population of songs
#------------------------------------------------------------... | Python | zaydzuhri_stack_edu_python |
function render_email_comment_detail self comment is_html
begin
raise NotImplementedError
end function | def render_email_comment_detail(self, comment, is_html):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function add_to_SL item
begin
global items
append items item
print format string Item added to the list! You have {} items in list length items
return items
end function
function show_list
begin
if items
begin
print string + string Here is your Shopping list:
for p in items
begin
print p
end
print string
end
else
begi... | def add_to_SL(item):
global items
items.append(item)
print('Item added to the list! You have {} items in list'.format(len(items)))
return items
def show_list():
if items:
print('\n'+'Here is your Shopping list:')
for p in items: print(p)
print('\n')
else:
print('... | Python | zaydzuhri_stack_edu_python |
function __add__ self *args
begin
return call ConstString___add__ self *args
end function | def __add__(self, *args):
return _yarp.ConstString___add__(self, *args) | Python | nomic_cornstack_python_v1 |
function initialize_walker self
begin
set start = random choice N
set walker = list 0 start
end function | def initialize_walker(self):
start = np.random.choice(self.N)
self.walker = [0, start] | Python | nomic_cornstack_python_v1 |
import os
set environ at string TF_CPP_MIN_LOG_LEVEL = string 2
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers , regularizers
from tensorflow.keras.datasets import mnist
comment Use Pandas to load dataset from csv file
import pandas as pd
set tuple tuple X_train y_train tuple X... | import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, regularizers
from tensorflow.keras.datasets import mnist
# Use Pandas to load dataset from csv file
import pandas as pd
(X_train, y_train), (X_test, y_test) = mnist.load_data()... | Python | zaydzuhri_stack_edu_python |
function find_missing_number arr
begin
comment Find the difference between the first element and its index
set difference = arr at 0 - 0
comment Use binary search to find the missing number
set left = 0
set right = length arr - 1
while left <= right
begin
set mid = left + right // 2
comment If the difference between th... | def find_missing_number(arr):
# Find the difference between the first element and its index
difference = arr[0] - 0
# Use binary search to find the missing number
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
# If the difference between the middl... | Python | jtatman_500k |
import pandas as pd
set librettos = read csv string ../data/librettos_dummies.csv
set librettos_theaters = read csv string ../data/librettos_theaters.csv sep=string at list string file_name string inferred_title string inferred_latitude string inferred_longitude
set librettos = concat list librettos librettos_theaters ... | import pandas as pd
librettos = pd.read_csv('../data/librettos_dummies.csv')
librettos_theaters = pd.read_csv('../data/librettos_theaters.csv', sep='\t')[['file_name', 'inferred_title', 'inferred_latitude', 'inferred_longitude']]
librettos = pd.concat([librettos, librettos_theaters], axis=1)
print('Total number of l... | Python | zaydzuhri_stack_edu_python |
function sector_is_commodity sector_name
begin
return call _sector_is sector_name string is_commodity
end function | def sector_is_commodity(sector_name):
return _sector_is(sector_name, 'is_commodity') | Python | nomic_cornstack_python_v1 |
function set_auth_token ngrok_path token config_path=none
begin
set start = list ngrok_path string authtoken token string --log=stdout
if config_path
begin
append start format string --config={} config_path
end
set result = check output start
if string Authtoken saved not in string result
begin
raise call PyngrokNgrokE... | def set_auth_token(ngrok_path, token, config_path=None):
start = [ngrok_path, "authtoken", token, "--log=stdout"]
if config_path:
start.append("--config={}".format(config_path))
result = subprocess.check_output(start)
if "Authtoken saved" not in str(result):
raise PyngrokNgrokError("An... | Python | nomic_cornstack_python_v1 |
function valid_input player_num
begin
set player_input = input string Player + string player_num + string enter r to roll the die:
set player_input = lower player_input
while player_input != string r
begin
print string Invalid input
set player_input = input string Player + string player_num + string enter r to roll the... | def valid_input(player_num):
player_input = input("Player "+str(player_num)+ " enter r to roll the die: ")
player_input = player_input.lower()
while player_input != "r":
print("Invalid input")
player_input = input("Player "+str(player_num)+" enter r to roll the die: ")
player_in... | Python | nomic_cornstack_python_v1 |
import pygame
import numpy as np
import random
import time
from navigation_map import NavigationMap
class Simulation_Environment
begin
string The simple simulation environment containing only pedestrians If want to include any other objects, please write another class based on this class
function __init__ self screen_s... | import pygame
import numpy as np
import random
import time
from navigation_map import NavigationMap
class Simulation_Environment:
"""
The simple simulation environment containing only pedestrians
If want to include any other objects, please write another class
based on this class
"""
def __init... | Python | zaydzuhri_stack_edu_python |
function _create_optimizer config=none
begin
if config is none
begin
return adam
end
set algorithm = lower config at string algorithm
if algorithm == string adam
begin
return adam
end
else
if algorithm == string sgd
begin
return sgd momentum=get config string momentum 0.0 nesterov=get config string nesterov false
end
e... | def _create_optimizer(
config: Union[None, Mapping] = None
) -> keras.optimizers.Optimizer:
if config is None:
return keras.optimizers.Adam()
algorithm = config['algorithm'].lower()
if algorithm == 'adam':
return keras.optimizers.Adam()
elif algorithm == 'sgd':
return keras... | Python | nomic_cornstack_python_v1 |
function node_wait_for_power_state task new_state timeout=none
begin
set retry_timeout = timeout or power_state_change_timeout
function _wait
begin
set status = call get_power_state task
if status == new_state
begin
raise call LoopingCallDone retvalue=status
end
comment NOTE(sambetts): Return False to trigger BackOffLo... | def node_wait_for_power_state(task, new_state, timeout=None):
retry_timeout = (timeout or CONF.conductor.power_state_change_timeout)
def _wait():
status = task.driver.power.get_power_state(task)
if status == new_state:
raise loopingcall.LoopingCallDone(retvalue=status)
# NOT... | Python | nomic_cornstack_python_v1 |
function create_order self **params
begin
return call _post string order true data=params
end function | def create_order(self, **params):
return self._post('order', True, data=params) | Python | nomic_cornstack_python_v1 |
function remove_this_factvalue self factvalue_id
begin
string Removes the factvalue for the given factvalue identifier @type factvalue_id: string @param factvalue_id: the factvalue identifier to be removed
for fact in call get_factvalues
begin
if call get_id == factvalue_id
begin
remove node call get_node
break
end
end... | def remove_this_factvalue(self,factvalue_id):
"""
Removes the factvalue for the given factvalue identifier
@type factvalue_id: string
@param factvalue_id: the factvalue identifier to be removed
"""
for fact in self.get_factvalues():
if fact.get_id() == factval... | Python | jtatman_500k |
function add_enrollment userid pclassid
begin
set data = call get_or_404 userid
set pclass = call get_or_404 pclassid
if not call is_enrolled pclass
begin
call add_enrollment pclass
end
return call redirect call redirect_url
end function | def add_enrollment(userid, pclassid):
data = FacultyData.query.get_or_404(userid)
pclass = ProjectClass.query.get_or_404(pclassid)
if not data.is_enrolled(pclass):
data.add_enrollment(pclass)
return redirect(redirect_url()) | Python | nomic_cornstack_python_v1 |
from src.bill import Bill
from src.extraction import Extraction
from src.lotto import Lotto
function check_input_answ question poss_response
begin
print question
set usr_in = input
while usr_in
begin
if poss_response is NUMBERS or poss_response == string all numbers
begin
try
begin
set usr_in = integer usr_in
end
excep... | from src.bill import Bill
from src.extraction import Extraction
from src.lotto import Lotto
def check_input_answ(question, poss_response):
print(question)
usr_in = input()
while usr_in:
if poss_response is Lotto.NUMBERS or poss_response == 'all numbers':
try:
usr_in = i... | Python | zaydzuhri_stack_edu_python |
for _ in range n
begin
append d integer input
end
sort d
set a = 1
for i in range length d - 1
begin
if d at i < d at i + 1
begin
set a = a + 1
end
end
print a | for _ in range(n):
d.append(int(input()))
d.sort()
a = 1
for i in range(len(d) - 1):
if d[i] < d[i + 1]:
a += 1
print(a) | Python | zaydzuhri_stack_edu_python |
import sys
comment read a line with a single integer
set T = integer input
function dive_into matrix r c visited sol_so_far cur_step R C
begin
comment print('visiting ', r, c)
set matrix at r at c = cur_step
append sol_so_far tuple r c
append visited tuple r c
if length visited == R * C
begin
return true
end
for next_r... | import sys
T = int(input()) # read a line with a single integer
def dive_into(matrix, r, c, visited, sol_so_far, cur_step, R, C):
# print('visiting ', r, c)
matrix[r][c] = cur_step
sol_so_far.append((r,c))
visited.append((r,c))
if len(visited) == R * C:
return True
for next_r in r... | Python | zaydzuhri_stack_edu_python |
function organization_slugs_by_creation
begin
comment Get a list of all the site's organizations from CKAN
set organizations = call call get_action string organization_list data_dict=dict string sort string package_count desc ; string all_fields true ; string include_dataset_count true ; string include_groups true
comm... | def organization_slugs_by_creation():
# Get a list of all the site's organizations from CKAN
organizations = toolkit.get_action("organization_list")(
data_dict={
"sort": "package_count desc",
"all_fields": True,
"include_dataset_count": True,
"include_gro... | Python | nomic_cornstack_python_v1 |
function source_artifact self
begin
return get _values string source_artifact
end function | def source_artifact(self) -> aws_cdk.aws_codepipeline.Artifact:
return self._values.get("source_artifact") | Python | nomic_cornstack_python_v1 |
function action_signal context action_id value
begin
return call action_signal context action_id value
end function | def action_signal(context, action_id, value):
return IMPL.action_signal(context, action_id, value) | Python | nomic_cornstack_python_v1 |
function test_install self
begin
comment This call should not throw an exception
call checked_subprocess_run string { python } -m pip install .
comment Check the version number from `pip info`
set tuple info _ = call checked_subprocess_run string { python } -m pip show { PACKAGE_NAME }
comment The info section from pip... | def test_install(self):
# This call should not throw an exception
checked_subprocess_run(f"{self.python} -m pip install .")
# Check the version number from `pip info`
info, _ = checked_subprocess_run(f"{self.python} -m pip show {PACKAGE_NAME}")
# The info section from pip is fo... | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
set answers = list
end function | def __init__(self):
self.answers = [] | Python | nomic_cornstack_python_v1 |
function _nullable_constraint self key
begin
return _constraints at key at 1
end function | def _nullable_constraint(self, key):
return self._constraints[key][1] | Python | nomic_cornstack_python_v1 |
function updateParameters self parameters
begin
return
end function | def updateParameters(self, parameters):
return | Python | nomic_cornstack_python_v1 |
string Author: Deepak Gujraniya email: deepakgujraniya@gmail.com
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import random
class GenerateGraph extends object
begin
function __init__ self n p D graph_type=string random
begin
set graph = call Graph
set nodes = call generate_nodes n D
comment ... | """
Author: Deepak Gujraniya
email: deepakgujraniya@gmail.com
"""
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import random
class GenerateGraph(object):
def __init__(self, n, p, D, graph_type="random"):
self.graph = nx.Graph()
nodes = self.generate_nodes(n, D)
... | Python | zaydzuhri_stack_edu_python |
function rebin_counts_broadcast x I xo Io ND_portion=1.0
begin
comment overlap map (MxN), where M is input size(x) and N is output size (xo):
set overlap = call clip min=0.0
set portion = overlap / x at slice 1 : : - x at slice : - 1 : at tuple slice : : none
set Io = Io + sum I at tuple slice : : none * ND_p... | def rebin_counts_broadcast(x, I, xo, Io, ND_portion=1.0):
# overlap map (MxN), where M is input size(x) and N is output size (xo):
overlap = (np.minimum(xo[None, 1:], x[1:, None])
- np.maximum(xo[None, :-1], x[:-1, None])).clip(min=0.0)
portion = overlap / (x[1:] - x[:-1])[:, None]
Io += ... | Python | nomic_cornstack_python_v1 |
comment ========================================================================================
comment IMPORTS AND GLOBAL CONFIGURATIONS
comment ========================================================================================
import csv
import os
import time
import datetime
set PROJECTS = list string Closure ... | # ========================================================================================
# IMPORTS AND GLOBAL CONFIGURATIONS
# ========================================================================================
import csv
import os
import time
import datetime
PROJECTS = ['Closure', 'Lang', 'Chart', 'Math', 'Mo... | Python | zaydzuhri_stack_edu_python |
function next_node self value
begin
if not is instance value Node and value is not none
begin
raise call TypeError string next_node must be a Node object
end
else
begin
set __next_node = value
end
end function | def next_node(self, value):
if not isinstance(value, Node) and value is not None:
raise TypeError("next_node must be a Node object")
else:
self.__next_node = value | Python | nomic_cornstack_python_v1 |
function test_config_home_custom_home_dir
begin
set cache_folder = join path call temp_folder string custom
with call environment_append dict string CONAN_USER_HOME cache_folder
begin
set client = call TestClient cache_folder=cache_folder
run string config home
assert cache_folder in out
run string config home --json h... | def test_config_home_custom_home_dir():
cache_folder = os.path.join(temp_folder(), "custom")
with environment_append({"CONAN_USER_HOME": cache_folder}):
client = TestClient(cache_folder=cache_folder)
client.run("config home")
assert cache_folder in client.out
client.run("config h... | Python | nomic_cornstack_python_v1 |
function generate_n_wavs self n forever=false
begin
if n is not none and n >= length path_cache
begin
set n = none
end
else
if forever
begin
set n = none
end
set n_yielded = 0
set i = 0
comment While we haven't seen all the data
while length _iterator_cache != length path_cache
begin
comment If we have already yielded ... | def generate_n_wavs(self, n, forever=False):
if n is not None and (n >= len(self.path_cache)):
n = None
elif forever:
n = None
n_yielded = 0
i = 0
# While we haven't seen all the data
while len(self._iterator_cache) != len(self.path_cache):
... | Python | nomic_cornstack_python_v1 |
function findKthPositive arr k
begin
set s = set arr
set count = 0
set i = 1
while true
begin
if i not in s
begin
set count = count + 1
if count == k
begin
return i
end
end
set i = i + 1
end
end function
print findKthPositive at tuple 2 3 4 7 11 5
print findKthPositive at tuple 1 2 3 4 2 | def findKthPositive(arr, k):
s=set(arr)
count=0
i=1
while True:
if i not in s:
count+=1
if count==k:
return i
i=i+1
print(findKthPositive[2,3,4,7,11], 5)
print(findKthPositive[1,2,3,4], 2) | Python | zaydzuhri_stack_edu_python |
function get_user_details self response
begin
set tuple fullname first_name last_name = call get_user_names get response string fullName
return dict string username get response string username ; string email get response string email ; string fullname fullname ; string first_name first_name ; string last_name last_nam... | def get_user_details(self, response):
fullname, first_name, last_name = self.get_user_names(
response.get('fullName')
)
return {'username': response.get('username'),
'email': response.get('email'),
'fullname': fullname,
'first_na... | Python | nomic_cornstack_python_v1 |
string Monte Carlo Tic-Tac-Toe Player
import random
import poc_ttt_gui
import poc_ttt_provided as provided
comment Constants for Monte Carlo simulator
comment Change as desired
comment Number of trials to run
set NTRIALS = 10
comment Score for squares played by the machine player
set MCMATCH = 1.0
comment Score for squ... | """
Monte Carlo Tic-Tac-Toe Player
"""
import random
import poc_ttt_gui
import poc_ttt_provided as provided
# Constants for Monte Carlo simulator
# Change as desired
NTRIALS = 10 # Number of trials to run
MCMATCH = 1.0 # Score for squares played by the machine player
MCOTHER = 1.0 # Score for squares played by th... | Python | zaydzuhri_stack_edu_python |
class Test
begin
set myvar = 22222
function __init__ self num=1
begin
set num = num
set __num = 122
end function
function get_value self
begin
return __num
end function
function set_value self num
begin
set __num = num
end function
decorator property
function methodA self
begin
print string Hi I am Method A
end functio... | class Test:
myvar = 22222
def __init__(self,num=1):
self.num = num
self.__num = 122
def get_value(self):
return self.__num
def set_value(self,num):
self.__num = num
@property
def methodA(self):
print("Hi I am Method A")
@staticmethod
def meth... | Python | zaydzuhri_stack_edu_python |
function project_coordinator self
begin
return _project_coordinator
end function | def project_coordinator(self):
return self._project_coordinator | Python | nomic_cornstack_python_v1 |
comment This code is written by Taha Jalili at 3/24/2018 : ==>tahajalili@gmail.com<==
comment HOW IT WORKS:
comment This program takes an Integer from user and convert the Integer number into words.
comment For Example: 987 => nine hundred eighty seven.
comment getting user input
set x = input string enter a number:
co... | #This code is written by Taha Jalili at 3/24/2018 : ==>tahajalili@gmail.com<==
#HOW IT WORKS:
#This program takes an Integer from user and convert the Integer number into words.
#For Example: 987 => nine hundred eighty seven.
x = input('enter a number: ') #getting user input
x = str(x) #converting the Integer value ... | Python | zaydzuhri_stack_edu_python |
import time
set starting_time = time
function speed_calc_decorator fun
begin
function run_func
begin
call fun
set function_execution_time = time
set total_time = function_execution_time - function_execution_time
print string Time taken to execute { __name__ } from initial time is of { total_time }
end function
return r... | import time
starting_time = time.time()
def speed_calc_decorator(fun):
def run_func():
fun()
function_execution_time = time.time()
total_time = function_execution_time - function_execution_time
print(f'Time taken to execute {fun.__name__} from initial time is of {total_time}')
return ru... | Python | zaydzuhri_stack_edu_python |
function doubleVowel_finder
begin
set kelime = input string Bir kelime girin:
set vowels = list string a string e string i string o string u
set isaret = string negative
set i = 0
set m = 1
while m < length kelime
begin
if kelime at i in vowels and kelime at m in vowels
begin
set isaret = string Positive
end
set i = i ... | def doubleVowel_finder():
kelime = input("Bir kelime girin:")
vowels=["a", "e", "i", "o", "u"]
isaret="negative"
i=0
m=1
while m < len(kelime):
if kelime[i] in vowels and kelime[m] in vowels:
isaret="Positive"
i=i+1
m=m+1
print(isaret)
do... | Python | zaydzuhri_stack_edu_python |
import math
import sys
set punct = string '.?,!:;-()[]/{}><& | ################################################################################################################################################################################################################################################################################################################################... | Python | zaydzuhri_stack_edu_python |
function dist2cax self
begin
comment TODO: see about using line and built-in dist to point.
set center_fit = call poly1d fit
if orientation == UP_DOWN
begin
set length = shape at 0
end
else
begin
set length = shape at 1
end
set x_data = array range length
set y_data = call center_fit x_data
set idx = integer round leng... | def dist2cax(self) -> float:
# TODO: see about using line and built-in dist to point.
center_fit = np.poly1d(self.fit)
if self.orientation == Orientation.UP_DOWN:
length = self.image.shape[0]
else:
length = self.image.shape[1]
x_data = np.arange(length)
... | Python | nomic_cornstack_python_v1 |
string ============================================================================= Factor analysis. =============================================================================
import torch
import cuda
import linalg as LA
from torch.distributions.multivariate_normal import MultivariateNormal as MVN
comment ---------... | """=============================================================================
Factor analysis.
============================================================================="""
import torch
import cuda
import linalg as LA
from torch.distributions.multivariate_normal import MultivariateNormal as MVN
# ------------... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
from pre_processing import load_images as l_i
from pre_processing import load_file as l_f
import tensorflow.compat.v1 as tf
call disable_v2_behavior
from tensorflow.python.framework import ops
from PIL import Image
import numpy as np
from os import listdir , environ
im... | #!/usr/bin/env python
# coding: utf-8
from pre_processing import load_images as l_i
from pre_processing import load_file as l_f
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from tensorflow.python.framework import ops
from PIL import Image
import numpy as np
from os import listdir, environ
import matpl... | Python | zaydzuhri_stack_edu_python |
comment Make a convertion from kg to lbs
comment Use this formula: $lbs = kg * 2.2046$
comment Make the cell to use variables
set kg = integer input string Enter number:
set lbs = kg * 2.2046
print lbs
string Make calculation of circumference of a circle The cell should define the radius Calculate the circumference by ... | # Make a convertion from kg to lbs
# Use this formula: $lbs = kg * 2.2046$
# Make the cell to use variables
kg = int(input("Enter number: "))
lbs = kg * 2.2046
print(lbs)
"""
Make calculation of circumference of a circle
The cell should define the radius
Calculate the circumference by the formula: c = 2* pi * r
Def... | Python | zaydzuhri_stack_edu_python |
import os
import json
function set_creds creds_file
begin
set creds = dict
set creds at string site = input string Website:
set creds at string username = input string Username:
set creds at string password = input string Password:
set creds at string sheet_id = input string Sheet Id:
dump creds creds_file
close creds... | import os
import json
def set_creds(creds_file):
creds = {}
creds['site'] = input('Website: ')
creds['username'] = input('Username: ')
creds['password'] = input('Password: ')
creds['sheet_id'] = input('Sheet Id: ')
json.dump(creds, creds_file)
creds_file.close()
def get_creds(creds_file)... | Python | zaydzuhri_stack_edu_python |
if is instance a int or is instance a float and a >= 0
begin
set b = input string 小费比例:
if is instance b int or is instance b float
begin
set c = a * b / 100.0
if c % 0.01 >= 0.001
begin
set c = c - c % 0.001
end
end
end | if (isinstance(a, int) or isinstance(a, float)) and a>=0:
b = input(' 小费比例:')
if isinstance(b, int) or isinstance(b, float):
c = a*b/100.
if c%0.01 >= 0.001:
c = c-c%0.001 | Python | zaydzuhri_stack_edu_python |
function map_lines_to_tris line_cells tri_cells
begin
set tri_cells = call asarray tri_cells
set line_cells = call asarray line_cells
sort line_cells axis=1
set nlines = shape at 0
comment Check triangles, element node indices always monotonic
assert shape at 1 == 3
assert all tri_cells at tuple slice : : 0 < tri_ce... | def map_lines_to_tris(line_cells, tri_cells):
tri_cells = np.asarray(tri_cells)
line_cells = np.asarray(line_cells)
line_cells.sort(axis=1)
nlines = line_cells.shape[0]
# Check triangles, element node indices always monotonic
assert tri_cells.shape[1] == 3
assert np.all(tri_cells[:, 0] < t... | Python | nomic_cornstack_python_v1 |
function toggle_full_model self event
begin
set visible = not new
set visible = new
call draw
end function | def toggle_full_model(self, event):
self.csf_surface.visible = not event.new
self.full_csf_surface.visible = event.new
self.scene.mlab.draw() | Python | nomic_cornstack_python_v1 |
function apply_normalization_schedule perc layer_idx
begin
return integer perc - layer_idx * 0.02
end function | def apply_normalization_schedule(perc, layer_idx):
return int(perc - layer_idx * 0.02) | Python | nomic_cornstack_python_v1 |
function _prune_cache self
begin
set default_expiry = call utcnow - time delta minutes=cache_resources_for
for tuple resource_id resource in items local_resource_status
begin
if string cache_until in resource
begin
if call utcnow > resource at string cache_until
begin
call _delete_cache resource_id
end
end
else
if reso... | def _prune_cache(self):
default_expiry = datetime.datetime.utcnow() - datetime.timedelta(minutes=self.cache_resources_for)
for resource_id, resource in self.local_resource_status.items():
if 'cache_until' in resource:
if datetime.datetime.utcnow() > resource['cache_until']:
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import codecs
import sys
call reload sys
call setdefaultencoding string utf-8
class preProcess extends object
begin
function __init__ self arg
begin
call __init__
set arg = arg
end function
end class | # -*- coding: utf-8 -*-
import codecs
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
class preProcess(object):
def __init__(self, arg):
super(preProcess, self).__init__()
self.arg = arg
| Python | zaydzuhri_stack_edu_python |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other):
return not self == other | Python | nomic_cornstack_python_v1 |
function transpose *args
begin
return transpose _almathswig *args
end function | def transpose(*args):
return _almathswig.transpose(*args) | Python | nomic_cornstack_python_v1 |
function raw n
begin
set k = max n
set l = min n
for i in n
begin
for x in n
begin
if i == k and x == l
begin
set p = tuple i l
print p
end
end
end
return
end function
set n = list input string 输入一个列表值:
call raw n
comment 王卓越 | def raw(n):
k=max(n)
l=min(n)
for i in n:
for x in n:
if i==k and x==l:
p=(i,l)
print(p)
return
n=list(input("输入一个列表值:"))
raw(n)
#王卓越
| Python | zaydzuhri_stack_edu_python |
function _build_preprocessor self crop_size=list 224 224
begin
set image_ph = call placeholder float32
comment y1,x1,y2,x2
set cropbox_ph = call placeholder float32 shape=list 4
set img = image_ph - VGG_MEAN
set batch_img = call crop_and_resize call expand_dims img 0 call expand_dims cropbox_ph 0 list 0 crop_size
set i... | def _build_preprocessor(self, crop_size=[224,224]):
self.image_ph = tf.placeholder(tf.float32)
self.cropbox_ph = tf.placeholder(tf.float32, shape=[4]) #y1,x1,y2,x2
img = self.image_ph - self.VGG_MEAN
batch_img = tf.image.crop_and_resize(
tf.expand_dims(img, 0),
... | 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.