code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function main
begin
set curr1 = call Current string Savings string Account1 1 500.0
set sav1 = call Current string Current string Account2 2 100.0
set curr3 = call Current string Current string Account2 3 1000.0
comment bill1 = Bill("phone", 200)
set accounts = list curr1 sav1 curr3
set login = integer input string Ent... | def main():
curr1 = Current("Savings", "Account1", 1, 500.0)
sav1 = Current("Current", "Account2", 2, 100.0)
curr3 = Current("Current", "Account2", 3, 1000.0)
# bill1 = Bill("phone", 200)
accounts = [curr1, sav1, curr3]
login = int(input("Enter you account number: "))
print("Here is the m... | Python | nomic_cornstack_python_v1 |
function list_securitygroup call=none
begin
string Return a list of security group
if call == string action
begin
raise call SaltCloudSystemExit string The list_nodes function must be called with -f or --function.
end
set params = dict string Action string DescribeSecurityGroups ; string RegionId call get_location ; st... | def list_securitygroup(call=None):
'''
Return a list of security group
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
params = {
'Action': 'DescribeSecurityGroups',
'RegionId': get_loc... | Python | jtatman_500k |
from sympy.abc import x , y
from sympy import solve
set s = call solve list x ^ 2 + y ^ 2 - 1 x - y list x y
print string 方程组的解为 s | from sympy.abc import x,y
from sympy import solve
s=solve([x**2+y**2-1,x-y],[x,y])
print("方程组的解为",s) | Python | zaydzuhri_stack_edu_python |
from django.http import HttpResponse
from django.shortcuts import render
function home request
begin
return call render request string home.html dict string hi string how are u ?
end function
function eggs request
begin
return call HttpResponse string <h1>How many eggs u want ?</h1>
end function
function about request
... | from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return render(request, 'home.html',{'hi':'how are u ?'})
def eggs(request):
return HttpResponse('<h1>How many eggs u want ?</h1>')
def about(request):
return render(request, 'about.html')
def count(request):
fulltext ... | Python | zaydzuhri_stack_edu_python |
function create_date self value
begin
comment Split on the comma for the name
set names = split re string \s*,\s* value
comment Return the resulting string.
return string <date> + value + string </date>
end function | def create_date(self, value):
# Split on the comma for the name
names = re.split(r'\s*,\s*', value)
# Return the resulting string.
return "<date>" + value + "</date>" | Python | nomic_cornstack_python_v1 |
function predict_hashtags self
begin
function get_hashtags_from_tweet _hts
begin
return list set list comprehension call normalize_lower ht at string text for ht in _hts
end function
set tokenizer = call CustomTweetTokenizer
set v = load joblib string model/20190415-DictVectorizer.joblib
set clf = load joblib string mo... | def predict_hashtags(self):
def get_hashtags_from_tweet(_hts):
return list(set([normalize_lower(ht["text"]) for ht in _hts]))
tokenizer = CustomTweetTokenizer()
v = joblib.load('model/20190415-DictVectorizer.joblib')
clf = joblib.load('model/20190415-LR.joblib')
cnt_... | Python | nomic_cornstack_python_v1 |
function set_game
begin
for row in range 0 LINES_OF_PAWNS 1
begin
if row % 2
begin
for column in range 0 SIZE 2
begin
set board at row at column = BLACK_PAWN
end
end
else
begin
for column in range 1 SIZE 2
begin
set board at row at column = BLACK_PAWN
end
end
end
for row in range SIZE - LINES_OF_PAWNS SIZE 1
begin
if r... | def set_game():
for row in range(0, con.LINES_OF_PAWNS, 1):
if row % 2:
for column in range(0, con.SIZE, 2):
game.Game.board[row][column] = con.BLACK_PAWN
else:
for column in range(1, con.SIZE, 2):
game.Game.board[row][column] = con.BLACK_PAWN... | Python | nomic_cornstack_python_v1 |
function sigmoid self value
begin
string YOUR CODE
set value = - value
set val_calc = 1 + exp value
return 1.0 / val_calc
end function | def sigmoid(self, value):
"""YOUR CODE"""
value = -(value)
val_calc = 1 + exp(value)
return 1.0 / val_calc | Python | nomic_cornstack_python_v1 |
from mcpi.minecraft import *
from mcpi.entity import *
from mcpi.block import *
from time import sleep
set mc = call create
set pos = call getTilePos
set x = x
set y = y
set z = z
call setBlocks x + 3 y - 1 z + 3 x - 3 y - 1 z + 9 DIAMOND_BLOCK
set pig = call spawnEntity PIG x y z
set sheep = call spawnEntity SHEEP x y... | from mcpi.minecraft import *
from mcpi.entity import *
from mcpi.block import *
from time import sleep
mc = Minecraft.create()
pos = mc.player.getTilePos()
x = pos.x
y = pos.y
z = pos.z
mc.setBlocks(x+3,y-1,z+3,x-3,y-1,z+9,DIAMOND_BLOCK)
pig = mc.spawnEntity(PIG,x,y,z)
sheep = mc.spawnEntity(SHEEP,x,y,z)
while(True... | Python | zaydzuhri_stack_edu_python |
function answer number
begin
while length string number > 1
begin
set newNumber = 0
for digit in list string number
begin
set newNumber = newNumber + integer digit
end
set number = newNumber
end
return number
end function | def answer(number):
while len(str(number)) > 1:
newNumber = 0
for digit in list(str(number)):
newNumber += int(digit)
number = newNumber
return number
| Python | zaydzuhri_stack_edu_python |
function app_label cls
begin
return app_label
end function | def app_label(cls):
return cls.model_meta.app_label | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Iterator based batch handling
import itertools
import query
import pattern
class MethodSwitch extends object
begin
set ROUTE = tuple
function __init__ self *args **kwargs
begin
set __init_args = args
set __init_kwargs = kwargs
end function
function perform self src
begin
raise NotI... | # -*- coding: utf-8 -*-
"""
Iterator based batch handling
"""
import itertools
import query
import pattern
class MethodSwitch(object):
ROUTE = ()
def __init__(self, *args, **kwargs):
self.__init_args = args
self.__init_kwargs = kwargs
def perform(self, src):
raise NotImplemented... | Python | zaydzuhri_stack_edu_python |
function _construct_input_spec self
begin
set _input_spec = list call InputSpec shape=list none none dtype=string int64 name=string token_ids call InputSpec shape=list none dtype=string int64 name=string length
end function | def _construct_input_spec(self):
self._input_spec = [
paddle.static.InputSpec(
shape=[None, None], dtype="int64", name='token_ids'),
paddle.static.InputSpec(
shape=[None], dtype="int64", name='length')
] | Python | nomic_cornstack_python_v1 |
from neural_network.tagger import TaggerNN
from neural_network.parser import ParserNN
from perceptron.tagger import Tagger
import logging
import json
import sys
import tensorflow as tf
from sklearn.model_selection import train_test_split
from lstm.data_utils import *
import itertools , pickle , argparse
from neural_net... | from neural_network.tagger import TaggerNN
from neural_network.parser import ParserNN
from perceptron.tagger import Tagger
import logging
import json
import sys
import tensorflow as tf
from sklearn.model_selection import train_test_split
from lstm.data_utils import *
import itertools, pickle, argparse
from neural_netwo... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment encoding: utf-8
string Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4.
comment 4次过,2^i是位异或,2**i是幂
class Solution extends object
begin
function rangeBitwise... | #!/usr/bin/env python
# encoding: utf-8
"""
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
"""
# 4次过,2^i是位异或,2**i是幂
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"... | Python | zaydzuhri_stack_edu_python |
function optional self
begin
return get pulumi self string optional
end function | def optional(self) -> Optional[bool]:
return pulumi.get(self, "optional") | Python | nomic_cornstack_python_v1 |
for i in range 0 length a - 1
begin
for j in range i + 1 length a
begin
set R = a at slice i : j + 1 :
if R == R at slice : : - 1
begin
if length R > m
begin
set m = length R
set h = R
end
end
end
end
print h | for i in range(0,len(a)-1):
for j in range(i+1,len(a)):
R = a[i:j+1]
if R == R[::-1]:
if len(R) > m:
m = len(R)
h = R
print(h)
| Python | zaydzuhri_stack_edu_python |
set x = string 11
set b = integer x
print b + 9 | x = '11'
b = int(x)
print(b+9) | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function countNodes self root
begin
if not root
begin
return 0
end
comment if not root.left:
comment return 1
set depth = 0
set cur = root
while cur
begin
set depth = depth + 1
set cur = left
end
set current_depth = 1
set count = 0
set cur = root
while cur
begin
set tmp_depth = current_depth
set tm... | class Solution:
def countNodes(self, root):
if not root:
return 0
# if not root.left:
# return 1
depth = 0
cur = root
while cur:
depth += 1
cur = cur.left
current_depth = 1
count = 0
cur = root
wh... | Python | zaydzuhri_stack_edu_python |
comment !usr/bin/env
comment this script creates a DNA sequence class with its seq name and organism, plus nucleotide composition method, reverse complement, GC cont
class dna_seq extends object
begin
function __init__ self sequence seq_name seq_organism
begin
set sequence = sequence
set seq_name = seq_name
set seq_org... | #!usr/bin/env
# this script creates a DNA sequence class with its seq name and organism, plus nucleotide composition method, reverse complement, GC cont
class dna_seq(object):
def __init__(self, sequence, seq_name, seq_organism):
self.sequence = sequence
self.seq_name = seq_name
self.seq_organism = seq_... | Python | zaydzuhri_stack_edu_python |
function fit_rmse t y p0=none
begin
set sort = call argsort t
if p0 is none
begin
set p0 = tuple 0.0 log 10 mean np y at sort at slice : 10 : mean np y at sort at slice - 10 : : - mean np y at sort at slice : 10 :
end
set tuple p *_ flag = call fmin lambda p -> call rmse call linear_ramp t at sort p at 0 exp p at 1 ... | def fit_rmse(t, y, p0=None):
sort = np.argsort(t)
if p0 is None:
p0 = (0.0, np.log(10), np.mean(y[sort][:10]),
np.mean(y[sort][-10:]) - np.mean(y[sort][:10]))
p, *_, flag = fmin(lambda p: rmse(linear_ramp(t[sort], p[0], np.exp(p[1]),
p[... | Python | nomic_cornstack_python_v1 |
function view self dtype=none
begin
comment NB:
comment - This must return a *new* object referencing the same data, not self.
comment - The only case that *must* be implemented is with dtype=None,
comment giving a view with the same dtype as self.
if dtype is not none
begin
raise call NotImplementedError dtype
end
ret... | def view(self, dtype=None):
# NB:
# - This must return a *new* object referencing the same data, not self.
# - The only case that *must* be implemented is with dtype=None,
# giving a view with the same dtype as self.
if dtype is not None:
raise NotImplementedError(d... | Python | nomic_cornstack_python_v1 |
function is_palindrome n
begin
return string n == string n at slice : : - 1
end function
function largest_palindromic_number arr
begin
set max_length = - 1
set max_index = - 1
for i in range length arr
begin
if call is_palindrome arr at i
begin
set length = length string arr at i
if length > max_length
begin
set max_... | def is_palindrome(n):
return str(n) == str(n)[::-1]
def largest_palindromic_number(arr):
max_length = -1
max_index = -1
for i in range(len(arr)):
if is_palindrome(arr[i]):
length = len(str(arr[i]))
if length > max_length:
max_length = length
... | Python | jtatman_500k |
function _validate self
begin
string Validate model data and save errors
set errors = dict
for tuple name validator in items _validators
begin
set value = get attribute self name
try
begin
call validator self value
end
except ValidationError as e
begin
set errors at name = string e
end
end
set _validate_errors = error... | def _validate(self):
"""Validate model data and save errors
"""
errors = {}
for name, validator in self._validators.items():
value = getattr(self, name)
try:
validator(self, value)
except ValidationError as e:
errors[n... | Python | jtatman_500k |
function calculate_sum arr limit
begin
comment Initialize the sum to 0
set sum = 0
comment Initialize a flag to check if there are elements divisible by 3
set divisible_by_3 = false
comment Iterate through the array
for i in range length arr
begin
comment Check if the element is divisible by 3
if arr at i % 3 == 0
begi... | def calculate_sum(arr, limit):
# Initialize the sum to 0
sum = 0
# Initialize a flag to check if there are elements divisible by 3
divisible_by_3 = False
# Iterate through the array
for i in range(len(arr)):
# Check if the element is divisible by 3
if arr[i] % 3 == 0:
... | Python | jtatman_500k |
string Script to setup the repository environment
import subprocess
from pathlib import Path
set DATASET_REPO_URL = string https://github.com/PRFina/Rinocitologia-Datasets.git
set DATASET_DIR_NAME = string Datasets
set CONFIG_FILE_NAME = string config.ini
set cwd = call Path string .
print string 1) Downloading dataset... | """
Script to setup the repository environment
"""
import subprocess
from pathlib import Path
DATASET_REPO_URL = 'https://github.com/PRFina/Rinocitologia-Datasets.git'
DATASET_DIR_NAME = 'Datasets'
CONFIG_FILE_NAME = 'config.ini'
cwd = Path(".")
print("1) Downloading datasets")
subprocess.call(['git','clone', DATA... | Python | zaydzuhri_stack_edu_python |
function get_width self
begin
return string %s % width
end function | def get_width(self):
return "%s" % self.width | Python | nomic_cornstack_python_v1 |
function useShaders self value
begin
if value == true and _haveShaders == false
begin
error string Shaders were requested but aren't available. Shaders need OpenGL 2.0+ drivers
end
comment if there's a change...
if value != useShaders
begin
set __dict__ at string useShaders = value
if has attribute self string tex
begi... | def useShaders(self, value):
if value == True and self.win._haveShaders == False:
logging.error("Shaders were requested but aren't available. Shaders need OpenGL 2.0+ drivers")
if value != self.useShaders: # if there's a change...
self.__dict__['useShaders'] = value
... | Python | nomic_cornstack_python_v1 |
function go_right self
begin
set change_x = 6
end function | def go_right(self):
self.change_x = 6 | Python | nomic_cornstack_python_v1 |
function panggil func
begin
return func
end function
function helloworld
begin
return string HELLO WORLD
end function
function main
begin
set daftarnama = list string Adi, Cahyo, budi, Dedi
print string Keadaan awal
print daftarnama
print string menggunakan sorted ():
print sorted daftarnama
sort daftarnama key=lambda ... | def panggil (func):
return func
def helloworld ():
return "HELLO WORLD"
def main ():
daftarnama = ["Adi, Cahyo, budi, Dedi"]
print ("Keadaan awal")
print (daftarnama)
print ("\nmenggunakan sorted (): ")
print (sorted (daftarnama))
daftarnama.sort(key = lambda n: n.lower())
... | Python | zaydzuhri_stack_edu_python |
import win10toast
import mysql.connector
import os , requests
from PIL import Image
from pathlib import Path
comment Get current working directory path
set filePath = get current directory
comment Try checking whether file exists in the directory
comment and create one if not. At last change current directory.
try
begi... | import win10toast
import mysql.connector
import os, requests
from PIL import Image
from pathlib import Path
# Get current working directory path
filePath = os.getcwd()
# Try checking whether file exists in the directory
# and create one if not. At last change current directory.
try:
os.makedirs(filePath + "\Img")... | Python | zaydzuhri_stack_edu_python |
import sys
import inspect
import unicodedata
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager , PDFPageInterpreter
comment , TagExtractor
from pdfminer.pdfdevice import PDFDevice
from pdfminer.pdfpage import PDFPage
from pdfminer.con... | import sys
import inspect
import unicodedata
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice #, TagExtractor
from pdfminer.pdfpage import PDFPage
from pdfminer.converter i... | Python | zaydzuhri_stack_edu_python |
comment leetcode 1.5
comment Replace all spaces in a string with '%20'
import unittest
function replaceAllSpaces string
begin
set i = 0
while i < length string
begin
if string at i != string
begin
set i = i + 1
end
else
begin
set string = replace string string string %20
set i = i + 3
end
end
return string
end functi... | ####
#
# leetcode 1.5
#
# Replace all spaces in a string with '%20'
#
####
import unittest
def replaceAllSpaces(string):
i = 0
while i < len(string):
if string[i] != " ":
i+=1
else:
string = string.replace(" ", "%20")
i+=3
return string
class TestRepla... | Python | zaydzuhri_stack_edu_python |
string File: taxformwithgui.py Project 8.1 A GUI-based tax calculator. Computes and prints the total tax, given the income and number of dependents (inputs), and a standard deduction of $10,000, an exemption amount of $3,000. Add radio button options for filing status to the tax calculator program of Project 1. The use... | """
File: taxformwithgui.py
Project 8.1
A GUI-based tax calculator.
Computes and prints the total tax, given the income and number of dependents
(inputs), and a standard deduction of $10,000, an exemption amount of $3,000.
Add radio button options for filing status to the tax calculator program of
Project 1. The user... | Python | zaydzuhri_stack_edu_python |
function get_simple_coloration cls status
begin
if status in list STATUS at string official at string up STATUS at string official at string valid
begin
comment The status is in the list of UP status.
comment We return the green coloration.
return GREEN + BRIGHT
end
if status == STATUS at string official at string down... | def get_simple_coloration(cls, status):
if status in [
PyFunceble.STATUS["official"]["up"],
PyFunceble.STATUS["official"]["valid"],
]:
# The status is in the list of UP status.
# We return the green coloration.
return PyFunceble.Fore.GREEN + ... | Python | nomic_cornstack_python_v1 |
function snap_run args
begin
comment TODO: link snap num to host name
debug string ETCD config file: + etcd_config_file
set etcd_params = call read_yaml etcd_config_file
debug string CORR config file: + corr_config_file
debug string HOST SNAP: + host_snap
debug string SNAP NUMBER: + string snap_num
set delay_params = c... | def snap_run(args):
## TODO: link snap num to host name
logger.debug("ETCD config file: "+args.etcd_config_file)
etcd_params = read_yaml(args.etcd_config_file)
logger.debug("CORR config file: "+args.corr_config_file)
logger.debug("HOST SNAP: "+args.host_snap)
logger.debug("SNAP NUMBER: "+str(a... | Python | nomic_cornstack_python_v1 |
function NewFeeds num_feeds
begin
set feeds = list
for i in call xrange num_feeds
begin
set feed = call Feed url=string http://feed%d % i
put
append feeds feed
end
return feeds
end function | def NewFeeds(num_feeds):
feeds = []
for i in xrange(num_feeds):
feed = cap_schema.Feed(url='http://feed%d' % i)
feed.put()
feeds.append(feed)
return feeds | Python | nomic_cornstack_python_v1 |
function recreate_db
begin
call drop_all
call create_all
commit session
end function | def recreate_db():
db.drop_all()
db.create_all()
db.session.commit() | Python | nomic_cornstack_python_v1 |
print string NAME:Zakari Zakari Abba
print string DEPARTMENT: Computer Science
set scare = string Boo!
print scare
set var1 = 56
set var2 = 67
set third_score = var1 + var2
print var1 var2 third_score
set var5 = 12
set var4 = 0.5
set var6 = var5 / var4
print var6
set one = 34
set two = 56
set three = one + two
print th... | print("NAME:Zakari Zakari Abba")
print("DEPARTMENT: Computer Science")
scare = "Boo!"
print (scare)
var1 = 56
var2 = 67
third_score= var1 + var2
print(var1, var2, third_score)
var5 = 12
var4 = .5
var6 = var5 / var4
print (var6)
one = 34
two = 56
three = one + two
print (three)
dash = 8
crash = dash % 3
print (crash)
E1... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Oct 28 16:16:55 2019 @author: daniel.lopez
comment Import all the dependencies
import gensim
from nltk import RegexpTokenizer
from nltk.corpus import stopwords
from os import listdir
from os.path import isfile , join
import pandas as pd
comment now create a list that ... | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 28 16:16:55 2019
@author: daniel.lopez
"""
#Import all the dependencies
import gensim
from nltk import RegexpTokenizer
from nltk.corpus import stopwords
from os import listdir
from os.path import isfile, join
import pandas as pd
#now create a list that contains the name... | Python | zaydzuhri_stack_edu_python |
from pprint import pprint
import re
from typing import NamedTuple
import os
from collections import defaultdict
set raw_data = string abc a b c ab ac a a a a b
function part1 raw_data
begin
string For each group, count the number of questions to which anyone answered "yes". What is the sum of those counts?
set groups =... | from pprint import pprint
import re
from typing import NamedTuple
import os
from collections import defaultdict
raw_data = """abc
a
b
c
ab
ac
a
a
a
a
b"""
def part1(raw_data):
"""For each group, count the number of questions
to which anyone answered "yes".
What is the sum of those counts?"""
gro... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Oct 28 12:07:52 2019 @author: fabian kresse @brief: realizes the adaptive quadrature for an integral f(x)dx from a to b, @details: is based on the simpson rule
import numpy as np
import matplotlib.pyplot as p
function func x
begin
if x < 1 / 3
begin
return 1 / 2 * e ^... | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 28 12:07:52 2019
@author: fabian kresse
@brief: realizes the adaptive quadrature for an integral f(x)dx from a to b,
@details: is based on the simpson rule
"""
import numpy as np
import matplotlib.pyplot as p
def func(x):
if x < 1/3:
return (1/2) * np.e**x
... | Python | zaydzuhri_stack_edu_python |
function refextract reference mappedlocations unmappedlocations conflictlocations prefix flanking
begin
comment Parse reference FASTA file
set read = read SeqIO reference format=string fasta
comment Extract mapped regions and store in a dictionary
set mappeddict = dictionary
set idmap = list
for i in range 0 shape at 0... | def refextract(reference, mappedlocations, unmappedlocations, conflictlocations, prefix, flanking):
# Parse reference FASTA file
read = SeqIO.read(reference, format = 'fasta')
# Extract mapped regions and store in a dictionary
mappeddict = dict()
idmap = list()
for i in range(0, ma... | Python | nomic_cornstack_python_v1 |
import argparse
from pathlib import Path
from wordhunt import wordhunt , open_pdf
set arg_parser = call ArgumentParser description=string Fuzzy word hunt in pdf files.
call add_argument string pattern type=str help=string file or folder path
call add_argument string fpath type=lambda x -> call Path x help=string file o... | import argparse
from pathlib import Path
from wordhunt import wordhunt, open_pdf
arg_parser = argparse.ArgumentParser(description='Fuzzy word hunt in pdf files.')
arg_parser.add_argument("pattern", type=str, help="file or folder path")
arg_parser.add_argument("fpath", type=lambda x: Path(x), help="file or folder path... | Python | zaydzuhri_stack_edu_python |
comment 1. on CheckiO your solution should be a function
comment 2. the function should return the right answer, not print it.
function say_hi name age
begin
string Hi!
comment your code here
return string Hi. My name is + name + string and I'm + age + string years old
end function
if __name__ == string __main__
begin
... | # 1. on CheckiO your solution should be a function
# 2. the function should return the right answer, not print it.
def say_hi(name: str, age: int) -> str:
"""
Hi!
"""
# your code here
return "Hi. My name is " + name + "and I'm " + age + " years old"
if __name__ == '__main__':
#These "asse... | Python | zaydzuhri_stack_edu_python |
function lookup collated_file query_file
begin
set x = open query_file string r
set query = list
for i in x
begin
set i = replace i string string
append query i
end
set y = open collated_file string r
set collection = list
for i in y
begin
set i = replace i string string
set i = split i string :
append collection i... | def lookup(collated_file,query_file):
x=open(query_file,"r")
query=[]
for i in x:
i=i.replace("\n","")
query.append(i)
y=open(collated_file,"r")
collection=[]
for i in y :
i=i.replace("\n","")
i=i.split(":")
collection.append(i)
answer=[]
... | Python | nomic_cornstack_python_v1 |
for i in range 1 times
begin
if numslist at i > numslist at i - 1
begin
set len = len + 1
end
else
begin
if len > maxlen
begin
set maxlen = len
end
set len = 1
end
end
if len > maxlen
begin
set maxlen = len
end
print maxlen | for i in range(1,times):
if(numslist[i]>numslist[i-1]):
len=len+1
else:
if(len>maxlen):
maxlen=len
len=1
if(len>maxlen):
maxlen=len
print(maxlen) | Python | zaydzuhri_stack_edu_python |
function calculate_singles_percentage total_hits home_runs triples doubles
begin
comment Step 3: Calculate the number of non-single hits
set non_single_hits = home_runs + triples + doubles
comment Step 4: Calculate the number of singles
set singles = total_hits - non_single_hits
comment Step 5: Calculate the percentage... | def calculate_singles_percentage(total_hits, home_runs, triples, doubles):
# Step 3: Calculate the number of non-single hits
non_single_hits = home_runs + triples + doubles
# Step 4: Calculate the number of singles
singles = total_hits - non_single_hits
# Step 5: Calculate the percentage o... | Python | dbands_pythonMath |
function _attr_setdefault self attrs
begin
if string id not in attrs and id is not none
begin
set attrs at string id = id
end
end function | def _attr_setdefault(self, attrs):
if 'id' not in attrs and self.id is not None:
attrs['id'] = self.id | Python | nomic_cornstack_python_v1 |
function train self testing=false
begin
call check_sanity
call await_signal_from_parent
comment Synchronize weights
call set_weights weights
set num_batches = 0
set epoch = 0
set batches_per_epoch = shape at 0 // batch_size
info string Worker { rank } start training
if monitor
begin
call start_monitor
end
for tuple x_b... | def train(self, testing=False):
self.check_sanity()
self.await_signal_from_parent()
# Synchronize weights
self.model.set_weights(self.weights)
num_batches = 0
epoch = 0
batches_per_epoch = self.data.get_train_data().shape[0] // self.data.batch_size
self.... | Python | nomic_cornstack_python_v1 |
comment excepciones
import math
function raiz x
begin
if x < 0
begin
raise call ValueError string El número no puede ser negativo
end
else
begin
return square root x
end
end function
try
begin
print call raiz - 3
end
except any
begin
print string Error
end
print string Finalizamos con normalidad | # excepciones
import math
def raiz(x):
if x<0:
raise ValueError('El número no puede ser negativo')
else:
return math.sqrt(x)
try:
print(raiz(-3))
except:
print('Error')
print('Finalizamos con normalidad') | Python | zaydzuhri_stack_edu_python |
function make_tables con
begin
with con
begin
execute con string CREATE TABLE authorpapers ( id TEXT NOT NULL PRIMARY KEY, value TEXT );
end
comment write one testValue to papers
set sql = string INSERT INTO authorpapers (id, value) values (?, ?)
set data = list tuple string test A Paper string testy_McTest
with con
be... | def make_tables(con):
with con:
con.execute("""
CREATE TABLE authorpapers (
id TEXT NOT NULL PRIMARY KEY,
value TEXT
);
""")
#write one testValue to ... | Python | nomic_cornstack_python_v1 |
function ph_from self ph_from
begin
set _ph_from = ph_from
end function | def ph_from(self, ph_from):
self._ph_from = ph_from | Python | nomic_cornstack_python_v1 |
for x in range qtd
begin
append numeros integer input
end
print sum numeros | for x in range(qtd):
numeros.append(int(input()))
print(sum(numeros)) | Python | zaydzuhri_stack_edu_python |
function remove_loop self from_pos to_pos
begin
if from_pos == to_pos
begin
return 0
end
set min_pos = min from_pos to_pos
set max_pos = max from_pos to_pos
del walk at slice min_pos : max_pos :
return max_pos - min_pos
end function | def remove_loop(self, from_pos, to_pos):
if from_pos == to_pos:
return 0
min_pos = min(from_pos, to_pos)
max_pos = max(from_pos, to_pos)
del self.walk[min_pos:max_pos]
return max_pos - min_pos | Python | nomic_cornstack_python_v1 |
function test_bill self res
begin
pass
end function | def test_bill(self, res):
pass | Python | nomic_cornstack_python_v1 |
function alphabeta self game depth alpha=decimal string -inf beta=decimal string inf
begin
if call time_left < TIMER_THRESHOLD
begin
raise call SearchTimeout
end
set possible_moves = call get_legal_moves
if not possible_moves
begin
return tuple - 1 - 1
end
else
begin
set tuple _ best_move = call my_alphabeta game depth... | def alphabeta(self, game, depth, alpha=float("-inf"), beta=float("inf")):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
possible_moves = game.get_legal_moves()
if not possible_moves:
return (-1,-1)
else:
_, best_move = self.my_al... | Python | nomic_cornstack_python_v1 |
function qLearning env num_episodes discount_factor=0.9 alpha=0.1 epsilon=0.1
begin
function createPolicy Q epsilon num_actions
begin
string Creates an epsilon-greedy policy based on a given Q-function and epsilon. Returns a function that takes the state as an input and returns the probabilities for each action in the ... | def qLearning(env, num_episodes, discount_factor = 0.9,
alpha = 0.1, epsilon = 0.1):
def createPolicy(Q, epsilon, num_actions):
"""
Creates an epsilon-greedy policy based
on a given Q-function and epsilon.
... | Python | zaydzuhri_stack_edu_python |
from itertools import repeat
from random import choice
class PopulationGenerator
begin
set __slots__ = list string mutation_values string strand_size
function __init__ self mutation_values strand_size
begin
set mutation_values = mutation_values
set strand_size = strand_size
end function
function generate self n
begin
r... | from itertools import repeat
from random import choice
class PopulationGenerator:
__slots__ = ['mutation_values', 'strand_size']
def __init__(self, mutation_values, strand_size):
self.mutation_values = mutation_values
self.strand_size = strand_size
def generate(self, n):
return [[... | Python | zaydzuhri_stack_edu_python |
import urlparse
from bs4 import BeautifulSoup
import csv
import codecs
function html_parse html
begin
set html_soup = call BeautifulSoup html string lxml
set content = select html_soup string div#content at 0
comment info = content.select('div#info')[0]
set comment = select content string div#interest_sectl at 0
set ti... | import urlparse
from bs4 import BeautifulSoup
import csv
import codecs
def html_parse(html):
html_soup = BeautifulSoup(html, 'lxml')
content = html_soup.select('div#content')[0]
# info = content.select('div#info')[0]
comment = content.select('div#interest_sectl')[0]
title = content.h1.select('sp... | Python | zaydzuhri_stack_edu_python |
string *Q1*
print string My name is durgesh
string Q2
print string Acad + string View
string Q3
set x = input string x =
set y = input string y =
set z = input string z =
print string x = + x
print string y = + y
print string z = + z
string Q4
print string Let's get started
string Q5
set s = string Acadview
set course ... | '''*Q1*'''
print("My name is durgesh")
'''Q2'''
print("Acad" + "View")
'''Q3'''
x = input('x = ')
y = input('y = ')
z = input('z = ')
print('x = ' + x)
print('y = ' + y)
print('z = ' + z)
'''Q4'''
print("Let's get started")
'''Q5'''
s = 'Acadview'
course = 'Python'
fees = 5000
print("In {}, {} ... | Python | zaydzuhri_stack_edu_python |
function receive_post self message
begin
if online == true and message not in posts_seen
begin
set messages_received = messages_received + 1
add inbox message
call request_post_attention self
end
end function | def receive_post(self, message):
if self.online == True and message not in self.posts_seen:
self.model.messages_received += 1
self.inbox.add(message)
self.model.request_post_attention(self) | Python | nomic_cornstack_python_v1 |
import pygame
class Button
begin
function __init__ self rect_settings screen
begin
set rect_settings = rect_settings
set screen = screen
set screen_rect = call get_rect
set font = call SysFont none button_fontsize
set rect = call Rect 0 0 button_width button_height
set center = center
call prep_msg button_msg
end funct... | import pygame
class Button():
def __init__(self, rect_settings, screen):
self.rect_settings = rect_settings
self.screen = screen
self.screen_rect=self.screen.get_rect()
self.font = pygame.font.SysFont(
None, self.rect_settings.button_fontsize)
self.rect = pyga... | Python | zaydzuhri_stack_edu_python |
function remove self key
begin
set hashv = call hash key
set bucket = hashmap at hashv
for tuple i tuple k v in enumerate bucket
begin
if k == key
begin
del bucket at i
end
end
end function | def remove(self, key):
hashv = self.hash(key)
bucket=self.hashmap[hashv]
for i,(k,v) in enumerate(bucket):
if k==key:
del bucket[i] | Python | nomic_cornstack_python_v1 |
function getSkyline buildings
begin
if not buildings
begin
return list
end
if length buildings == 1
begin
return list list buildings at 0 at 0 buildings at 0 at 2 list buildings at 0 at 1 0
end
set mid = length buildings // 2
set left = call getSkyline buildings at slice : mid :
set right = call getSkyline buildings ... | def getSkyline(buildings):
if not buildings: return []
if len(buildings) == 1:
return [[buildings[0][0], buildings[0][2]], [buildings[0][1], 0]]
mid = len(buildings) // 2
left = getSkyline(buildings[:mid])
right = getSkyline(buildings[mid:])
return merge(left, right)
def merge(left, rig... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env pybricks-micropython
comment Aaryan and Felix code here.
from TurnGradualGyro import *
from GradualGyroF import *
from GradualGyroB import *
from ColorSensorFunctions import *
from GyroB import *
from GyroF import *
call readAllValues
comment Code Here.
function Run2
begin
call gradualGyroForward ... | #!/usr/bin/env pybricks-micropython
# Aaryan and Felix code here.
from TurnGradualGyro import *
from GradualGyroF import *
from GradualGyroB import *
from ColorSensorFunctions import *
from GyroB import *
from GyroF import *
readAllValues()
# Code Here.
def Run2():
gradualGyroForward(570, 300)
sideLineFollowe... | Python | zaydzuhri_stack_edu_python |
import collections
function ans n arr
begin
set graph = list comprehension list 0 * n for _ in call xrange n
for i in call xrange length arr
begin
set tarr = arr at i
set u = i
for j in call xrange 1 length tarr 2
begin
set v = tarr at j - 1
set w = tarr at j + 1
set graph at u at v = w
end
end
comment print graph
set ... | import collections
def ans(n, arr):
graph = [ [0] * n for _ in xrange(n) ]
for i in xrange(len(arr)):
tarr = arr[i]
u = i
for j in xrange(1, len(tarr), 2):
v = tarr[j] - 1
w = tarr[j + 1]
graph[u][v] = w
#print graph
dp = [ [float("inf")] * n... | Python | zaydzuhri_stack_edu_python |
function _get_declarative_base_class cls
begin
return get attribute MagicMethodMixin string _declarative_base_class none
end function | def _get_declarative_base_class(cls):
return getattr(MagicMethodMixin, '_declarative_base_class', None) | Python | nomic_cornstack_python_v1 |
function admin self mask target args
begin
set rcvd = join string args at string <words>
call set_target target
if not target
begin
set target = nick
end
if target == nick
begin
set target = nick
end
if is_debug
begin
set msg = string Command received : + rcvd + string , from: + target
call privmsg target msg
end
if r... | def admin(self, mask, target, args):
rcvd = ' '.join(args['<words>'])
self.func.set_target(target)
if not target:
target = mask.nick
if target == self.bot.nick:
target = mask.nick
if self.is_debug:
msg = " Command received : " + rcvd + ", fro... | Python | nomic_cornstack_python_v1 |
import os
import time
import logging
import numpy as np
from logging.handlers import TimedRotatingFileHandler
function setUpLogger log_name
begin
set log_fold = string /home/efc/SJTUdrive/move_log/
set is_exist = exists path log_fold
if not is_exist
begin
make directories log_fold
end
set logger = call getLogger log_na... | import os
import time
import logging
import numpy as np
from logging.handlers import TimedRotatingFileHandler
def setUpLogger(log_name):
log_fold = '/home/efc/SJTUdrive/move_log/'
is_exist = os.path.exists(log_fold)
if not is_exist:
os.makedirs(log_fold)
logger = logging.getLogger(log_name)
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import numpy as np
import pandas as pd
comment 2
set M = 100
comment 10
set N = 1000000
set df = call DataFrame dict string feature1 random integer M size=tuple N ; string feature2 random integer M size=tuple N ; string time call rand N
to csv df string incidents-10~6.csv index_label=string... | #!/usr/bin/env python
import numpy as np
import pandas as pd
M = 100 #2
N = 1000000 #10
df = pd.DataFrame({'feature1':np.random.randint(M, size=(N,)),
'feature2':np.random.randint(M, size=(N,)),
'time':np.random.rand(N)
})
df.to_csv('incidents-10~6.csv', index_... | Python | zaydzuhri_stack_edu_python |
function add_component_type self component_type
begin
call add_component_type component_type
end function | def add_component_type(self, component_type):
self.context.add_component_type(component_type) | Python | nomic_cornstack_python_v1 |
function WriteJsonSummary img_root nopatch_json nopatch_images_base_url withpatch_json withpatch_images_base_url output_file_path gs_output_dir gs_skp_dir slave_num additions_to_sys_path
begin
if additions_to_sys_path
begin
for dirpath in additions_to_sys_path
begin
if dirpath not in path
begin
insert path 0 dirpath
en... | def WriteJsonSummary(img_root, nopatch_json, nopatch_images_base_url,
withpatch_json, withpatch_images_base_url,
output_file_path, gs_output_dir, gs_skp_dir, slave_num,
additions_to_sys_path):
if additions_to_sys_path:
for dirpath in additions_to_sys_... | Python | nomic_cornstack_python_v1 |
import gtk
class PyApp extends Window
begin
function __init__ self
begin
call __init__
call set_size_request 300 150
comment self.set_position(Gtk.WIN_POS_CENTER)
call connect string destroy main_quit
call set_title string About battery
set button = call Button string About
call set_size_request 80 30
call connect stri... | import gtk
class PyApp(gtk.Window):
def __init__(self):
super(PyApp, self).__init__()
self.set_size_request(300, 150)
#self.set_position(Gtk.WIN_POS_CENTER)
self.connect("destroy", gtk.main_quit)
self.set_title("About battery")
button = gtk.Button("About")
b... | Python | zaydzuhri_stack_edu_python |
function get_user request user_id
begin
try
begin
set get_user = get objects id=user_id
end
except any
begin
return call JsonResponse string Not Found - User does not exist. status=404 safe=false
end
comment Check for share code.
set valid_sc = false
if share_code
begin
if get GET string sharecode == share_code
begin
s... | def get_user(request, user_id):
try:
get_user = User.objects.get(id=user_id)
except:
return JsonResponse(
"Not Found - User does not exist.", status=404, safe=False
)
# Check for share code.
valid_sc = False
if get_user.share_code:
if request.GET.get("sh... | Python | nomic_cornstack_python_v1 |
function test_upper_hybrid_frequency
begin
set omega_uh = call upper_hybrid_frequency B n_e=n_e
set omega_ce = call electron_gyrofrequency B
set omega_pe = call electron_plasma_frequency n_e=n_e
assert unit == rad / s
assert unit == rad / s
assert unit == rad / s
set LHS = omega_uh ^ 2
set RHS = omega_ce ^ 2 + omega_pe... | def test_upper_hybrid_frequency():
omega_uh = upper_hybrid_frequency(B, n_e=n_e)
omega_ce = electron_gyrofrequency(B)
omega_pe = electron_plasma_frequency(n_e=n_e)
assert omega_ce.unit == u.rad/u.s
assert omega_pe.unit == u.rad/u.s
assert omega_uh.unit == u.rad/u.s
LHS = omega_uh**2
RHS... | Python | nomic_cornstack_python_v1 |
import json
import csv
import requests
import requests
import time
import pandas
import argparse
set details = dict
comment this function gets the IDs for the Researcher Observations and the Image Observations from the database
comment it will only work on an SI computer that has access to solr
comment returns a dict ... | import json
import csv
import requests
import requests
import time
import pandas
import argparse
details = {}
#this function gets the IDs for the Researcher Observations and the Image Observations from the database
#it will only work on an SI computer that has access to solr
def getPID(dep_names):#returns a dict of... | Python | zaydzuhri_stack_edu_python |
import asyncio
async function do_something
begin
print string starting something
await sleep 2
print string done with something
end function
run call do_something | import asyncio
async def do_something():
print('starting something')
await asyncio.sleep(2)
print('done with something')
asyncio.run(do_something()) | Python | iamtarun_python_18k_alpaca |
import time
from chronologger import Timer , TimeUnit
decorator call Timer name=string Foo method! unit=ms simple_log=true log_when_exiting=true
function foo
begin
sleep 0.1
end function
function main
begin
with start call Timer name=string Test Loop! unit=s simple_log=true log_when_exiting=true as timer
begin
for i in... | import time
from chronologger import Timer, TimeUnit
@Timer(name="Foo method!", unit=TimeUnit.ms, simple_log=True, log_when_exiting=True)
def foo():
time.sleep(0.1)
def main():
with Timer(name="Test Loop!", unit=TimeUnit.s,
simple_log=True, log_when_exiting=True).start() as timer:
fo... | Python | zaydzuhri_stack_edu_python |
function post_kronos_data_update scheduler **kwargs
begin
return call post_schedule_job scheduler __name__ keyword kwargs
end function | def post_kronos_data_update(scheduler, **kwargs):
return post_schedule_job(scheduler, handlers.KronosDataUpdater.__name__, **kwargs) | Python | nomic_cornstack_python_v1 |
function block_request_based_on_entity_governance_rule self request_mapping_for_regex_config ready_for_body_request governance_rules entity_rules rule_entity_type entity_id DEBUG
begin
set response_buffer = call BlockResponseBufferList
set entity_id_rules_mapping = none
try
begin
set entity_id_rules_mapping = entity_ru... | def block_request_based_on_entity_governance_rule(self,
request_mapping_for_regex_config,
ready_for_body_request,
governance_rules,
... | Python | nomic_cornstack_python_v1 |
function test_PauliRot_decomposition_XIYZ self
begin
set theta = 0.4
set op = call PauliRot theta string XIYZ wires=list 0 1 2 3
set decomp_ops = call decomposition theta string XIYZ wires=list 0 1 2 3
assert length decomp_ops == 5
assert name == string Hadamard
assert wires == call Wires list 0
assert name == string R... | def test_PauliRot_decomposition_XIYZ(self):
theta = 0.4
op = qml.PauliRot(theta, "XIYZ", wires=[0, 1, 2, 3])
decomp_ops = op.decomposition(theta, "XIYZ", wires=[0, 1, 2, 3])
assert len(decomp_ops) == 5
assert decomp_ops[0].name == "Hadamard"
assert decomp_ops[0].wires ... | Python | nomic_cornstack_python_v1 |
from django.db import models
comment Create your models here.
class Business extends Model
begin
set caption = call CharField max_length=32
comment 后面新增的,可以直接先附上默认值,或者给可以为空
set code = call CharField max_length=32 null=true default=string SA
end class
class Host extends Model
begin
set nid = call AutoField primary_key=t... | from django.db import models
# Create your models here.
class Business(models.Model):
caption=models.CharField(max_length=32)
code=models.CharField(max_length=32,null=True,default="SA") #后面新增的,可以直接先附上默认值,或者给可以为空
class Host(models.Model):
nid=models.AutoField(primary_key=True)
hostname=models.CharF... | Python | zaydzuhri_stack_edu_python |
import pytest
decorator fixture
function car
begin
from car import Car
set car_obj = call Car color=string Blue max_speed=40 acceleration=10 tyre_friction=3
return car_obj
end function
comment Task-1 Creating car
function test_creating_multiple_car_instances_with_valid_details
begin
comment Arrange
from car import Car
... | import pytest
@pytest.fixture
def car():
from car import Car
car_obj = Car(
color='Blue',
max_speed=40,
acceleration=10,
tyre_friction=3
)
return car_obj
# Task-1 Creating car
def test_creating_multiple_car_instances_w... | Python | zaydzuhri_stack_edu_python |
import pytest
from client import Client
class TestClient
begin
function setup self
begin
set user = call Client
set _send_message = sub_send_message
set account_name = string Vasia
set room = string room
set to_user = string Igor
end function
function sub_send_message self data
begin
set message = string Hello Vasia!
r... | import pytest
from client import Client
class TestClient:
def setup(self):
self.user = Client()
self.user._send_message = self.sub_send_message
self.user.account_name = 'Vasia'
self.user.room = 'room'
self.user.to_user = 'Igor'
def sub_send_message(self, data):
... | Python | zaydzuhri_stack_edu_python |
function remove_timeout self timeout
begin
Ellipsis
end function | def remove_timeout(self, timeout):
... | Python | nomic_cornstack_python_v1 |
import RPi.GPIO as GPIO
import threading
import time
import state as ST
comment GPIO.setmode(GPIO.BOARD)
comment main_switch_1 = 37
comment main_switch_2 = 40
comment motors = {"1":16, "2":18, "3":22, "4":32, "5":36, "6":38,
comment "7":35, "8":33, "9":31, "10":29, "11":15, "12":13}
set main_switch_1 = 26
set main_swit... | import RPi.GPIO as GPIO
import threading
import time
import state as ST
#GPIO.setmode(GPIO.BOARD)
#main_switch_1 = 37
#main_switch_2 = 40
#motors = {"1":16, "2":18, "3":22, "4":32, "5":36, "6":38,
# "7":35, "8":33, "9":31, "10":29, "11":15, "12":13}
main_switch_1 = 26
main_switch_2 = 21
ir_sensor = 17
motors=... | Python | zaydzuhri_stack_edu_python |
function __parse_prstatus self prstatus
begin
comment TODO: support all architectures angr supports
comment extract siginfo from prstatus
set tuple si_signo si_code si_errno = call unpack string <3I desc at slice : 12 :
comment this field is a short, but it's padded to an int
set pr_cursig = call unpack string <I desc... | def __parse_prstatus(self, prstatus):
# TODO: support all architectures angr supports
# extract siginfo from prstatus
self.si_signo, self.si_code, self.si_errno = struct.unpack("<3I", prstatus.desc[:12])
# this field is a short, but it's padded to an int
self.pr_cursig = struc... | Python | nomic_cornstack_python_v1 |
import unittest
import numpy as np
from utils import *
class MeanAveragePrecisionTests extends TestCase
begin
function test_mean_average_precision_equal_to_one self
begin
set outputs = array tuple list 0.12 0.11 0.45 list 0.1 0.9 0.87 list 0.45 0.65 0.8
set labels = array tuple list 0 0 1 list 0 1 1 list 1 1 1
assert e... | import unittest
import numpy as np
from utils import *
class MeanAveragePrecisionTests(unittest.TestCase):
def test_mean_average_precision_equal_to_one(self):
outputs = np.array(([0.12, 0.11, 0.45], [0.1, 0.9, 0.87],
[0.45, 0.65, 0.8]))
labels = np.array(([0, 0, 1], [0,... | Python | zaydzuhri_stack_edu_python |
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import math
import random
import rtmidi_python as rtmidi
import time
set ckey = string
set csecret = string
set atoken = string
set asecret = string
set midi_out = call MidiOut
call open_port 1
set note_map = dict ... | from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import math
import random
import rtmidi_python as rtmidi
import time
ckey = ''
csecret = ''
atoken = ''
asecret = ''
midi_out = rtmidi.MidiOut()
midi_out.open_port(1)
note_map = {
'A': 4,
'B': 5,
'C': 7,
'D': 9,
... | Python | zaydzuhri_stack_edu_python |
function add self obj
begin
try
begin
call EditMedia dbstate uistate list call MediaObject
end
except WindowActiveError
begin
pass
end
end function | def add(self, obj):
try:
EditMedia(self.dbstate, self.uistate, [], MediaObject())
except WindowActiveError:
pass | Python | nomic_cornstack_python_v1 |
comment CT60A0203 Ohjelmoinnin perusteet
comment Tekijä: Aatu Laitinen
comment Opiskelijanumero: 0501379
comment Päivämäärä: 29.10.2019
comment Yhteistyö ja lähteet, nimi ja yhteistyön muoto:
import math
import random
function paaohjelma
begin
print string Tämä ohjelma käyttää kirjastoja tehtävien ratkaisemiseen.
while... | # CT60A0203 Ohjelmoinnin perusteet
# Tekijä: Aatu Laitinen
# Opiskelijanumero: 0501379
# Päivämäärä: 29.10.2019
# Yhteistyö ja lähteet, nimi ja yhteistyön muoto:
import math
import random
def paaohjelma():
print("Tämä ohjelma käyttää kirjastoja tehtävien ratkaisemiseen.")
while True:
valin... | Python | zaydzuhri_stack_edu_python |
function cells_charts_get_worksheet_chart_legend self name sheet_name chart_index **kwargs
begin
set kwargs at string _return_http_data_only = true
if get kwargs string callback
begin
return call cells_charts_get_worksheet_chart_legend_with_http_info name sheet_name chart_index keyword kwargs
end
else
begin
set data = ... | def cells_charts_get_worksheet_chart_legend(self, name, sheet_name, chart_index, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.cells_charts_get_worksheet_chart_legend_with_http_info(name, sheet_name, chart_index, **kwargs)
else:
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env puthon
comment -*- coding:utf-8 -*-
comment Author:Genming Zhang
from collections import Iterable
print is instance list Iterable
print is instance dict Iterable
print is instance string abc Iterable
print is instance generator expression x for x in range 10 Iterable
comment 判断对象是否是一个Iterable可迭代... | #!/usr/bin/env puthon
# -*- coding:utf-8 -*-
# Author:Genming Zhang
from collections import Iterable
print(isinstance([], Iterable))
print(isinstance({}, Iterable))
print(isinstance('abc', Iterable))
print(isinstance((x for x in range(10)), Iterable))
print(isinstance(100, Iterable))#判断对象是否是一个Iterable可迭代对象
from co... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string Testing file
import json
import requests
if __name__ == string __main__
begin
string Get amenity_id with name Wifi
set r = get requests string http://0.0.0.0:5000/api/v1/amenities
set r_j = json r
set amenity_id = none
for amenity_j in r_j
begin
if get amenity_j string name == string Wi... | #!/usr/bin/python3
"""Testing file
"""
import json
import requests
if __name__ == "__main__":
""" Get amenity_id with name Wifi
"""
r = requests.get("http://0.0.0.0:5000/api/v1/amenities")
r_j = r.json()
amenity_id = None
for amenity_j in r_j:
if amenity_j.get('name') == "Wifi":
... | Python | zaydzuhri_stack_edu_python |
function __eq__ self rhs
begin
set t1 = get FSM_global _id
set t2 = get FSM_global _id
return t1 == t2
end function | def __eq__(self,rhs):
t1 = FSM_global.get(self._id)
t2 = FSM_global.get(rhs._id)
return t1 == t2 | Python | nomic_cornstack_python_v1 |
comment setting up class Patient
class Patient
begin
function __init__ self name age sex bmi num_of_children smoker
begin
set name = name
set age = age
set sex = sex
set bmi = bmi
set num_of_children = num_of_children
set smoker = smoker
end function
function estimated_insurance_cost self
begin
set estimated_cost = 250... | #setting up class Patient
class Patient:
def __init__(self, name, age, sex, bmi, num_of_children, smoker):
self.name= name
self.age= age
self.sex= sex
self.bmi=bmi
self.num_of_children= num_of_children
self.smoker= smoker
def estimated_insurance_cost(self... | Python | zaydzuhri_stack_edu_python |
string ----------------------------------------------- Friction functions Fassett implementation =======
import numpy as np
from model_params import gravity , ks , constantn
function frictionfactor_larsenandlamb_n
begin
comment NOTE that this returns n, not sqrt eight div cf
comment Larsen and Lamb, eq. 3 of methods. V... | """ -----------------------------------------------
Friction functions
Fassett implementation
======= """
import numpy as np
from model_params import gravity, ks, constantn
def frictionfactor_larsenandlamb_n():
# NOTE that this returns n, not sqrt eight div cf
n=(gravity**(-0.5))*(1.0/8.1)*(ks**(-... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment coding=utf-8
import os
import math
import string
import xml.etree.ElementTree as et
import re
import pprint
import random
set file_path = string /Users/apple/Documents/workspace/git/sangoslg/SangoSLG/Resources/res/images/map/map_copyright_src.tmx
set save_path = string /Users/apple... | #!/usr/bin/env python3
# coding=utf-8
import os
import math
import string
import xml.etree.ElementTree as et
import re
import pprint
import random
file_path = "/Users/apple/Documents/workspace/git/sangoslg/SangoSLG/Resources/res/images/map/map_copyright_src.tmx"
save_path = "/Users/apple/Documents/workspace/git/sango... | Python | zaydzuhri_stack_edu_python |
import datetime
comment 获取当前日期和时间
set now = now
print now
comment 获取一个指定日期
set d = call datetime 2019 10 1 12 23 40
print d
comment 日期转字符串
set now = now
set d = string format time now string %Y-%m-%d %H:%M:%S
print d
comment 字符串转日期
set s = string 2020-8-15 2:30:20
comment 格式要与字符串一致
set d1 = string parse time s string %... | import datetime
#获取当前日期和时间
now=datetime.datetime.now()
print(now)
#获取一个指定日期
d=datetime.datetime(2019,10,1,12,23,40)
print(d)
#日期转字符串
now=datetime.datetime.now()
d=now.strftime('%Y-%m-%d %H:%M:%S')
print(d)
#字符串转日期
s='2020-8-15 2:30:20'
d1=datetime.datetime.strptime(s,'%Y-%m-%d %H:%M:%S')#格式要与字符串一致
print(type(d1)) | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.