code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function vlan_options self **kwargs
begin
call get attribute client_handle string shell command=string cd + rpc_client_path
set func_name = stack at 0 at 3
if string port in kwargs
begin
set port = pop kwargs string port
end
else
begin
raise call TypeError string Mandatory argument port is missing
end
if string tc_id i... | def vlan_options(self, **kwargs):
getattr(self.client_handle, 'shell')(command="cd "+self.rpc_client_path)
func_name = inspect.stack()[0][3]
if 'port' in kwargs:
port = kwargs.pop('port')
else:
raise TypeError("Mandatory argument port is missing")
if 'tc_... | Python | nomic_cornstack_python_v1 |
function _upload_and_unpack source
begin
with call hide string stdout string running
begin
comment Local archive relative path
set local_archive = string temp.tar.gz
comment Remote archive absolute path
set remote_archive = format string /root/{0} local_archive
comment Remove existing temporary directory
call local str... | def _upload_and_unpack(source):
with hide('stdout', 'running'):
# Local archive relative path
local_archive = 'temp.tar.gz'
# Remote archive absolute path
remote_archive = '/root/{0}'.format(local_archive)
# Remove existing temporary directory
local('(chmod -R u+rwX t... | Python | nomic_cornstack_python_v1 |
comment Klementinus Kennyvito Salim , 2201811391
comment Final Project : Food For Folks
from tkinter import *
from PIL import ImageTk , Image
import webbrowser
comment import necessary APIs
comment Making a Class for application
class Application extends Frame
begin
function __init__ self master
begin
call __init__ sel... | #Klementinus Kennyvito Salim , 2201811391
#Final Project : Food For Folks
from tkinter import *
from PIL import ImageTk, Image
import webbrowser
#import necessary APIs
#Making a Class for application
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
s... | Python | zaydzuhri_stack_edu_python |
function no_limit_value self
begin
return none
end function | def no_limit_value(self):
return None | Python | nomic_cornstack_python_v1 |
function test_enable_retainUnsent
begin
set config_info = call read_config
set config_info at string retainUnsent = true
close open config_file string w
with open config_file string r+ as conf
begin
write conf dumps config_info
end
set config_info = call read_config
assert config_info at string retainUnsent is true
end... | def test_enable_retainUnsent():
config_info = read_config()
config_info['retainUnsent'] = True
open(config_file, 'w').close()
with open(config_file, 'r+') as conf:
conf.write(json.dumps(config_info))
config_info = read_config()
assert config_info['retainUnsent'] is True | Python | nomic_cornstack_python_v1 |
import re
from datetime import date
function expcalc1 firstmonth firstyear secondmonth secondyear
begin
set year1 = firstyear at slice - 4 : :
set year2 = secondyear at slice - 4 : :
set m1 = lower firstmonth
set m2 = lower secondmonth
set m1 = m1 at slice 0 : 3 :
set m2 = m2 at slice 0 : 3 :
set month1 = 0
set m... | import re
from datetime import date
def expcalc1(firstmonth,firstyear,secondmonth,secondyear):
year1=firstyear[-4:]
year2=secondyear[-4:]
m1=firstmonth.lower()
m2=secondmonth.lower()
m1=m1[0:3]
m2=m2[0:3]
month1=0
month2=0
if(m1=="... | Python | zaydzuhri_stack_edu_python |
comment 冒泡排序
comment 两两之间进行比较,以升序或降序的方式调换元素的大小
comment 两个变量两两比较--一次
comment 三个变量两两比较--2次
comment n个变量两两比较--n-1次(n>=2)
set numbers = list comprehension _ for _ in range 22 0 - 1
function bubble_sort numbers
begin
set size = length numbers
set index = 0
comment size-1 比较的轮数,n个元素需要n-1轮比较
while index < size - 1
begin
set i... | # 冒泡排序
# 两两之间进行比较,以升序或降序的方式调换元素的大小
# 两个变量两两比较--一次
# 三个变量两两比较--2次
# n个变量两两比较--n-1次(n>=2)
numbers=[_ for _ in range(22,0,-1)]
def bubble_sort(numbers):
size = len(numbers)
index = 0
# size-1 比较的轮数,n个元素需要n-1轮比较
while index < size -1:
inner_index=0
while inner_index < size-1-... | Python | zaydzuhri_stack_edu_python |
function setProperties self **prop
begin
set lenPropPrefix = length propPrefix
comment '+ 1' allows for the dot separator
set lenAttributeInterfacePrefix = length ATTRIBUTE_INTERFACE_OPTPREFIX + 1
for tuple name val in items prop
begin
if starts with name propPrefix
begin
set name = name at slice lenPropPrefix : :
en... | def setProperties(self, **prop):
lenPropPrefix = len(self.propPrefix)
# '+ 1' allows for the dot separator
lenAttributeInterfacePrefix = len(
AttributeAuthority.ATTRIBUTE_INTERFACE_OPTPREFIX) + 1
for name, val in prop.items():
if name.startswith(self... | Python | nomic_cornstack_python_v1 |
from django.test import TestCase , Client
from models import *
import datetime
from django.utils import timezone
from io import BytesIO
import re
string NOTES | from https://docs.djangoproject.com/en/3.0/topics/testing/tools/ - Use test client to simulate GET and POST requests - Test client does not need server to be r... | from django.test import TestCase, Client
from .models import *
import datetime
from django.utils import timezone
from io import BytesIO
import re
'''
NOTES | from https://docs.djangoproject.com/en/3.0/topics/testing/tools/
- Use test client to simulate GET and POST requests
- Test client does not need server to be ru... | Python | zaydzuhri_stack_edu_python |
function get_employ_id self employ
begin
set field_employ = none
set object_user = call get_object_by_id employ
set meta = object_user at string metadata
set object_values = object_user at string object at string values
for item in meta
begin
if item at string knownId == string ФИО_сотрудника
begin
set field_employ = s... | def get_employ_id(self, employ):
field_employ = None
object_user = self.get_object_by_id(employ)
meta = object_user["metadata"]
object_values = object_user["object"]["values"]
for item in meta:
if item["knownId"] == "ФИО_сотрудника":
field_employ = 'i'... | Python | nomic_cornstack_python_v1 |
function operator self *terms coeffs=none axes=none parallelizer=none logger=none chunk_size=none **operator_settings
begin
if all generator expression is instance t str for t in terms
begin
set computer = call HarmonicProductOperatorTermEvaluator terms
comment determine the symmetries up front to make stuff faster
set... | def operator(self, *terms, coeffs=None, axes=None, parallelizer=None, logger=None, chunk_size=None, **operator_settings):
if all(isinstance(t, str) for t in terms):
computer = HarmonicProductOperatorTermEvaluator(terms)
# determine the symmetries up front to make stuff faster
... | Python | nomic_cornstack_python_v1 |
function test_7 self
begin
set main = call Main
call execute_graphs outstanding=true timeout=10800 save=true
end function
comment main.plot_graphs_results(save=True) | def test_7(self):
main = Main()
main.execute_graphs(outstanding=True,
timeout=10800,
save=True)
# main.plot_graphs_results(save=True) | Python | nomic_cornstack_python_v1 |
function parts self
begin
return _parts
end function | def parts(self):
return self._parts | Python | nomic_cornstack_python_v1 |
import requests
set BASE_URL = string https://api.covid19api.com
set COUNTRIES_ENDPOINT = string /countries
set SUMMARY_ENDPOINT = string /summary
set CONFIRMED_ENDPOINT = string /total/country/{country}/status/confirmed
set RECOVERED_ENDPOINT = string /total/country/{country}/status/recovered
set DEATHS_ENDPOINT = str... | import requests
BASE_URL = "https://api.covid19api.com"
COUNTRIES_ENDPOINT = "/countries"
SUMMARY_ENDPOINT = "/summary"
CONFIRMED_ENDPOINT = "/total/country/{country}/status/confirmed"
RECOVERED_ENDPOINT = "/total/country/{country}/status/recovered"
DEATHS_ENDPOINT = "/total/country/{country}/status/deaths"
def fetc... | Python | zaydzuhri_stack_edu_python |
class DataObject extends object
begin
function __init__ self required_attributes
begin
set _required_attributes = required_attributes
set _built = false
end function
function __call__ self cls *args **kwargs
begin
function build inner_self
begin
for attr in _required_attributes
begin
try
begin
call __getattribute__ inn... | class DataObject(object):
def __init__(self, required_attributes):
self._required_attributes = required_attributes
self._built = False
def __call__(self, cls, *args, **kwargs):
def build(inner_self):
for attr in self._required_attributes:
try:
... | Python | zaydzuhri_stack_edu_python |
function merge_values values return_as_list=true
begin
set grouped_results = group by itertools values key=lambda value -> value at string id
set merged_values = if expression return_as_list then list else counter
for tuple _ g in grouped_results
begin
set groups = list g
set merged_value = dict
for group in groups
b... | def merge_values(values, return_as_list=True):
grouped_results = itertools.groupby(values, key=lambda value: value['id'])
merged_values = [] if return_as_list else collections.Counter()
for _, g in grouped_results:
groups = list(g)
merged_value = {}
for group in groups:
for key, val in group.i... | Python | nomic_cornstack_python_v1 |
comment Advent of Code - http://adventofcode.com/day/1
comment From http://adventofcode.com/day/1
comment Coder : Ginny C Ghezzo
comment What I learned:
import sys
if length argv > 1
begin
set filename = argv at 1
end
else
begin
set filename = string day1data.txt
end
print filename
set f = open filename string r
set fl... | # Advent of Code - http://adventofcode.com/day/1
# From http://adventofcode.com/day/1
# Coder : Ginny C Ghezzo
# What I learned:
import sys
if len(sys.argv) > 1:
filename = sys.argv[1]
else: filename = 'day1data.txt'
print(filename)
f = open(filename,'r')
floor = 0
basement = False
while True:
ch = f.read(1)
... | Python | zaydzuhri_stack_edu_python |
function sort_with_maintained_order array
begin
string Sort an array of integers but maintain the order of similar elements. Parameters ---------- array : List[int] The input array Returns ------- List[int] The sorted array
comment Keep track of elements already seen
set seen_elements = list
comment Loop over the list... | def sort_with_maintained_order(array):
"""
Sort an array of integers
but maintain the order of similar elements.
Parameters
----------
array : List[int]
The input array
Returns
-------
List[int]
The sorted array
"""
# Keep track of elements already seen
... | Python | iamtarun_python_18k_alpaca |
function hpoterms
begin
string Search for HPO terms.
set query = get args string query
if query is none
begin
return call abort 500
end
set terms = sorted call hpo_terms query=query key=call itemgetter string hpo_number
set json_terms = list comprehension dict string name format string {} | {} term at string _id term a... | def hpoterms():
"""Search for HPO terms."""
query = request.args.get('query')
if query is None:
return abort(500)
terms = sorted(store.hpo_terms(query=query), key=itemgetter('hpo_number'))
json_terms = [
{'name': '{} | {}'.format(term['_id'], term['description']),
'id': term... | Python | jtatman_500k |
comment [42] Trapping Rain Water
comment https://leetcode.com/problems/trapping-rain-water/description/
comment algorithms
comment Hard (37.53%)
comment Total Accepted: 162.1K
comment Total Submissions: 432K
comment Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]'
comment Given n non-negative integers representing an elev... | #
# [42] Trapping Rain Water
#
# https://leetcode.com/problems/trapping-rain-water/description/
#
# algorithms
# Hard (37.53%)
# Total Accepted: 162.1K
# Total Submissions: 432K
# Testcase Example: '[0,1,0,2,1,0,1,3,2,1,2,1]'
#
# Given n non-negative integers representing an elevation map where the width
# of each ... | Python | zaydzuhri_stack_edu_python |
for i in S
begin
if i == string 0
begin
set s0 = s0 + 1
end
else
if i == string 1
begin
set s1 = s1 + 1
end
end
print min s0 s1 * 2 | for i in S:
if i == "0":
s0 += 1
elif i == "1":
s1 += 1
print(min(s0, s1) * 2) | Python | zaydzuhri_stack_edu_python |
function tfidf mat=none rownames=none
begin
set colsums = sum mat axis=0
set doccount = shape at 1
set w = array list comprehension call _tfidf_row_func row colsums doccount for row in mat
return tuple w rownames
end function | def tfidf(mat=None, rownames=None):
colsums = np.sum(mat, axis=0)
doccount = mat.shape[1]
w = np.array([_tfidf_row_func(row, colsums, doccount) for row in mat])
return (w, rownames) | Python | nomic_cornstack_python_v1 |
function fetch_block_transaction_hashes self index cb
begin
set data = call pack_block_index index
call send_command string blockchain.fetch_block_transaction_hashes data cb
end function | def fetch_block_transaction_hashes(self, index, cb):
data = pack_block_index(index)
self.send_command('blockchain.fetch_block_transaction_hashes',
data, cb) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Mon Nov 4 22:02:56 2019 @author: Mateusz.Jaworski
set days = list string mon string tue string wed string thu string fri string sat string sun
set workday = copy days
print workday
remove workday string sun
remove workday string sat
print workday | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 4 22:02:56 2019
@author: Mateusz.Jaworski
"""
days = ['mon','tue','wed','thu','fri','sat','sun']
workday=days.copy()
print(workday)
workday.remove('sun')
workday.remove('sat')
print(workday) | Python | zaydzuhri_stack_edu_python |
function test_validateDocumentWithSchema31 self
begin
set res = call validateDocumentWithSchema testFiles at string t31.xml XML_SCHEMA_PATH
assert is none res at string parserError
set msg = string Element 'INSDFeature_quals': Missing child element(s). Expected is ( INSDQualifier ).
assert in msg string res at string s... | def test_validateDocumentWithSchema31(self):
res = util.validateDocumentWithSchema(self.testFiles['t31.xml'],
util.XML_SCHEMA_PATH)
self.assertIsNone(res['parserError'])
msg = r"Element 'INSDFeature_quals': Missing child element(s). Expected is ( INS... | Python | nomic_cornstack_python_v1 |
function set_resources self instance_type=none instance_count=none properties=none **kwargs
begin
if resources is none
begin
set resources = call ResourceConfiguration
end
if instance_type is not none
begin
set instance_type = instance_type
end
if instance_count is not none
begin
set instance_count = instance_count
end... | def set_resources(
self,
*,
instance_type: Union[str, List[str]] = None,
instance_count: int = None,
properties: Dict = None,
**kwargs,
):
if self.resources is None:
self.resources = ResourceConfiguration()
if instance_type is not None:
... | Python | nomic_cornstack_python_v1 |
from time import time
from parameters import MAX_ITERATIONS , GRAPH_NAME
comment Loads a graph
function load_graph data limit=decimal string inf
begin
set graph = dict
with open string ../datasets/ { data } / { data } .v string r as nodes
begin
for node in nodes
begin
set graph at integer node = dict string neighbors ... | from time import time
from parameters import MAX_ITERATIONS, GRAPH_NAME
# Loads a graph
def load_graph(data, limit=float('inf')):
graph = {}
with open(f'../datasets/{data}/{data}.v', 'r') as nodes:
for node in nodes:
graph[int(node)] = {'neighbors': set(),
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import pygame , sys , random | #!/usr/bin/env python
import pygame, sys, random
| Python | zaydzuhri_stack_edu_python |
async function directory self dir_key exist_ok=false
begin
try
begin
await call aclose
end
except KeyError
begin
await put dir_key list
return true
end
try else
begin
if not exist_ok
begin
raise call KeyError string dir_key
end
return false
end
end function | async def directory(self, dir_key: datastore.Key, exist_ok: bool = False) -> bool:
try:
await (await super().get(dir_key)).aclose()
except KeyError:
await super().put(dir_key, [])
return True
else:
if not exist_ok:
raise KeyError(str(dir_key))
return False | Python | nomic_cornstack_python_v1 |
function add_header response
begin
set headers at string X-UA-Compatible = string IE=Edge,chrome=1
set headers at string Cache-Control = string public, max-age=600
return response
end function | def add_header(response):
response.headers['X-UA-Compatible'] = 'IE=Edge,chrome=1'
response.headers['Cache-Control'] = 'public, max-age=600'
return response | Python | nomic_cornstack_python_v1 |
string importing
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils.datastructures import MultiValueDictKeyError
from models import StudentInfo
comment Create your views here.
function add_student request
begin
string add student info
i... | """ importing """
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils.datastructures import MultiValueDictKeyError
from .models import StudentInfo
# Create your views here.
def add_student(request):
"""add student info"""
if ... | Python | zaydzuhri_stack_edu_python |
function append_field self fieldname
begin
comment type: (str) -> None
string Mark a field as present in the Rock Ridge records. Parameters: fieldname - The name of the field to mark as present; should be one of 'PX', 'PN', 'SL', 'NM', 'CL', 'PL', 'RE', or 'TF'. Returns: Nothing.
if not _initialized
begin
raise call Py... | def append_field(self, fieldname):
# type: (str) -> None
'''
Mark a field as present in the Rock Ridge records.
Parameters:
fieldname - The name of the field to mark as present; should be one
of 'PX', 'PN', 'SL', 'NM', 'CL', 'PL', 'RE', or 'TF'.
Ret... | Python | jtatman_500k |
string https://leetcode.com/problems/maximize-score-after-n-operations/ since nums length is 14, we can use bitmask to represent the state of nums
from header import *
class Solution
begin
function maxScore self A
begin
set n = length A
decorator cache
function dp i mask
begin
if mask == 1 ? n - 1
begin
return 0
end
se... | """ https://leetcode.com/problems/maximize-score-after-n-operations/
since nums length is 14, we can use bitmask to represent the state of nums
"""
from header import *
class Solution:
def maxScore(self, A: List[int]) -> int:
n = len(A)
@cache
def dp(i, mask):
if mask==(... | Python | zaydzuhri_stack_edu_python |
function auth_error_handler self f
begin
decorator wraps f
function decorated_function error error_description=none error_uri=none
begin
return f dist error error_description error_uri
end function
set _auth_error_handler = f
return decorated_function
end function | def auth_error_handler(self, f):
@wraps(f)
def decorated_function(error, error_description=None, error_uri=None):
return f(error, error_description, error_uri)
self._auth_error_handler = f
return decorated_function | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[ ]:
from __future__ import absolute_import , division , print_function , unicode_literals
import os
set environ at string TF_CPP_MIN_LOG_LEVEL = string 2
comment In[ ]:
comment TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
comment Helper libraries
import n... | # coding: utf-8
# In[ ]:
from __future__ import absolute_import, division, print_function, unicode_literals
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# In[ ]:
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as... | Python | zaydzuhri_stack_edu_python |
function publish self message_body routing_key exchange=none
begin
set publish_exchange = exchange or exchange
call publish body=message_body exchange=publish_exchange routing_key=routing_key retry=PUBLISH_RETRY retry_policy=dict string interval_start PUBLISH_RETRY_INTERVAL_START ; string interval_step PUBLISH_RETRY_IN... | def publish(self, message_body, routing_key, exchange=None):
publish_exchange = exchange or self.producer.exchange
self.producer.publish(
body=message_body,
exchange=publish_exchange,
routing_key=routing_key,
retry=settings.PUBLISH_RETRY,
ret... | Python | nomic_cornstack_python_v1 |
function wait_for_job self value
begin
info string Waiting for job %s % job_name
if dry_run == true
begin
info string Dry run: continuing
end
else
begin
info string Checking job status...
set provider = call get_provider provider_options
while true
begin
set tasks = call lookup_job_tasks string * job_name_list=list job... | def wait_for_job(self, value):
logger.info('Waiting for job %s' % self.job_name)
if self.provider_options.dry_run == True:
logger.info('Dry run: continuing')
else:
logger.info('Checking job status...')
provider = provider_base.get_provider(self.provider_options)
while True:
... | Python | nomic_cornstack_python_v1 |
function get_SPLASH_from_restAPI spectra_json
begin
comment Initialize the return
set splash_string = none
comment Make the request (note, we need to use 'post' not 'get'
comment and we need to pass a json arg, not a params arg)
set response = post url=SLAPSH_API_URL json=spectra_json
comment Check the response code. 2... | def get_SPLASH_from_restAPI(spectra_json: Dict) -> str:
# Initialize the return
splash_string = None
# Make the request (note, we need to use 'post' not 'get'
# and we need to pass a json arg, not a params arg)
response = requests.post(url=SLAPSH_API_URL, json=spectra_json)
# Check the respon... | Python | nomic_cornstack_python_v1 |
function key_value_root self tag spec separator=none
begin
set separator = separator or string :
set tuple meta_name root = call tag_parts tag spec
if root
begin
remove meta_name root
end
set tag_value = get tag spec at string value
set tag_key = join separator meta_name
return tuple tag_key tag_value root
end function | def key_value_root(self, tag, spec, separator=None):
separator = separator or ":"
meta_name, root = self.tag_parts(tag, spec)
if root:
meta_name.remove(root)
tag_value = tag.get(spec['value'])
tag_key = separator.join(meta_name)
return tag_key, tag_value, root | Python | nomic_cornstack_python_v1 |
function send_tc_form_request self
begin
set tc_obj = env at string trensfer.certificate
for student_rec in student_ids
begin
set tc_ex_rec = search list tuple string name string = id
if id
begin
raise call except_orm call _ string Warning! call _ string The TC process has already been initiated for %s! % name
end
set ... | def send_tc_form_request(self):
tc_obj = self.env['trensfer.certificate']
for student_rec in self.student_ids:
tc_ex_rec = tc_obj.search([('name', '=', student_rec.id)])
if tc_ex_rec.id:
raise except_orm(_('Warning!'),
_("The TC process has... | Python | nomic_cornstack_python_v1 |
function plot_100_image X
begin
set size = integer square root shape at 1
comment sample 100 image, reshape, reorg it
comment 100*400
set sample_idx = random choice array range shape at 0 100
set sample_images = X at tuple sample_idx slice : :
set tuple fig ax_array = call subplots nrows=10 ncols=10 sharey=true shar... | def plot_100_image(X):
size = int(np.sqrt(X.shape[1]))
# sample 100 image, reshape, reorg it
sample_idx = np.random.choice(np.arange(X.shape[0]), 100) # 100*400
sample_images = X[sample_idx, :]
fig, ax_array = plt.subplots(nrows=10, ncols=10, sharey=True, sharex=True, figsize=(8, 8))
for r i... | Python | nomic_cornstack_python_v1 |
function __init__ self *args **kwargs
begin
if string project not in kwargs
begin
raise call TypeError string ProjectAllocationForm missing required argument: 'project'
end
set project = pop kwargs string project none
comment call super
call __init__ *args keyword kwargs
comment do stuff with project to set the initial... | def __init__ (self, *args, **kwargs):
if 'project' not in kwargs:
raise TypeError("ProjectAllocationForm missing required argument: 'project'")
self.project = kwargs.pop('project', None)
# call super
super(ProjectAllocationForm, self).__init__(*args, **kwargs)
# do s... | Python | nomic_cornstack_python_v1 |
import requests
import json
function getRequest user int
begin
set URL = string https://api.github.com/users/ + user + string /repos
set r = get requests URL
set repo = loads text
if int < length repo
begin
set repo = loads text at int at string name
set URL = string https://api.github.com/repos/ + user + string / + re... | import requests
import json
def getRequest(user, int):
URL = "https://api.github.com/users/"+user+"/repos"
r = requests.get(URL)
repo = json.loads(r.text)
if (int < len(repo)):
repo = json.loads(r.text)[int]['name']
URL = "https://api.github.com/repos/"+user+"/"+repo+"/commits"... | Python | zaydzuhri_stack_edu_python |
function camelize_dict d
begin
if not is instance d dict
begin
return d
end
return dictionary list comprehension tuple call to_camel_case v at 0 call camelize_dict v at 1 for v in items d
end function | def camelize_dict(d):
if not isinstance(d, dict):
return d
return dict([(to_camel_case(v[0]), camelize_dict(v[1])) for v in d.items()]) | Python | nomic_cornstack_python_v1 |
function plot_bar_group filename data std=none xlab=string x ylab=string y title=string Bar-Plot methods=none hatchs=none datasets=none figwidth=8 figheight=6 colors=none legend_loc=string lower left xytick_fontsize=12 xylabel_fontsize=15 title_fontsize=15 legend_fontsize=12 ymin=0 ymax=1 rotation=45
begin
import matpl... | def plot_bar_group(filename, data, std=None, xlab='x', ylab='y', title='Bar-Plot', methods=None, hatchs=None, datasets=None, figwidth=8, figheight=6, colors=None, legend_loc="lower left", xytick_fontsize=12, xylabel_fontsize=15, title_fontsize=15, legend_fontsize=12,ymin=0,ymax=1,rotation=45):
import matplotlib as ... | Python | nomic_cornstack_python_v1 |
import os
function ae_chunk file_path window_size
begin
set answer = list
with open file_path string rb as f
begin
set stream = read f
set temp = - 1
set max_point = stream at 0
set chunked = list 0
for idx in range length stream - 1
begin
set temp = temp + 1
if stream at idx > max_point
begin
set max_point = stream at... | import os
def ae_chunk(file_path, window_size):
answer = list()
with open(file_path, 'rb') as f:
stream = f.read()
temp = -1
max_point = stream[0]
chunked = [0]
for idx in range(len(stream) - 1):
temp += 1
if stream[idx] > max_point:
... | Python | zaydzuhri_stack_edu_python |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import datetime
import random
function getNames http
begin
print string http://vstup.info/2018 + http
set html = url open string http://vstup.info/2018 + http
set bsObj = call BeautifulSoup html string lxml
set nameDivs = find all string tr
set ... | from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import datetime
import random
def getNames(http):
print("http://vstup.info/2018" + http)
html = urlopen("http://vstup.info/2018" + http)
bsObj = BeautifulSoup(html, "lxml")
nameDivs = bsObj.find("tbody").findAll("tr")
names = set()
for n ... | Python | zaydzuhri_stack_edu_python |
function _build self s_in s_out
begin
set head_module = call BasicDartsAuxHead init_pool_stride=3
return call build s_in call num_features
end function | def _build(self, s_in: Shape, s_out: Shape) -> Shape:
self.head_module = BasicDartsAuxHead(init_pool_stride=3)
return self.head_module.build(s_in, s_out.num_features()) | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup
set url = input string Enter the page you want to download
set res = get requests url
call raise_for_status
set soup = call BeautifulSoup text string html.parser
for link in find all soup string a
begin
print link
end | import requests
from bs4 import BeautifulSoup
url = input('Enter the page you want to download\n')
res = requests.get(url)
res.raise_for_status()
soup = BeautifulSoup(res.text, 'html.parser')
for link in soup.find_all('a'):
print(link)
| Python | zaydzuhri_stack_edu_python |
import socket
from machine import Pin
from time import sleep_ms
function start
begin
set led = call Pin 2 OUT value=1
set sw_led = call Pin 0 IN PULL_UP
set sw_bye = call Pin 12 IN PULL_UP
set s = call socket AF_INET SOCK_STREAM
call setsockopt SOL_SOCKET SO_REUSEADDR 1
call connect tuple string 192.168.4.1 13326
while... | import socket
from machine import Pin
from time import sleep_ms
def start():
led = Pin(2, Pin.OUT, value=1)
sw_led = Pin(0, Pin.IN, Pin.PULL_UP)
sw_bye = Pin(12, Pin.IN, Pin.PULL_UP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR... | Python | zaydzuhri_stack_edu_python |
function get_chromeos_platform_name
begin
try
begin
set platform = call call_cros_config_get_output string / name run
if platform == string
begin
set platform = call get_board
end
return platform
end
except any
begin
info string Not found
return - 1
end
end function | def get_chromeos_platform_name():
try:
platform = cros_config.call_cros_config_get_output('/ name', utils.run)
if platform == '':
platform = get_board()
return platform
except:
logging.info("Not found")
return -1 | Python | nomic_cornstack_python_v1 |
function one_hot array N
begin
set array = as type array int
assert max array < N
assert min array >= 0
set one_hot = zeros tuple shape at 0 N
set one_hot at tuple array range shape at 0 array = 1
return one_hot
end function | def one_hot(array, N):
array = array.astype(int)
assert numpy.max(array) < N
assert numpy.min(array) >= 0
one_hot = numpy.zeros((array.shape[0], N))
one_hot[numpy.arange(array.shape[0]), array] = 1
return one_hot | Python | nomic_cornstack_python_v1 |
comment distance
import RPi.GPIO as GPIO
import time
comment set modes
call setmode BCM
call setwarnings false
comment define GPIO pins to use on Pi
set pinTrigger = 17
set pinEcho = 18
print string ultrasonic distance
comment set pins as input and output
setup GPIO pinTrigger OUT
setup GPIO pinEcho IN
try
begin
commen... | #distance
import RPi.GPIO as GPIO
import time
#set modes
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#define GPIO pins to use on Pi
pinTrigger = 17
pinEcho = 18
print("ultrasonic distance")
#set pins as input and output
GPIO.setup(pinTrigger, GPIO.OUT)
GPIO.setup(pinEcho, GPIO.IN)
try:
#repeat indented blo... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode.cn id=23 lang=python3
comment [23] 合并K个排序链表
comment https://leetcode-cn.com/problems/merge-k-sorted-lists/description/
comment algorithms
comment Hard (47.71%)
comment Likes: 374
comment Dislikes: 0
comment Total Accepted: 51.9K
comment Total Submissions: 108.8K
comment Testcase Example: '[[1,4... | #
# @lc app=leetcode.cn id=23 lang=python3
#
# [23] 合并K个排序链表
#
# https://leetcode-cn.com/problems/merge-k-sorted-lists/description/
#
# algorithms
# Hard (47.71%)
# Likes: 374
# Dislikes: 0
# Total Accepted: 51.9K
# Total Submissions: 108.8K
# Testcase Example: '[[1,4,5],[1,3,4],[2,6]]'
#
# 合并 k 个排序链表,返回合并后的排序链表... | Python | zaydzuhri_stack_edu_python |
import random
from sklearn import svm
from sklearn import linear_model
from sklearn.metrics import accuracy_score
function parseData fname
begin
for l in open fname
begin
yield split l string ,
end
end function | import random
from sklearn import svm
from sklearn import linear_model
from sklearn.metrics import accuracy_score
def parseData(fname):
for l in open(fname):
yield l.split(',')
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import import_data
import math
import numpy
import collections
import sys
from sklearn import linear_model
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
from itertools import cycle
from sklearn.metrics import roc_curve , auc
set model_to_use = string logist... | #!/usr/bin/python
import import_data
import math
import numpy
import collections
import sys
from sklearn import linear_model
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
from itertools import cycle
from sklearn.metrics import roc_curve, auc
model_to_use = 'logistic'
#model_to_... | Python | zaydzuhri_stack_edu_python |
function count_parameters self
begin
set tuple c_trained c_total = tuple 0 0
for p in parameters self
begin
set increment = reduce lambda x y -> x * y size p
if requires_grad
begin
set c_trained = c_trained + increment
end
set c_total = c_total + increment
end
return tuple c_trained c_total
end function | def count_parameters(self) -> Tuple[int, int]:
c_trained, c_total = 0, 0
for p in self.parameters():
increment = reduce(lambda x, y: x * y, p.size())
if p.requires_grad:
c_trained += increment
c_total += increment
return c_trained, c_total | Python | nomic_cornstack_python_v1 |
function setOrder self order
begin
set orderInData = order
end function | def setOrder(self, order):
self.orderInData = order | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sun Aug 8 12:44:23 2021 @author: alexe
import numpy as np
import pandas as pd
from collections import defaultdict
function activity_ranking X y rxn_component n_splits=4
begin
set mols = call drop_duplicates
set ranked_mols = list
for mol in mols
begin
append ranked_mols ... | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 8 12:44:23 2021
@author: alexe
"""
import numpy as np
import pandas as pd
from collections import defaultdict
def activity_ranking(X, y, rxn_component, n_splits=4):
mols = X.index.get_level_values(rxn_component).drop_duplicates()
ranked_mols = []
for mol i... | Python | zaydzuhri_stack_edu_python |
function findBall grid
begin
set tuple m n = tuple length grid length grid at 0
set ans = list - 1 * n
for i in range n
begin
set tuple r c = tuple 0 i
while r < m
begin
if grid at r at c == 1
begin
if c == n - 1 or grid at r at c + 1 == - 1
begin
break
end
set c = c + 1
end
else
begin
if c == 0 or grid at r at c - 1 =... | def findBall(grid):
m, n = len(grid), len(grid[0])
ans = [-1] * n
for i in range(n):
r, c = 0, i
while r < m:
if grid[r][c] == 1:
if c == n - 1 or grid[r][c+1] == -1:
break
c += 1
else:
if c == 0 or g... | Python | jtatman_500k |
function palindromeInRange start end
begin
for num in range start end + 1
begin
set rev = 0
set n = num
while num > 0
begin
set r = num % 10
set rev = rev * 10 + r
set num = num // 10
end
if rev == n and num > 10
begin
print n end=string
end
end
end function
set start = 100
set end = 500
call palindromeInRange start en... | def palindromeInRange(start, end):
for num in range(start, end + 1):
rev = 0
n = num
while num > 0:
r = num % 10
rev = (rev * 10) + r
num = num // 10
if rev == n and num > 10:
print(n, end=" ")
start = 100
end = 500
palindromeInRange(start, end)
| Python | flytech_python_25k |
function is_error_still_ok df1 df2 decimals=2
begin
set r1 = call get_values df1
set r2 = call get_values df2
comment check each of the error values to check if they are the same to the
comment correct number of decimals
set r1 = list comprehension floor r * 10 ^ decimals for r in r1
set r2 = list comprehension floor r... | def is_error_still_ok(df1, df2, decimals=2):
r1 = get_values(df1)
r2 = get_values(df2)
# check each of the error values to check if they are the same to the
# correct number of decimals
r1 = [math.floor(r * 10**decimals) for r in r1]
r2 = [math.floor(r * 10**decimals) for r in r2]
... | Python | nomic_cornstack_python_v1 |
function train_valid_split raw_data split_index
begin
return tuple raw_data at slice : split_index : raw_data at slice split_index : :
end function | def train_valid_split(raw_data, split_index):
return raw_data[:split_index], raw_data[split_index:] | Python | nomic_cornstack_python_v1 |
import pygame
set playing = true
comment Define the colors we will use in RGB format
set BLACK = tuple 0 0 0
set WHITE = tuple 255 255 255
set BLUE = tuple 0 0 255
set GREEN = tuple 0 255 0
set RED = tuple 255 0 0
set GRAY = tuple 128 128 128
set LIME = tuple 0 255 0
set PURPLE = tuple 128 0 128
set TEAL = tuple 0 128 ... | import pygame
playing = True
# Define the colors we will use in RGB format
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
BLUE = ( 0, 0, 255)
GREEN = ( 0, 255, 0)
RED = (255, 0, 0)
GRAY = (128, 128, 128)
LIME = ( 0, 255, 0)
PURPLE = (128, 0, 128)
TEAL = ( 0, 128, 128)
YELLOW = (255, 25... | Python | zaydzuhri_stack_edu_python |
comment Lowest SHA-512 value by brute force (Python)
comment Copyright (c) 2020 Project Nayuki
comment All rights reserved. Contact Nayuki for licensing.
comment https://www.nayuki.io/page/lowest-sha512-value-by-brute-force
import hashlib , itertools
function main
begin
comment Configuration and constraints
set MSG_LEN... | #
# Lowest SHA-512 value by brute force (Python)
#
# Copyright (c) 2020 Project Nayuki
# All rights reserved. Contact Nayuki for licensing.
# https://www.nayuki.io/page/lowest-sha512-value-by-brute-force
#
import hashlib, itertools
def main():
# Configuration and constraints
MSG_LEN = 12
START_CHAR = ord("a")
... | Python | zaydzuhri_stack_edu_python |
function increment_scan_point_count self
begin
set _scan_point_count = _scan_point_count + 1
end function | def increment_scan_point_count(self):
self._scan_point_count += 1 | Python | nomic_cornstack_python_v1 |
import random
import itertools
import collections
import time
import operator
from tkinter import *
class Node
begin
string A class representing an Solver node - 'puzzle' is a Puzzle instance - 'parent' is the preceding node generated by the solver - 'action' is the action taken to produce puzzle _ 'g' is cost from sta... | import random
import itertools
import collections
import time
import operator
from tkinter import *
class Node:
"""
A class representing an Solver node
- 'puzzle' is a Puzzle instance
- 'parent' is the preceding node generated by the solver
- 'action' is the action taken to produce puzzle
... | Python | zaydzuhri_stack_edu_python |
comment returnfun
string 函数作为返回值 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。 我们来实现一个可变参数的求和。通常情况下,求和的函数是这样定义的: def calc_sum(*args): ax = 0 for n in args: ax = ax + n return ax 但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?可以不返回求和的结果,而是返回求和的函数:
function lazy_sum *args
begin
function sum
begin
set ax = 0
for n in args
begin
set ax = ax + n
end... | #returnfun
r'''
函数作为返回值
高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回。
我们来实现一个可变参数的求和。通常情况下,求和的函数是这样定义的:
def calc_sum(*args):
ax = 0
for n in args:
ax = ax + n
return ax
但是,如果不需要立刻求和,而是在后面的代码中,根据需要再计算怎么办?可以不返回求和的结果,而是返回求和的函数:
'''
def lazy_sum(*args):
def sum():
ax = 0
for n in args:
... | Python | zaydzuhri_stack_edu_python |
function convert_conf_for_unreachable params
begin
string The 'u' state for UNREACHABLE has been rewritten in 'x' in: * flap_detection_options * notification_options * snapshot_criteria So convert value from config file to keep compatibility with Nagios :param params: parameters of the host before put in properties :ty... | def convert_conf_for_unreachable(params):
"""
The 'u' state for UNREACHABLE has been rewritten in 'x' in:
* flap_detection_options
* notification_options
* snapshot_criteria
So convert value from config file to keep compatibility with Nagios
:param params: param... | Python | jtatman_500k |
function is_post_authorised self params
begin
if string id not in params or not params at string id
begin
return true
end
else
begin
return call is_get_authorised params at string id
end
end function | def is_post_authorised(self, params):
if 'id' not in params or not params['id']:
return True
else:
return self.is_get_authorised(params['id']) | Python | nomic_cornstack_python_v1 |
function dashed_line self
begin
for i in range length
begin
call pd
call forward 5
call pu
call forward 5
end
end function | def dashed_line(self):
for i in range(self.length):
tim.pd()
tim.forward(5)
tim.pu()
tim.forward(5) | Python | nomic_cornstack_python_v1 |
function remove_copies m_list
begin
set rand_list = list set m_list
reverse m_list
for i in rand_list
begin
while count m_list i > 1
begin
remove m_list i
end
end
reverse m_list
end function | def remove_copies(m_list):
rand_list = list(set(m_list))
m_list.reverse()
for i in rand_list:
while m_list.count(i) > 1:
m_list.remove(i)
m_list.reverse() | Python | nomic_cornstack_python_v1 |
import subprocess
import os
set tmp_game_filename = string tmp_game.rbg
set tmp_game_text = string #players = red(100), blue(50) #pieces = e, r, b #variables = turn(10) #board = rectangle(up, down, left, right, [b,r,e] [e,e,e] [e,e,e]) #rules = ->red . (up + down + left + right)* . . [r] . {r} . (up + down + left + rig... | import subprocess
import os
tmp_game_filename = 'tmp_game.rbg'
tmp_game_text = '''
#players = red(100), blue(50)
#pieces = e, r, b
#variables = turn(10)
#board = rectangle(up, down, left, right,
[b,r,e]
[e,e,e]
[e,e,e])
#rules = ->red . (up + down + left + right)* . . [r] . {r} . (up + down + left + right... | Python | zaydzuhri_stack_edu_python |
function previous_value self
begin
if _previous_value_present
begin
return _previous_value_value
end
else
begin
return none
end
end function | def previous_value(self):
if self._previous_value_present:
return self._previous_value_value
else:
return None | Python | nomic_cornstack_python_v1 |
function GetReferenceImage self
begin
return call itkResampleImageFilterIVF23IVF23_GetReferenceImage self
end function | def GetReferenceImage(self) -> "itkImageBase3 const *":
return _itkResampleImageFilterPython.itkResampleImageFilterIVF23IVF23_GetReferenceImage(self) | Python | nomic_cornstack_python_v1 |
import time
import os
function condition h a b c d e f g h1 i j
begin
if h == 0
begin
print j
end
else
if h == 1
begin
print a
end
else
if h == 2
begin
print b
end
else
if h == 3
begin
print c
end
else
if h == 4
begin
print d
end
else
if h == 5
begin
print e
end
else
if h == 6
begin
print f
end
else
if h == 7
begin
pri... | import time
import os
def condition(h,a,b,c,d,e,f,g,h1,i,j):
if h==0:
print(j)
elif h==1:
print(a)
elif h==2:
print(b)
elif h==3:
print(c)
elif h==4:
print(d)
elif h==5:
print(e)
elif h==6:
print(f)
elif h==... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment # Solution: Exercise 4.M02
comment ### a) Fahrenheit to Celsius
comment To convert a temperature in Fahrenheit to the equivalent temperature in celsius use:
comment \begin{equation}
comment T_{Celsius} = (T_{Fahrenheit} - 32) \cdot 5/9
comment \end{equation}
comment In[9]:
comment Initiali... | # coding: utf-8
# # Solution: Exercise 4.M02
# ### a) Fahrenheit to Celsius
# To convert a temperature in Fahrenheit to the equivalent temperature in celsius use:
# \begin{equation}
# T_{Celsius} = (T_{Fahrenheit} - 32) \cdot 5/9
# \end{equation}
# In[9]:
# Initialize test temperature [in Fahrenheit]
temperatu... | Python | zaydzuhri_stack_edu_python |
function _displayExperimentSessionSettingsDialog self allSessionDialogVariables sessionVariableOrder
begin
set sessionDlg = call DlgFromDict allSessionDialogVariables string Experiment Session Settings list sessionVariableOrder
set result = none
if OK
begin
set result = allSessionDialogVariables
end
return result
end ... | def _displayExperimentSessionSettingsDialog(self,allSessionDialogVariables,sessionVariableOrder):
sessionDlg=gui.DlgFromDict(allSessionDialogVariables, 'Experiment Session Settings', [], sessionVariableOrder)
result=None
if sessionDlg.OK:
result=allSessionDialogVari... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import asyncio
import json
import time
import os , sys
set parentdir = directory name path directory name path absolute path path __file__
insert path 0 parentdir
import websockets
class room
begin
set users = list
function __init__ self name id=time
begin
set name = name
set id = id
run
e... | #!/usr/bin/env python
import asyncio
import json
import time
import os,sys
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0,parentdir)
import websockets
class room:
users = []
def __init__(self, name,id=time.time()):
self.name = name
self.id=id
... | Python | zaydzuhri_stack_edu_python |
function forward self prev_y_batch prev_h_batch equ_encoder_outputs sns_encoder_outputs z_sample input_equ_node_mask input_sns_node_mask
begin
comment calcualte attention from current RNN state and equation encoder outputs
set attn_weights_equ = call attn_equ prev_h_batch equ_encoder_outputs input_equ_node_mask
comment... | def forward(self, prev_y_batch, prev_h_batch, equ_encoder_outputs, sns_encoder_outputs, z_sample,input_equ_node_mask, input_sns_node_mask):
# calcualte attention from current RNN state and equation encoder outputs
attn_weights_equ = self.attn_equ(prev_h_batch, equ_encoder_outputs, input_equ_node_mask)
... | Python | nomic_cornstack_python_v1 |
from benford import benford_test
from flask import Flask , flash , render_template , request
import json
import plotly.express as px
from plotly.utils import PlotlyJSONEncoder
set app = call Flask __name__
with open string secretkey.txt string r as secret
begin
set secret_key = read secret
end
decorator call route stri... | from benford import benford_test
from flask import Flask, flash, render_template, request
import json
import plotly.express as px
from plotly.utils import PlotlyJSONEncoder
app = Flask(__name__)
with open('secretkey.txt','r') as secret:
app.secret_key = secret.read()
@app.route('/Home')
@app.route('/')
def home()... | Python | zaydzuhri_stack_edu_python |
function get_latest_bars_values self symbol val_type N=1
begin
try
begin
set bars_list = call get_latest_bars symbol N
end
except KeyError
begin
print string That symbol is not available in the historical data set.
raise
end
try else
begin
return array list comprehension get attribute b at 1 val_type for b in bars_list... | def get_latest_bars_values(self, symbol, val_type, N=1):
try:
bars_list = self.get_latest_bars(symbol, N)
except KeyError:
print("That symbol is not available in the historical data set.")
raise
else:
return np.array([getattr(b[1], val_type) for b ... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
set iris = call load_iris
set X = data
set y = target
comment 只选取两个特征
set X = X at tuple y < 2 slice : 2 :
set y = y at y < 2
comment plt.scatter(X[y==0,0], X[y==0,1], color='r')
comment plt.scatter(X[y==1,0], X[y==1,1], color='green')
co... | import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 只选取两个特征
X = X[y<2, :2]
y = y[y<2]
# plt.scatter(X[y==0,0], X[y==0,1], color='r')
# plt.scatter(X[y==1,0], X[y==1,1], color='green')
# plt.show()
from Machine_Learning.model_sele... | Python | zaydzuhri_stack_edu_python |
function load_page self
begin
if enable == true
begin
if length stories < 2
begin
comment get a page stories
set page_stories = call get_page_item page
if page_stories
begin
append stories page_stories
set page = page + 1
end
end
end
end function | def load_page(self):
if self.enable == True:
if len(self.stories) < 2:
# get a page stories
page_stories = self.get_page_item(self.page)
if page_stories:
self.stories.append(page_stories)
self.page += 1 | Python | nomic_cornstack_python_v1 |
comment V1.0
comment def foo():
comment print('foo')
comment foo #表示是函数
comment foo() #表示执行foo函数
comment V 2.0
comment def foo():
comment print("foo")
comment foo=lambda x:x+1
comment foo()
comment #v3.0
comment def haha(func):
comment print('haha...')
comment func()
comment print('zeze..')
comment def hehe():
comment ... | # V1.0
# def foo():
# print('foo')
#
# foo #表示是函数
# foo() #表示执行foo函数
#V 2.0
# def foo():
# print("foo")
#
# foo=lambda x:x+1
# foo()
# #v3.0
# def haha(func):
# print('haha...')
# func()
# print('zeze..')
# def hehe():
# print('hehe...')
#
# haha(hehe)
#V 4.0
'''初创公司有N个业务部门,1个基础平台部门,基础平台负责提供... | Python | zaydzuhri_stack_edu_python |
function test_run_mantel_correlogram_too_small self
begin
set exp = tuple string # A sample comment. DM DM Number of entries Number of permutations Class index Number of distances Mantel r statistic p-value p-value (Bonferroni corrected) Tail type foo.txt baz.txt Too few samples list 0
set obs = call run_mantel_correl... | def test_run_mantel_correlogram_too_small(self):
exp = ('# A sample comment.\nDM\tDM\tNumber of entries\tNumber of '
'permutations\tClass index\tNumber of distances\tMantel r statistic\t'
'p-value\tp-value (Bonferroni corrected)\tTail type\nfoo.txt\tbaz.txt'
'\t\... | Python | nomic_cornstack_python_v1 |
function reg_col self column_settings=none
begin
comment TODO: HG: Use reference field
if column_settings is none
begin
raise call ValueError string column_settings cannot be None
end
set column_nm = strip column_nm
set column_nm = lower column_nm
set column_nm = column_nm
set table at column_nm = column_settings
retur... | def reg_col(self, column_settings: ColFormatter = None):
# TODO: HG: Use reference field
if column_settings is None:
raise ValueError("column_settings cannot be None")
column_nm = column_settings.column_nm.strip()
column_nm = column_nm.lower()
column_settings.co... | Python | nomic_cornstack_python_v1 |
function test_unused_token_is_valid self
begin
assert call is_valid
end function | def test_unused_token_is_valid(self):
assert self.token.is_valid() | Python | nomic_cornstack_python_v1 |
comment check empty or not
comment case 1
set name = string abc
if name
begin
comment check string is empty or not
print string string not empty
end
else
begin
print string string empty
end
comment case 2
set nme = input string enter name ::
if nme
begin
print string your name is { nme }
end
else
begin
print string str... | # check empty or not
#case 1
name="abc"
if name:
print("string not empty") #check string is empty or not
else:
print("string empty")
# case 2
nme=input("enter name ::")
if nme:
print(f"your name is {nme}")
else:
print("string is empty") | Python | zaydzuhri_stack_edu_python |
import sys
import cv2
import numpy as np
from pdf2image import convert_from_bytes
import typer
set THRESHOLD = 0.07
set IOU_THRESHOLD = 0.75
set BLACK_THRESHOLD = 30
function read_document path
begin
if ends with path string .pdf
begin
set img = call convert_from_bytes read open path at 0
set img = array img
end
else
b... | import sys
import cv2
import numpy as np
from pdf2image import convert_from_bytes
import typer
THRESHOLD = 0.07
IOU_THRESHOLD = 0.75
BLACK_THRESHOLD = 30
def read_document(path):
if path.endswith(".pdf"):
img = convert_from_bytes(open(path).read())[0]
img = np.array(img)
else:
img = ... | Python | zaydzuhri_stack_edu_python |
from django.db import models
comment LANGUAGE/LESSON MODELS - MAY BE MOVED INTO ITS OWN APP ###
class LanguageManager extends Manager
begin
string Manager class for language methods
function get_lesson_count self lesson language
begin
string Method for returning the lesson count for a particular language
set count = co... | from django.db import models
### LANGUAGE/LESSON MODELS - MAY BE MOVED INTO ITS OWN APP ###
class LanguageManager(models.Manager):
""" Manager class for language methods """
def get_lesson_count(self, lesson, language):
""" Method for returning the lesson count for a particular language """
co... | Python | zaydzuhri_stack_edu_python |
function add_product request
begin
comment redirect if user not superuser
if not is_superuser
begin
error request string Sorry, incorrect url
return call redirect reverse string shop
end
if method == string POST
begin
if string is_sizes in POST and string is_for_six in POST
begin
error request string Please only select... | def add_product(request):
# redirect if user not superuser
if not request.user.is_superuser:
messages.error(request, 'Sorry, incorrect url')
return redirect(reverse('shop'))
if request.method == 'POST':
if 'is_sizes' in request.POST and 'is_for_six' in request.POST:
mes... | Python | nomic_cornstack_python_v1 |
function goto
begin
set dirgo = input string Введите полный путь до директории в которую хотите перейти:
try
begin
change directory dirgo
print string Вы успешно перешли в нужную диреткорию.
call action
end
except any
begin
print string Что то пошло не так... Не удалось изменит директорию.
call action
end
end function
... | def goto():
dirgo = input('Введите полный путь до директории в которую хотите перейти: ')
try:
os.chdir(dirgo)
print('Вы успешно перешли в нужную диреткорию.')
action()
except:
print('Что то пошло не так... Не удалось изменит директорию.')
action()
def listdir():
... | Python | zaydzuhri_stack_edu_python |
function draw_keypoints img kpts config
begin
assert config at string keypoint_color is not none
set img_kp = call drawKeypoints img kpts none color=config at string keypoint_color
return img_kp
end function | def draw_keypoints(
img:np.array,
kpts:List[cv2.KeyPoint],
config:Dict) -> np.array:
assert config['keypoint_color'] is not None
img_kp = cv2.drawKeypoints(img, kpts, None, color=config['keypoint_color'])
return img_kp | Python | nomic_cornstack_python_v1 |
function on_received self order
begin
append received_messages order
call on_interesting_shit
end function | def on_received(self, order):
self.received_messages.append(order)
self.bm.on_interesting_shit() | Python | nomic_cornstack_python_v1 |
import numpy as np
function work_on_title combine
begin
for dataset in combine
begin
set dataset at string Title = extract str string ([A-Za-z]+)\. expand=false
end
for dataset in combine
begin
set dataset at string Title = replace dataset at string Title list string Lady string Countess string Don string Dr string Rev... | import numpy as np
def work_on_title(combine):
for dataset in combine:
dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False)
for dataset in combine:
dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess', 'Don', 'Dr', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
... | Python | zaydzuhri_stack_edu_python |
import socket
import subprocess
import os
set s = call socket
set host = call gethostname
set stat1 = string KO
set stat2 = string KO
set stat3 = string KO | import socket
import subprocess
import os
s = socket.socket()
host = socket.gethostname()
stat1='KO'
stat2='KO'
stat3='KO' | Python | zaydzuhri_stack_edu_python |
import pytest
function myfunc a b c=3
begin
print a b c
return a + b + c
end function
function test_myfunc
begin
assert 6 == call myfunc 1 2
set arg = dict string a 2 ; string b 5
assert 10 == call myfunc keyword arg
set arg = dict string a 1 ; string b 2 ; string c 3
assert 6 == call myfunc keyword arg
end function
fu... | import pytest
def myfunc(a, b, c=3):
print(a, b, c)
return a + b + c
def test_myfunc():
assert 6 == myfunc(1, 2)
arg = {"a": 2, "b": 5}
assert 10 == myfunc(**arg)
arg = {"a": 1, "b": 2, "c": 3}
assert 6 == myfunc(**arg)
def test_unexpected_keyword_argument_error():
with pytest.ra... | Python | zaydzuhri_stack_edu_python |
function suggest_name2write filepath
begin
set tuple pdir filename = split path filepath
set filepaths = glob glob join path pdir string *
set tuple filepath_wo_ext ext = call splitext filepath
set verNo = 1
if not exists path filepath
begin
return filepath
end
while filepath in filepaths
begin
set newfilepath = filepa... | def suggest_name2write(filepath):
pdir, filename = os.path.split(filepath)
filepaths = glob.glob(os.path.join(pdir, '*'))
filepath_wo_ext, ext = os.path.splitext(filepath)
verNo = 1
if not os.path.exists(filepath):
return filepath
while filepath in filepaths:
newfilepath = filepa... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
set fig = figure
set ax = call axes xlim=tuple - 0.1 1.1 ylim=tuple 9 21 xlabel=string u
grid
set frameCount = 50
set x = linear space 0 1 frameCount
set y = add np call multiply x 10 10
set tuple line = plot x y lw=2
set tuple dots = p... | import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
fig = plt.figure()
ax = plt.axes(xlim=(-0.1, 1.1), ylim=(9, 21), xlabel='u')
ax.grid()
frameCount = 50
x = np.linspace(0, 1, frameCount);
y = np.add(np.multiply(x, 10), 10)
line, = ax.plot(x, y, lw=2)
dots, = ax.plot([], [], 'go', m... | 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.