code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from point import Point
from rectangle import Rectangle
from rectangle import point_in_rect
import turtle
class Circle
begin
string Represents a circle. attributes: center, radius. methods: set_center_radius, move.
function __init__ self
begin
set center = call Point
set radius = 1.0
set cp0 = call Point
set cp1 = call... | from point import Point
from rectangle import Rectangle
from rectangle import point_in_rect
import turtle
class Circle:
"""Represents a circle.
attributes: center, radius.
methods: set_center_radius, move.
"""
def __init__(self):
self.center = Point()
self.radius = 1.0
se... | Python | zaydzuhri_stack_edu_python |
function divide a b
begin
try
begin
return a / b
end
except ZeroDivisionError
begin
comment here we also print desired msg....
return string you cannot divide with zero
end
except TypeError as err
begin
comment here we also print desired msg....
return string you enter string instead of integer
end
except any
begin
ret... | def divide(a,b):
try:
return a/b
except ZeroDivisionError:
return "you cannot divide with zero" # here we also print desired msg....
except TypeError as err:
return "you enter string instead of integer" # here we also print desired msg....
exce... | Python | zaydzuhri_stack_edu_python |
function assigned_user self assigned_user
begin
set _assigned_user = assigned_user
end function | def assigned_user(self, assigned_user):
self._assigned_user = assigned_user | Python | nomic_cornstack_python_v1 |
function breadth_first start expand
begin
string Performs a breadth-first search of a graph-like structure. :param start: Node to start the search from :param expand: Function taking a node as an argument and returning iterable of its child nodes :return: Iterable of nodes in the BFS order Example:: tree = json.loads(s... | def breadth_first(start, expand):
"""Performs a breadth-first search of a graph-like structure.
:param start: Node to start the search from
:param expand: Function taking a node as an argument and returning iterable
of its child nodes
:return: Iterable of nodes in the BFS order
... | Python | jtatman_500k |
function post self dnzo_user
begin
from google.appengine.ext import db
from tasks_data.models import Task
from tasks_data.tasks import update_task_with_params , save_task , task_list_can_add_task
from tasks_data.task_lists import get_task_list
set task = call Task parent=dnzo_user
set task_list = get request string tas... | def post(self, dnzo_user):
from google.appengine.ext import db
from tasks_data.models import Task
from tasks_data.tasks import update_task_with_params, save_task, task_list_can_add_task
from tasks_data.task_lists import get_task_list
task = Task(parent=dnzo_user)
task_list = self.request... | Python | nomic_cornstack_python_v1 |
import logging
import json
import threading
from util.tool import check_address
from BLOCKCHAINclass.duration import Duration
from BLOCKCHAINclass.attribute import Attribute
from BLOCKCHAINclass.account_state import AccountState
from BLOCKCHAINclass.authorization import Authorization
class State
begin
function __init__... | import logging
import json
import threading
from util.tool import check_address
from BLOCKCHAINclass.duration import Duration
from BLOCKCHAINclass.attribute import Attribute
from BLOCKCHAINclass.account_state import AccountState
from BLOCKCHAINclass.authorization import Authorization
class State:
def __init__(s... | Python | zaydzuhri_stack_edu_python |
function setHTML self text
begin
append textBrowser text
end function | def setHTML(self, text):
self.ui.textBrowser.append(text) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import sys
from collections import defaultdict
set BLANK = string ---
function format number
begin
if number == BLANK
begin
return number
end
else
begin
comment remove leading zero
return replace format string {:.2f} number string 0. string .
end
end function
with open argv at 1 as fin
beg... | #!/usr/bin/env python3
import sys
from collections import defaultdict
BLANK = '---'
def format(number):
if number == BLANK:
return number
else:
return '{:.2f}'.format(number).replace('0.', '.') # remove leading zero
with open(sys.argv[1]) as fin:
fin.readline() # skip header
numbers1 = defaultdic... | Python | zaydzuhri_stack_edu_python |
function events self
begin
return _events
end function | def events(self):
return self._events | Python | nomic_cornstack_python_v1 |
function __init__ self wf_data sample_period
begin
set data = as type wf_data string float_
set sample_period = sample_period
set amplitude = call amax data
print string HYYYEEEE
end function | def __init__(self, wf_data, sample_period):
self.data = wf_data.astype('float_')
self.sample_period = sample_period
self.amplitude = np.amax(self.data)
print("HYYYEEEE") | Python | nomic_cornstack_python_v1 |
function write_data_submit ftdi buf size
begin
return call write_data_submit ftdi buf size
end function | def write_data_submit(ftdi, buf, size):
return _ftdi1.write_data_submit(ftdi, buf, size) | Python | nomic_cornstack_python_v1 |
function add_to_rc self content
begin
string add content to the rc script.
if not rewrite_config
begin
raise call DirectoryException string Error! Directory was not intialized w/ rewrite_config.
end
if not rc_file
begin
set tuple rc_path rc_file = call __get_rc_handle root_dir
end
write rc_file content + string
end fun... | def add_to_rc(self, content):
"""
add content to the rc script.
"""
if not self.rewrite_config:
raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.")
if not self.rc_file:
self.rc_path, self.rc_file = self.__get_rc_handle(self.r... | Python | jtatman_500k |
function SayHello
begin
print string hello
return
end function
function SayHelloName name
begin
set name = input string Enter the name:
print format string Hello {}! name
return
end function
function Compare a0 a1 a2
begin
set t = a0 + a1 + a2
set percent = t / 3
if percent >= 50
begin
print string Result:pass
end
else... | def SayHello():
print("hello")
return
def SayHelloName(name):
name=input("Enter the name: ")
print("Hello {}!".format(name))
return
def Compare(a0,a1,a2):
t=a0+a1+a2
percent=t/3
if percent>=50:
print("Result:pass")
else:
print("Result:fail")
re... | Python | zaydzuhri_stack_edu_python |
function print self
begin
for tuple i v in enumerate _adj
begin
if v
begin
print format string vertex {0} i
for e in v
begin
print e
end
print
end
end
end function | def print(self):
for i, v in enumerate(self._adj):
if v:
print("vertex {0}".format(i))
for e in v:
print(e)
print() | Python | nomic_cornstack_python_v1 |
class node
begin
function __init__ self val
begin
set val = val
set left = none
set right = none
end function
end class
input
set list1 = list map int split input string
set root = call node list1 at 0
set temp = root
for i in range 1 length list1
begin
set cur = list1 at i
set temp = root
while temp != none
begin
if c... | class node:
def __init__(self,val):
self.val=val
self.left=None
self.right=None
input()
list1=list(map(int,input().split(' ')))
root=node(list1[0])
temp=root
for i in range(1,len(list1)):
cur=list1[i]
temp=root
while temp!=None:
if cur>temp.val:
if temp.right... | Python | zaydzuhri_stack_edu_python |
function foo
begin
comment 전역 변수 x를 사용하겠다고 설정
global x
comment x는 전역 변수
set x = 20
comment 전역 변수 출력
print x
end function
call foo
comment 전역 변수 출력
print x | def foo():
global x # 전역 변수 x를 사용하겠다고 설정
x = 20 # x는 전역 변수
print(x) # 전역 변수 출력
foo()
print(x) # 전역 변수 출력
| Python | zaydzuhri_stack_edu_python |
function calc_rmse obs mod
begin
return square root mean np mod - obs ^ 2
end function | def calc_rmse(obs,mod):
return np.sqrt(np.mean((mod-obs)**2)) | Python | nomic_cornstack_python_v1 |
function get_words file_name letters
begin
with open file_name encoding=string utf-8 as file
begin
set correct_dict = dict string /n string noun ; string noun string noun ; string /v string verb ; string verb string verb ; string /adj string adjective ; string adj string adjective ; string adv string adverb
set word_li... | def get_words(file_name, letters):
with open(file_name, encoding = 'utf-8') as file:
correct_dict = {"/n":"noun", "noun":"noun", "/v":"verb", "verb":"verb",
"/adj":"adjective", "adj":"adjective", "adv":"adverb"}
word_list = []
for line in file:
for key, value in cor... | Python | nomic_cornstack_python_v1 |
set j1 = 10
set j2 = 3
set k = j2 ^ 3 > j1 and j1 > j2 ^ 2
print k | j1 = 10
j2 = 3
k = j2 ** 3 > j1 and j1 > j2 ** 2
print(k)
| Python | zaydzuhri_stack_edu_python |
function _get_dict_model cls key model spec
begin
try
begin
return model at key
end
except KeyError
begin
raise call ObjectNotFoundError path=spec at string full_path
end
end function | def _get_dict_model(cls, key, model, spec):
try:
return model[key]
except KeyError:
raise ObjectNotFoundError(path=spec["full_path"]) | Python | nomic_cornstack_python_v1 |
function exchange_checker self exchanges
begin
debug string Checking exchanges: '%s' exchanges
set exchanges = split exchanges string ,
set reference = call get_exchanges
for exchange in exchanges
begin
if exchange in reference
begin
pass
end
else
begin
raise call InvalidExchangeError format string Invalid exchange: '{... | def exchange_checker(self, exchanges):
self.logger.debug("Checking exchanges: '%s'", exchanges)
exchanges = exchanges.split(",")
reference = self.get_exchanges()
for exchange in exchanges:
if exchange in reference:
pass
else:
raise ... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
set fname = string ../../../data/diabetes.csv
set df = read csv fname header=none
set X_df = iloc at tuple slice : : slice : - 1 :
set y_df = iloc at tuple slice : : - 1
print value counts y_df /... | # -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
from sklearn.datasets import load_breast_cancer
fname = '../../../data/diabetes.csv'
df = pd.read_csv(fname, header=None)
X_df = df.iloc[:, :-1]
y_df = df.iloc[:, -1]
print(y_df.value_counts() / len(y_df))
pd.options.display.max_columns = 100
from sk... | Python | zaydzuhri_stack_edu_python |
function get_logger module_name
begin
function _logger
begin
string Callable used to obtain current logger object.
return call getLogger module_name
end function
return _logger
end function | def get_logger(module_name):
def _logger():
""" Callable used to obtain current logger object. """
return logging.getLogger(module_name)
return _logger | Python | nomic_cornstack_python_v1 |
function get_project_info configs heartbeat data
begin
string Find the current project and branch. First looks for a .wakatime-project file. Second, uses the --project arg. Third, uses the folder name from a revision control repository. Last, uses the --alternate-project arg. Returns a project, branch tuple.
set tuple ... | def get_project_info(configs, heartbeat, data):
"""Find the current project and branch.
First looks for a .wakatime-project file. Second, uses the --project arg.
Third, uses the folder name from a revision control repository. Last, uses
the --alternate-project arg.
Returns a project, branch tuple.... | Python | jtatman_500k |
from io import open
from time import time
function bubbleSort arr
begin
set n = length arr
for i in range n
begin
for j in range 0 n - i - 1
begin
if integer arr at j > integer arr at j + 1
begin
set tuple arr at j arr at j + 1 = tuple arr at j + 1 arr at j
end
end
end
end function
set tam = list 10000 20000 30000 4000... | from io import open
from time import time
def bubbleSort(arr) :
n = len(arr)
for i in range(n) :
for j in range(0, n - i - 1):
if int(arr[j]) > int(arr[j + 1]) :
arr[j], arr[j + 1] = arr[j + 1], arr[j]
tam = [10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 10... | Python | zaydzuhri_stack_edu_python |
string Write a program which can map() and filter() to make a list whose elements are square of even number in [1,2,3,4,5,6,7,8,9,10].
comment Map works with filter directly
set li = list 1 2 3 4 5 6 7 8 9 10
print list map lambda x -> x ^ 2 filter lambda x -> x % 2 == 0 li | """
Write a program which can map() and filter() to make a list whose elements
are square of even number in [1,2,3,4,5,6,7,8,9,10].
"""
# Map works with filter directly
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, li))))
| Python | zaydzuhri_stack_edu_python |
function reverseString self s
begin
if length s <= 1
begin
return s
end
set start = 0
set end = length s - 1
while start < end
begin
set tuple s at start s at end = tuple s at end s at start
set start = start + 1
set end = end - 1
end
end function | def reverseString(self, s):
if len(s) <=1:
return s
start = 0
end = len(s) - 1
while start<end:
s[start],s[end] = s[end], s[start]
start += 1
end -= 1 | Python | nomic_cornstack_python_v1 |
function test_set_with_deep_key_path_with_list
begin
set deep_key_path = tuple string second string deep string key string path
set test_value = string second deep key path value
set deep_key_path test_value
assert is instance get config string second dict
assert get config deep_key_path == test_value
end function | def test_set_with_deep_key_path_with_list():
deep_key_path = ('second', 'deep', 'key', 'path')
test_value = 'second deep key path value'
config.set(deep_key_path, test_value)
assert isinstance(config.get('second'), dict)
assert config.get(deep_key_path) == test_value | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_security import UserMixin , RoleMixin
from sqlalchemy import func
from sqlalchemy.orm import column_property
set db = call SQLAlchemy
set authors_books = call Table string authors_books call Column string auth... | # -*- coding: utf-8 -*-
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_security import UserMixin, RoleMixin
from sqlalchemy import func
from sqlalchemy.orm import column_property
db = SQLAlchemy()
authors_books = db.Table(
'authors_books',
db.Column('author_id', db.Integer... | Python | zaydzuhri_stack_edu_python |
function sync_tree_with_data self tree data
begin
call setModel call create_model_from_nodes data
call expandAll
end function | def sync_tree_with_data(self, tree: QTreeView, data: List[DataNode]) -> None:
tree.setModel(self.create_model_from_nodes(data))
tree.expandAll() | Python | nomic_cornstack_python_v1 |
function perturb_atomic_coords self structure random
begin
comment for each site in the structure, possibly randomly perturb it
for site in sites
begin
if random < frac_atoms_perturbed
begin
comment perturbation along x-coordinate
set nudge_x = gaussian 0 sigma_atomic_coord_perturbation
while absolute nudge_x > max_ato... | def perturb_atomic_coords(self, structure, random):
# for each site in the structure, possibly randomly perturb it
for site in structure.sites:
if random.random() < self.frac_atoms_perturbed:
# perturbation along x-coordinate
nudge_x = random.gauss(0, self.si... | Python | nomic_cornstack_python_v1 |
function destination_load_jobid_pairs self
begin
call validate list FILE_LOADS string DESTINATION_JOBID_PAIRS
return _destination_load_jobid_pairs
end function | def destination_load_jobid_pairs(
self) -> PCollection[Tuple[str, JobReference]]:
self.validate([WriteToBigQuery.Method.FILE_LOADS],
'DESTINATION_JOBID_PAIRS')
return self._destination_load_jobid_pairs | Python | nomic_cornstack_python_v1 |
import numpy as np
comment import hyperspy.api as hs
comment from hyperspy._signals.signal2d import Signal2D
from AmorphSim.utils.rotation_utils import _get_rotation_matrix , _get_random_2d_rot , _get_random_3d_rot
from AmorphSim.utils.simulation_utils import _get_speckle_size , _get_wavelength , _shape_function , _get... | import numpy as np
#import hyperspy.api as hs
#from hyperspy._signals.signal2d import Signal2D
from AmorphSim.utils.rotation_utils import _get_rotation_matrix, _get_random_2d_rot, _get_random_3d_rot
from AmorphSim.utils.simulation_utils import _get_speckle_size, _get_wavelength, _shape_function, _get_speckle_intensity... | Python | zaydzuhri_stack_edu_python |
import csv , time , random
from bs4 import BeautifulSoup
import urllib2 as url
comment parameters
comment maximum number of items in the item list
set N = 20
set field_names = list string Ratings string Cedent / sponsor string Placement / structuring agent/s string Trigger type string Risk modelling / calculation agent... | import csv, time, random
from bs4 import BeautifulSoup
import urllib2 as url
# parameters
N = 20 # maximum number of items in the item list
field_names = ['Ratings','Cedent / sponsor','Placement / structuring agent/s','Trigger type', 'Risk modelling / calculation agents etc','Risks / perils covered','Issuer','Size',... | Python | zaydzuhri_stack_edu_python |
import tkinter
import tkinter.messagebox as box
import random
class MyGUI
begin
function __init__ self
begin
comment Create the main window.
set mainWindow = call Tk
call geometry string 200x200
title mainWindow string Rock Paper Scissors
comment Create two frames. One for the Radiobuttons
comment and another for the r... | import tkinter
import tkinter.messagebox as box
import random
class MyGUI:
def __init__(self):
# Create the main window.
self.mainWindow = tkinter.Tk()
self.mainWindow.geometry("200x200")
self.mainWindow.title("Rock Paper Scissors")
# Create two frames. One for the Radiobut... | Python | zaydzuhri_stack_edu_python |
comment real signature unknown; restored from __doc__
function entryList self QDir_Filters QStringList
begin
return QStringList
end function | def entryList(self, QDir_Filters, QStringList): # real signature unknown; restored from __doc__
return QStringList | Python | nomic_cornstack_python_v1 |
import unittest
import base
class Suite extends Base
begin
function test_1 self
begin
string Test case 1
start self string Cradio/main
set txt = text
assert equal string Hello, I'm B. I'll be your waiter for this evening. txt
set txt2 = text
assert equal string Value: txt2
set el1 = call xpath string label[1]/input
set... | import unittest
import base
class Suite(base.Base):
def test_1(self):
"""Test case 1"""
self.start("Cradio/main")
txt = self.xpath('div[1]').text
self.assertEqual("Hello, I'm B. I'll be your waiter for this evening.", txt)
txt2 = self.xpath('div[2]').text
self.assert... | Python | zaydzuhri_stack_edu_python |
function weave self aWeb aWeaver
begin
set ux = call userNamesXref
if length ux != 0
begin
call xrefHead
for u in sorted ux
begin
set tuple defn refList = ux at u
call xrefDefLine u defn refList
end
call xrefFoot
end
else
begin
call xrefEmpty
end
end function | def weave( self, aWeb, aWeaver ):
ux= aWeb.userNamesXref()
if len(ux) != 0:
aWeaver.xrefHead()
for u in sorted(ux):
defn, refList= ux[u]
aWeaver.xrefDefLine( u, defn, refList )
aWeaver.xrefFoot()
else:
aWeaver.xrefEm... | Python | nomic_cornstack_python_v1 |
function code self code
begin
set _code = code
end function | def code(self, code):
self._code = code | Python | nomic_cornstack_python_v1 |
set nw = integer input string Insira um valor inteiro:
print format string O seu valor digitado foi de {} nw | nw = int(input('Insira um valor inteiro: '))
print('O seu valor digitado foi de {}'.format(nw))
| Python | zaydzuhri_stack_edu_python |
function refresh self force=false
begin
if _items is none or nocache or force
begin
set items = call browse_source_container _source_id id
set _items = list comprehension call create_media_leaf item self _pytheos for item in items
end
return _items
end function | def refresh(self, force: bool=False):
if self._items is None or self.nocache or force:
items = self._pytheos.api.browse.browse_source_container(self._source_id, self.id)
self._items = [create_media_leaf(item, self, self._pytheos) for item in items]
return self._items | Python | nomic_cornstack_python_v1 |
function count_values variable
begin
set variable_count = 0
end function | def count_values(variable):
variable_count = 0 | Python | nomic_cornstack_python_v1 |
comment Decomposition and abstraction through functions; introduction to recursion
comment decomposition
comment abstract
comment functions
comment block up into modules
comment suppress details
comment create new primitives
comment -def keyword
comment -FunctionName (x) #x represent foraml parameters
comment -return k... | # Decomposition and abstraction through functions; introduction to recursion
#decomposition
#abstract
#functions
#block up into modules
#suppress details
#create new primitives
#-def keyword
#-FunctionName (x) #x represent foraml parameters
#-return keyword
#-none special value
#-invoke a fuctiong by passing a val... | Python | zaydzuhri_stack_edu_python |
function real_normal_exit message=string Configuration completed, exiting...
begin
info message
exit 0
end function | def real_normal_exit(message="Configuration completed, exiting..."):
logging.info(message)
sys.exit(0) | Python | nomic_cornstack_python_v1 |
function _create_problem system workloads preallocation=none relaxed=false
begin
comment Instantiate LP problem
set _malloovia_lp = call MallooviaLp system=system workloads=workloads preallocation=preallocation relaxed=relaxed
comment Write the LP problem and measure the time required to create it
set start = performan... | def _create_problem(
system: System,
workloads: Sequence[Workload],
preallocation: ReservedAllocation = None,
relaxed: bool = False,
) -> Tuple[float, MallooviaLp]:
# Instantiate LP problem
_malloovia_lp = MallooviaLp(
system=system, workloads=workloads, preallocation=preallocation, rela... | Python | nomic_cornstack_python_v1 |
string File Processor
string Works with txt search files, maps and odds
string importing the libs & pkgs
import numpy as np
import re
string returns a map matrix after loading and checking the txt input file
function getMap fileName
begin
string reading the file
with open fileName string r as searchFile
begin
set data ... | ''' File Processor '''
''' Works with txt search files, maps and odds '''
''' importing the libs & pkgs '''
import numpy as np
import re
''' returns a map matrix after loading and checking the txt input file '''
def getMap (fileName):
''' reading the file '''
with open(fileName, 'r') as searchFile:
data = sea... | Python | zaydzuhri_stack_edu_python |
function testWithIO inp out f
begin
try
begin
set tuple oldin stdin = tuple stdin inp
set tuple oldout stdout = tuple stdout out
set x = f dist
end
finally
begin
set stdin = oldin
set stdout = oldout
end
return x
end function | def testWithIO(inp, out, f):
try:
oldin, sys.stdin = sys.stdin, inp
oldout, sys.stdout = sys.stdout, out
x = f()
finally:
sys.stdin = oldin
sys.stdout = oldout
return x | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import aiohttp
from luya import Luya
from luya import response
from luya import blueprint
from luya.exception import NOT_FOUND
from luya.view import MethodView
from lxml import etree
set food_bp = call Blueprint string zhengfang prefix_url=string /food
set headers = dict string User-Agent ... | #!/usr/bin/env python3
import aiohttp
from luya import Luya
from luya import response
from luya import blueprint
from luya.exception import NOT_FOUND
from luya.view import MethodView
from lxml import etree
food_bp = blueprint.Blueprint('zhengfang', prefix_url='/food')
headers = {
"User-Agent": "Mozilla/5.0 (X11... | Python | zaydzuhri_stack_edu_python |
function _intersect_continuous self interval
begin
set first = call bisect_left interval
set last = first
while first > 0 and upper >= lower
begin
set first = first - 1
end
while last < length intervals and lower <= upper
begin
set last = last + 1
end
return tuple first last
end function | def _intersect_continuous(self, interval):
first = self.intervals.bisect_left(interval)
last = first
while first > 0 and \
self.intervals[first - 1].upper >= interval.lower:
first -= 1
while last < len(self.intervals) and \
self.intervals[last].low... | Python | nomic_cornstack_python_v1 |
function separable_axes wcsobj start_frame=none end_frame=none
begin
if wcsobj is not none
begin
if start_frame is none
begin
set start_frame = input_frame
end
else
if start_frame not in available_frames
begin
raise call ValueError format string Unrecognized frame {0} start_frame
end
if end_frame is none
begin
set end_... | def separable_axes(wcsobj, start_frame=None, end_frame=None):
if wcsobj is not None:
if start_frame is None:
start_frame = wcsobj.input_frame
else:
if start_frame not in wcsobj.available_frames:
raise ValueError("Unrecognized frame {0}"... | Python | nomic_cornstack_python_v1 |
comment encoding: utf-8
string @author: sunxianpeng @file: transfer_learning.py @time: 2019/11/8 15:29
import torch
import numpy as np
import torchvision
from torchvision import datasets , transforms , models
import matplotlib.pyplot as plt
import time
import os
import copy
print string Torchvision Version: __version__... | # encoding: utf-8
"""
@author: sunxianpeng
@file: transfer_learning.py
@time: 2019/11/8 15:29
"""
import torch
import numpy as np
import torchvision
from torchvision import datasets, transforms, models
import matplotlib.pyplot as plt
import time
import os
import copy
print("Torchvision Version: ", torchvision.__vers... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import sys , os
comment Ask for input
set user = input string What is the username to remove?
set directory = string /home/backup
comment Create function to remove user/revoke ssh
function delUser user
begin
print string Deleting user: + user
call system string userdel + user
print string Revo... | #!/usr/bin/python3
import sys, os
## Ask for input
user = input("What is the username to remove? ")
directory = "/home/backup"
## Create function to remove user/revoke ssh
def delUser(user):
print ("Deleting user: " + user)
os.system("userdel " + user)
print ("Revoke ssh key for: " + user)
os.system("... | Python | zaydzuhri_stack_edu_python |
import time
import RPi.GPIO as GPIO
comment Moving the car
set FWD_PIN = 6
set BKD_PIN = 13
set LFT_PIN = 19
set RGT_PIN = 26
set OBS_PIN = 5
comment CHANGE TO CHANGE MOVEMENT DISTANCE
set STRAIGHT_TIME = 2
set TURN_TIME = 1
function setup
begin
call setmode BCM
comment Left
setup GPIO LFT_PIN OUT
comment Right
setup G... | import time
import RPi.GPIO as GPIO
# Moving the car
FWD_PIN = 6
BKD_PIN = 13
LFT_PIN = 19
RGT_PIN = 26
OBS_PIN = 5
STRAIGHT_TIME = 2 #CHANGE TO CHANGE MOVEMENT DISTANCE
TURN_TIME = 1
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(LFT_PIN, GPIO.OUT) #Left
GPIO.setup(RGT_PIN, GPIO.OUT) #Right
GPIO.setup(FWD_PIN... | Python | zaydzuhri_stack_edu_python |
function print_usage exitcode reason=none
begin
if reason is not none
begin
print string Error: %s % reason
end
print string Usage: %s <broker> [opts] [<topic>] [<schema_registry>] % argv at 0
print string Options:
print string --consumer, --producer, --avro, --performance - limit to matching tests
exit exitcode
end fu... | def print_usage(exitcode, reason=None):
if reason is not None:
print('Error: %s' % reason)
print('Usage: %s <broker> [opts] [<topic>] [<schema_registry>]' % sys.argv[0])
print('Options:')
print(' --consumer, --producer, --avro, --performance - limit to matching tests')
sys.exit(exitcode) | Python | nomic_cornstack_python_v1 |
function mostra_questao self
begin
print questao
end function | def mostra_questao(self):
print(self.questao) | Python | nomic_cornstack_python_v1 |
import os
from PyPDF2 import PdfFileReader
set path = string /RealPython
set input_file_name = join path path string RealPythonPart1.pdf
set input_file = call PdfFileReader open input_file_name string rb
print string Number of pages: call getNumPages
print string Title: call getDocumentInfo
print call extractText | import os
from PyPDF2 import PdfFileReader
path = "/RealPython"
input_file_name = os.path.join(path,"RealPythonPart1.pdf")
input_file = PdfFileReader(open(input_file_name,'rb'))
print('Number of pages:',input_file.getNumPages())
print('Title:', input_file.getDocumentInfo())
print(input_file.getPage(101).extrac... | Python | zaydzuhri_stack_edu_python |
function fib n
begin
if n < 2
begin
return n
end
else
begin
set a = 0
set b = 1
for _ in range 2 n + 1
begin
set c = a + b
set a = b
set b = c
end
return c
end
end function
print call fib 15 | def fib(n):
if(n<2):
return n
else:
a = 0
b = 1
for _ in range(2,n+1):
c = a+b
a = b
b = c
return c
print(fib(15)) | Python | zaydzuhri_stack_edu_python |
function _custom_round number threshold=0.5
begin
set sign = call copysign 1.0 number
set number = absolute number
set delta = number - call trunc number
if delta < threshold
begin
return call trunc number * sign
end
else
begin
return call trunc number + 1 * sign
end
end function | def _custom_round(number: float, threshold=0.5) -> float:
sign = np.copysign(1.0, number)
number = abs(number)
delta = number - np.trunc(number)
if delta < threshold:
return np.trunc(number) * sign
else:
return (np.trunc(number) + 1) * sign | Python | nomic_cornstack_python_v1 |
function min_time_to_repair ranks cars
begin
sort ranks
set tuple low high = tuple 0 100 * cars * cars
while low < high
begin
set mid = low + high - low // 2
set total_cars_repaired = 0
for rank in ranks
begin
set cars_repaired = min cars mid // rank * rank
set total_cars_repaired = total_cars_repaired + cars_repaired
... | def min_time_to_repair(ranks, cars):
ranks.sort()
low, high = 0, 100 * cars * cars
while low < high:
mid = low + (high - low) // 2
total_cars_repaired = 0
for rank in ranks:
cars_repaired = min(cars, mid // (rank * rank))
total_cars_repaired += cars_repai... | Python | jtatman_500k |
comment Create a list of items (you may use either strings or numbers in the list),
comment then create an iterator using the iter() function.
comment Use a for loop to loop "n" times, where n is the number of items in your list.
comment Each time round the loop, use next() on your list to print the next item.
comment ... | # Create a list of items (you may use either strings or numbers in the list),
# then create an iterator using the iter() function.
#
# Use a for loop to loop "n" times, where n is the number of items in your list.
# Each time round the loop, use next() on your list to print the next item.
#
# hint: use the len() functi... | Python | zaydzuhri_stack_edu_python |
function evaluate self n_games=1 save_path=string ./records use_monitor=true record_video=true verbose=true t_max=10000
begin
set env = call make_env
if not use_monitor and record_video
begin
raise warn string Cannot video without gym monitor. If you still want video, set use_monitor to True
end
if record_video
begin
c... | def evaluate(self,n_games=1,save_path="./records", use_monitor=True,record_video=True,verbose=True,t_max=10000):
env = self.make_env()
if not use_monitor and record_video:
raise warn("Cannot video without gym monitor. If you still want video, set use_monitor to True")
if record_vid... | Python | nomic_cornstack_python_v1 |
function main
begin
set tuple display clock = call init_pygame
set highscores = call HighScores display clock
run
end function | def main():
display, clock = game.init_pygame()
highscores = HighScores(display, clock)
highscores.run() | Python | nomic_cornstack_python_v1 |
function number latter
begin
for num in latter
begin
if num == string X or num == string x
begin
print string R
end
else
begin
print string num
end
end
end function
print call number string word | def number(latter):
for num in latter:
if num == "X" or num == "x":
print ("R")
else:
print ("num")
print (number("word"))
| Python | zaydzuhri_stack_edu_python |
function parse_file_name filename
begin
import re
set rgx = string bin_thresh_([0-9]+).*n_bins_([0-9]+)
set m = search rgx filename
if m
begin
debug format string Matching '{}' to '{}' worked: {} rgx filename call groups
return list comprehension integer call group i for i in list 1 2
end
warning format string Could no... | def parse_file_name(filename):
import re
rgx = r'bin_thresh_([0-9]+).*n_bins_([0-9]+)'
m = re.search(rgx, filename)
if m:
logging.debug('Matching \'{}\' to \'{}\' worked: {}'.format(rgx, filename, m.groups()))
return [int(m.group(i)) for i in [1,2]]
logging.warning('Could not match ... | Python | nomic_cornstack_python_v1 |
import time
import pandas as pd
from presets import *
from genetics import *
import glob
function initialize_current preset_path
begin
for file in glob glob string { preset_path } initial/*
begin
set data = call load_genepool file
set name = split file string / at - 1
call save_genepool data string { preset_path } curr... | import time
import pandas as pd
from presets import *
from genetics import *
import glob
def initialize_current(preset_path):
for file in glob.glob(f'{preset_path}initial/*'):
data = load_genepool(file)
name = file.split('/')[-1]
save_genepool(data, f'{preset_path}current/{name}')
def s... | Python | zaydzuhri_stack_edu_python |
function capitalize mystr
begin
print capitalize mystr
end function | def capitalize(mystr):
print(mystr.capitalize()) | Python | nomic_cornstack_python_v1 |
string A simple neural net for classifying handwritten letter images that contains one hidden layer of 200 units plus one bias unit. The inputs are taken as flattened NumPy arrays of 26x26 images with a bias unit added at the end, for an input size of 785. The output layer is a softmax of 26 units, representing the pro... | """
A simple neural net for classifying handwritten letter images that contains one hidden layer of 200 units
plus one bias unit. The inputs are taken as flattened NumPy arrays of 26x26 images with a bias unit added
at the end, for an input size of 785. The output layer is a softmax of 26 units, representing the
pro... | Python | zaydzuhri_stack_edu_python |
function make_index_unique index join=string -
begin
string Makes the index unique by appending '1', '2', etc. The first occurance of a non-unique value is ignored. Parameters ---------- join The connecting string between name and integer. Examples -------- >>> adata1 = sc.AnnData(np.ones((3, 2)), {'obs_names': ['a', '... | def make_index_unique(index: pd.Index, join: str = '-'):
"""Makes the index unique by appending '1', '2', etc.
The first occurance of a non-unique value is ignored.
Parameters
----------
join
The connecting string between name and integer.
Examples
--------
>>> adata1 = sc.An... | Python | jtatman_500k |
comment The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
comment The else part is executed if the condition in the while loop evaluates to False.
comment The while loop can be terminated with a break statement.
set number = integer input string Enter t... | # The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.
# The else part is executed if the condition in the while loop evaluates to False.
# The while loop can be terminated with a break statement.
number = int(input("Enter the number:"))
i = 1;
while i... | Python | zaydzuhri_stack_edu_python |
function call_on_close self function
begin
call push function
end function | def call_on_close(self, function):
self._close_functions.push(function) | Python | nomic_cornstack_python_v1 |
function _create_wire_invoices cls
begin
call _create_single_invoice_per_purchase WIRE
end function | def _create_wire_invoices(cls):
cls._create_single_invoice_per_purchase(PaymentMethod.WIRE) | Python | nomic_cornstack_python_v1 |
comment https://www.acmicpc.net/problem/2577
set a = integer input
set b = integer input
set c = integer input
set x = a * b * c
set xtr = string x
set counts = list 0 * 10
for i in xtr
begin
set num = integer i
set counts at num = counts at num + 1
end
for i in counts
begin
print i
end | # https://www.acmicpc.net/problem/2577
a = int(input())
b = int(input())
c = int(input())
x = a * b * c
xtr = str(x)
counts = [0] * 10
for i in xtr:
num = int(i)
counts[num] = counts[num] + 1
for i in counts:
print(i) | Python | zaydzuhri_stack_edu_python |
function isolate_priority_lexemes self intermediate_seq
begin
comment Key-value pair
set pair = intermediate_seq at 0
comment List level
for key in pair
begin
if key == string lexeme
begin
append master_seq pop intermediate_seq 0
return intermediate_seq
end
comment Row in config file
for char_seq in values at slice 0 :... | def isolate_priority_lexemes(self, intermediate_seq):
pair = intermediate_seq[0] # Key-value pair
for key in pair: # List level
if key == 'lexeme':
self.master_seq.append(intermediate_seq.pop(0))
return intermediate_seq
for char_seq in self.df.... | Python | nomic_cornstack_python_v1 |
function export_draco mesh
begin
string Export a mesh using Google's Draco compressed format. Only works if draco_encoder is in your PATH: https://github.com/google/draco Parameters ---------- mesh : Trimesh object Returns ---------- data : str or bytes DRC file bytes
with named temporary file suffix=string .ply as tem... | def export_draco(mesh):
"""
Export a mesh using Google's Draco compressed format.
Only works if draco_encoder is in your PATH:
https://github.com/google/draco
Parameters
----------
mesh : Trimesh object
Returns
----------
data : str or bytes
DRC file bytes
"""
wi... | Python | jtatman_500k |
function flip_points labels num_flips
begin
set new_labels = labels
set positive_flips = 0
set negative_flips = 0
for i in range length new_labels
begin
if positive_flips == num_flips and negative_flips == num_flips
begin
break
end
if positive_flips != num_flips and new_labels at i == 1
begin
set new_labels at i = 0
se... | def flip_points(labels, num_flips):
new_labels = labels
positive_flips = 0
negative_flips = 0
for i in range(len(new_labels)):
if positive_flips == num_flips and negative_flips == num_flips:
break
if positive_flips != num_flips and new_labels[i] == 1:
new_labels[i... | Python | nomic_cornstack_python_v1 |
from django.test import TestCase
from models import Category , Location
comment Create your tests here.
class CategoryTestClass extends TestCase
begin
comment Set up method to run tests before
function setUp self
begin
set food = call Category category_name=string Food
end function
comment Testing instance
function tes... | from django.test import TestCase
from .models import Category,Location
# Create your tests here.
class CategoryTestClass(TestCase):
# Set up method to run tests before
def setUp(self):
self.food = Category(category_name = 'Food')
# Testing instance
def test_instance(self):
self.asser... | Python | zaydzuhri_stack_edu_python |
function get_containers_on_datanode self datanode
begin
set container_parent_path = string %s/hdds/%s/current/containerDir0 % tuple datanode_dir scm_uuid
set command = string find %s -type f -name '*.container' % container_parent_path
set tuple exit_code output = call run_docker_command command datanode
set containers ... | def get_containers_on_datanode(self, datanode):
container_parent_path = "%s/hdds/%s/current/containerDir0" % \
(self.datanode_dir, self.scm_uuid)
command = "find %s -type f -name '*.container'" % container_parent_path
exit_code, output = util.run_docker_command(co... | Python | nomic_cornstack_python_v1 |
function to_dict self
begin
set result = dict
for tuple attr _ in call iteritems swagger_types
begin
set value = get attribute self attr
if is instance value list
begin
set result at attr = list map lambda x -> if expression has attribute x string to_dict then call to_dict else x value
end
else
if has attribute value ... | def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
... | Python | nomic_cornstack_python_v1 |
function test_fma_invalid_param_intarray_floatnum_str_floatarray_573 self
begin
comment This version is expected to pass.
call fma floatarrayx floatnumy floatarrayz floatarrayout
comment This is the actual test.
with assert raises TypeError
begin
call fma intarrayx floatnumy strz floatarrayout
end
end function | def test_fma_invalid_param_intarray_floatnum_str_floatarray_573(self):
# This version is expected to pass.
arrayfunc.fma(self.floatarrayx, self.floatnumy, self.floatarrayz, self.floatarrayout)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.fma(self.intarrayx, self.floatnumy, self.st... | Python | nomic_cornstack_python_v1 |
for pi in p
begin
set s = s + character ordinal string a + pi - 1
end
print s | for pi in p:
s += chr(ord("a") + pi - 1)
print(s)
| Python | zaydzuhri_stack_edu_python |
comment noqa: C901
function instantiate_entity cls raw_entity
begin
if string Type not in raw_entity
begin
return raw_entity
end
set entity_type = raw_entity at string Type
comment We get an undefined-variable warning here. _ENTITY_NAME_MAP
comment is not defined/populated until end of module since it needs
comment ent... | def instantiate_entity( # noqa: C901
cls, raw_entity: Mapping[str, Any]
) -> Union["Entity", Mapping[str, Any]]:
if "Type" not in raw_entity:
return raw_entity
entity_type = raw_entity["Type"]
# We get an undefined-variable warning here. _ENTITY_NAME_MAP
# is n... | Python | nomic_cornstack_python_v1 |
function migrate_content_to_v2 self parent child_type log
begin
if flow_class
begin
if child_type in tuple BlockMixin FlowMixin
begin
set div = call add_child Div tuple IMSQTI_NAMESPACE string div
set style_class = flow_class
call migrate_content_to_v2 self div FlowMixin log
end
else
begin
set span = call add_child Spa... | def migrate_content_to_v2(self, parent, child_type, log):
if self.flow_class:
if child_type in (html.BlockMixin, html.FlowMixin):
div = parent.add_child(
html.Div, (qtiv2.core.IMSQTI_NAMESPACE, 'div'))
div.style_class = self.flow_class
... | Python | nomic_cornstack_python_v1 |
function assert_markers_equal self markers
begin
call assert_equal markers call _parse_expected_attr string markers markers
end function | def assert_markers_equal(self, markers):
np.testing.assert_equal(
self.markers, self._parse_expected_attr("markers", markers)) | Python | nomic_cornstack_python_v1 |
comment use of random module
import random
comment intro line using print
print string Hello! welcome to the Guess Game!
print string A random number is generated by the PC and you need to guess it in one chance.
comment Creation of random number from 1 to 10
set num = random integer 1 10
print string Random number is ... | import random # use of random module
print("Hello! welcome to the Guess Game!") # intro line using print
print("A random number is generated by the PC and you need to guess it in one chance.")
num=random.randint(1,10) # Creation of random number from 1 to 10
print("Random number is generated ... | Python | zaydzuhri_stack_edu_python |
function betting game episode buttons
begin
set potential_wager = call process_user_input game player1 player2 buttons
if potential_wager
begin
set wager = potential_wager
call update_tablepot
if folded
begin
print string player1 folded
return false
end
set wager = call process_bot_input game player2 player1 episode
ca... | def betting(game, episode, buttons):
potential_wager = process_user_input(game, game.player1, game.player2, buttons)
if potential_wager:
game.player1.wager = potential_wager
game.update_tablepot()
if game.player1.folded:
print("player1 folded")
return False
... | Python | nomic_cornstack_python_v1 |
function build_hello_email
begin
set from_email = call Email string test@example.com
set subject = string Hello World from the SendGrid Python Library
set to_email = call Email string test@example.com
set content = call Content string text/plain string some text here
set mail = call Mail from_email subject to_email con... | def build_hello_email():
from_email = Email("test@example.com")
subject = "Hello World from the SendGrid Python Library"
to_email = Email("test@example.com")
content = Content("text/plain", "some text here")
mail = Mail(from_email, subject, to_email, content)
mail.personalizations[0].add_to(Emai... | Python | nomic_cornstack_python_v1 |
function sum_even_values *args
begin
set evens = list comprehension num for num in args if num % 2 == 0
if length evens == 0
begin
return 0
end
else
begin
set sum_evens = sum evens
return sum_evens
end
end function
print call sum_even_values 1 2 3 4
comment list comp reference
comment numbers = list(range(1,10))
commen... | def sum_even_values(*args):
evens = [num for num in args if num % 2 ==0]
if len(evens) == 0:
return 0
else:
sum_evens = sum(evens)
return sum_evens
print(sum_even_values(1,2,3,4))
# list comp reference
# numbers = list(range(1,10))
# evens = [num for num in numbers if num % 2 == 0] | Python | zaydzuhri_stack_edu_python |
function get_lineage_assignments self hashval min_num=none
begin
set x = list
set idx_list = get hashval_to_idx hashval list
if min_num is none or length idx_list >= min_num
begin
for idx in idx_list
begin
set lid = get idx_to_lid idx none
if lid is not none
begin
set lineage = lid_to_lineage at lid
append x lineage
e... | def get_lineage_assignments(self, hashval, *, min_num=None):
x = []
idx_list = self.hashval_to_idx.get(hashval, [])
if min_num is None or len(idx_list) >= min_num:
for idx in idx_list:
lid = self.idx_to_lid.get(idx, None)
if lid is not None:
... | Python | nomic_cornstack_python_v1 |
function calculate_principal total_amount rate time
begin
comment Calculate the denominator
set denominator = 1 + rate * time / 100
comment Calculate the principal amount
set principal = total_amount / denominator
comment Round the result to the nearest rupee
return round principal
end function
comment Parameters based... | def calculate_principal(total_amount, rate, time):
# Calculate the denominator
denominator = 1 + (rate * time) / 100
# Calculate the principal amount
principal = total_amount / denominator
# Round the result to the nearest rupee
return round(principal)
# Parameters based on the problem statemen... | Python | dbands_pythonMath |
comment Task:
comment Given a list of numbers of size n, where n is greater than 3, find the maximum and minimum of the list using less than
comment 2 * (n - 1) comparisons.
comment Here's a start:
comment def find_max_and_min_quickly(numbers):
comment # Fill this in.
comment print find_max_and_min_quickly([3, 5, 1, 2,... | # Task:
#
# Given a list of numbers of size n, where n is greater than 3, find the maximum and minimum of the list using less than
# 2 * (n - 1) comparisons.
#
# Here's a start:
#
# def find_max_and_min_quickly(numbers):
# # Fill this in.
#
# print find_max_and_min_quickly([3, 5, 1, 2, 4, 8])
# # (1, 8, 9)
# # wher... | Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render , HttpResponse , redirect
from miapp.models import Region , Employee
from django.contrib import messages
comment Create your views here.
function index request
begin
return call render request string index.html dict string titulo string Inicio ; string mensaje string Proyecto web con... | from django.shortcuts import render, HttpResponse, redirect
from miapp.models import Region, Employee
from django.contrib import messages
# Create your views here.
def index(request):
return render(request, 'index.html', {
'titulo':'Inicio',
'mensaje':'Proyecto web con Django'
})
def listar_r... | Python | zaydzuhri_stack_edu_python |
import time
import math
from selenium import webdriver
from selenium.webdriver.common.by import By
function calc x
begin
return string log absolute 12 * sin integer x
end function
set test_page = string http://suninjuly.github.io/redirect_accept.html
set browser = call Chrome
get browser test_page
try
begin
call click
... | import time
import math
from selenium import webdriver
from selenium.webdriver.common.by import By
def calc(x):
return str(math.log(abs(12*math.sin(int(x)))))
test_page = "http://suninjuly.github.io/redirect_accept.html"
browser = webdriver.Chrome()
browser.get(test_page)
try:
browser.find_element(By.CSS_... | Python | zaydzuhri_stack_edu_python |
set monday = true
set tuesday = false
function weekday_check mon tue
begin
if mon and tue
begin
return string It's a great start to the week!
end
else
if mon
begin
return string Hang in there, it's only Monday.
end
else
if tue
begin
return string Stay strong, it's only Tuesday.
end
else
begin
return string The weekend ... | monday = True
tuesday = False
def weekday_check(mon, tue):
if mon and tue:
return "It's a great start to the week!"
elif mon:
return "Hang in there, it's only Monday."
elif tue:
return "Stay strong, it's only Tuesday."
else:
return "The weekend is almost here, keep going... | Python | jtatman_500k |
function findFunctionsForHist subsystem hist
begin
set functionName = format string findFunctionsFor{}Histogram subsystem
set functionName = call subsystemNamespace functionName=functionName subsystemName=subsystem
set findFunction = get attribute currentModule functionName none
if findFunction is not none
begin
call f... | def findFunctionsForHist(subsystem, hist):
functionName = "findFunctionsFor{}Histogram".format(subsystem.subsystem)
functionName = subsystemNamespace(functionName = functionName, subsystemName = subsystem.subsystem)
findFunction = getattr(currentModule, functionName, None)
if findFunction is not None:
... | Python | nomic_cornstack_python_v1 |
function decode_raw_v1 input_bytes=none out_type=none little_endian=true name=none bytes=none
begin
comment pylint: disable=redefined-builtin
set input_bytes = call deprecated_argument_lookup string input_bytes input_bytes string bytes bytes
comment out_type is a required positional argument in the original API, and ha... | def decode_raw_v1(
input_bytes=None,
out_type=None,
little_endian=True,
name=None,
bytes=None # pylint: disable=redefined-builtin
):
input_bytes = deprecation.deprecated_argument_lookup("input_bytes",
input_bytes, "bytes",
... | Python | nomic_cornstack_python_v1 |
function menu
begin
print string Not Girişi İçin '1'
print string Not Eklemek İçin '2'
print string Not Tespiti İçin '3'
set secim = input string Seçiminiz Nedir?:
if secim == string 1 or secim == string 2 or secim == string 3
begin
return secim
end
else
begin
print string Lütfen Sadece Menüdeki Değerleri Tuşlayınız...... | def menu():
print("Not Girişi İçin '1'")
print("Not Eklemek İçin '2'")
print("Not Tespiti İçin '3'")
secim = input("Seçiminiz Nedir?: ")
if secim == "1" or secim == "2" or secim == "3":
return secim
else:
print("Lütfen Sadece Menüdeki Değerleri Tuşlayınız...")
menu()
def... | Python | zaydzuhri_stack_edu_python |
import uuid
from tabulate import tabulate
comment Print list without id numbers
function print_list list_name=list hidden_fields=list string id string courier_id string transaction_id string basket_id string product_id
begin
print string
set list_without_id = list comprehension dictionary comprehension k : v for tuple... | import uuid
from tabulate import tabulate
# Print list without id numbers
def print_list(
list_name=[],
hidden_fields=["id", "courier_id", "transaction_id", "basket_id", "product_id"],
):
print("\n")
list_without_id = [
{k: v for k, v in d.items() if k not in hidden_fields} for d in list_name
... | Python | zaydzuhri_stack_edu_python |
comment def debug_test():
comment for x in range(10):
comment if x == 8:
comment print('hello number 8')
comment print(x + 10)
comment debug_test()
function add a b
begin
return a + b
end function
assert add 1 2 == 3 msg string Should add integers
assert add - 1 2 == 1 msg string Should handle negative numbers
assert a... | # def debug_test():
# for x in range(10):
# if x == 8:
# print('hello number 8')
# print(x + 10)
# debug_test()
def add(a, b):
return a + b
assert add(1, 2) == 3, 'Should add integers'
assert add(-1, 2) == 1, 'Should handle negative numbers'
assert add(1.1, 2.2) == 3.3, 'Should h... | Python | zaydzuhri_stack_edu_python |
string Created on 2016年8月23日 @author: yuanyun.yy
set str1 = format string {0} love {1}.{2} string I string FishC string com
set str2 = format string {a} love {b}.{c} a=string I b=string FishC c=string com
print str1
print str2
set stringa = string %c % 97
set stringb = string %c %c %c %c % tuple 97 98 99 65
set stringc... | '''
Created on 2016年8月23日
@author: yuanyun.yy
'''
str1 = "{0} love {1}.{2}".format('I','FishC','com')
str2 = "{a} love {b}.{c}".format(a='I',b='FishC',c='com')
print(str1)
print(str2)
stringa = '%c' % 97
stringb = '%c %c %c %c' % (97 ,98, 99,65)
stringc = '%d + %d = %d' % (4,5,4+5)
print(stringc)
| Python | zaydzuhri_stack_edu_python |
function get_categories
begin
set categories = uniq_categs
set result = dict string success true ; string data dict string categories categories
return call jsonify result
end function | def get_categories():
categories = app.preprocessed.uniq_categs
result = {
'success': True,
'data': {
'categories': categories
}
}
return jsonify(result) | 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.