code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function findNum
begin
set tuple m n = map int split input
while true
begin
if m == n
begin
return 10 * n
end
if m > n
begin
set m = m // 2
end
else
begin
set n = n // 2
end
end
end function
for _ in range test_case
begin
print call findNum
end | def findNum():
m,n = map(int,input().split())
while True:
if m==n:
return 10*n
if m>n:
m//=2
else:
n//=2
for _ in range(test_case):
print(findNum()) | Python | zaydzuhri_stack_edu_python |
comment Given two words source and target, and a list of words words, find the length of the shortest series of edits that
comment transforms source to target.
comment Each edit must change exactly one letter at a time, and each intermediate word (and the final target word) must
comment exist in words.
comment If the t... | # Given two words source and target, and a list of words words, find the length of the shortest series of edits that
# transforms source to target.
#
# Each edit must change exactly one letter at a time, and each intermediate word (and the final target word) must
# exist in words.
#
# If the task is impossible, return ... | Python | zaydzuhri_stack_edu_python |
function validate_number_attribute tag attribute_name attribute_value
begin
if not attribute_value
begin
return
end
comment If the given attribute value is either integer/float, then return the
comment value.
if is instance attribute_value tuple int float
begin
return attribute_value
end
else
comment Give attribute val... | def validate_number_attribute(tag, attribute_name, attribute_value):
if not attribute_value:
return
# If the given attribute value is either integer/float, then return the
# value.
if isinstance(attribute_value, (int, float)):
return attribute_value
# Give attribute value can be a s... | Python | nomic_cornstack_python_v1 |
comment J3 Hidden Palindrome 2016
comment Tissan Kugathas
comment ICS4U0
comment September 9 2019
comment Ask user to input the text
set string = input string Enter the text:
comment this takes the text makes sure it is lower cased
set string = lower string
comment this allows the loop to run until it finds the longest... | # J3 Hidden Palindrome 2016
# Tissan Kugathas
# ICS4U0
# September 9 2019
# Ask user to input the text
string = input("Enter the text: ")
# this takes the text makes sure it is lower cased
string = string.lower()
# this allows the loop to run until it finds the longest loop possible
loop = True
found = False
# th... | Python | zaydzuhri_stack_edu_python |
function ScenarioReplayExcelAddVolumeId builder VolumeId
begin
return call AddVolumeId builder VolumeId
end function | def ScenarioReplayExcelAddVolumeId(builder, VolumeId):
return AddVolumeId(builder, VolumeId) | Python | nomic_cornstack_python_v1 |
string Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Try to do this in one pass. | """
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
""" | Python | zaydzuhri_stack_edu_python |
function getheaderAnim im
begin
set bb = string GIF89a
set bb = bb + call intToBin size at 0
set bb = bb + call intToBin size at 1
set bb = bb + string
return bb
end function | def getheaderAnim(im):
bb = "GIF89a"
bb += intToBin(im.size[0])
bb += intToBin(im.size[1])
bb += "\x87\x00\x00"
return bb | Python | nomic_cornstack_python_v1 |
function align_pair reference reference_rc pair indel_score=1 method_sse=false
begin
if method_sse
begin
set left = call align_sse reference pair at 0 indel_score
set right = call align_sse reference_rc pair at 1 indel_score
end
else
begin
set left = call align reference pair at 0 indel_score
set right = call align ref... | def align_pair(reference, reference_rc, pair, indel_score=1, method_sse=False):
if method_sse:
left = align_sse(reference, pair[0], indel_score)
right = align_sse(reference_rc, pair[1], indel_score)
else:
left = align(reference, pair[0], indel_score)
right = align(reference_rc, p... | Python | nomic_cornstack_python_v1 |
function changeBase n b
begin
set tuple x y = divide mod n b
if x > 0
begin
return call changeBase x b + baseList at y
end
else
begin
return baseList at y
end
end function
comment if __name__ == '__main__':
comment print (changeBase(123456789000,62)) | def changeBase(n,b):
x,y = divmod(n,b)
if x>0:
return changeBase(x,b) + baseList[y]
else:
return baseList[y]
# if __name__ == '__main__':
# print (changeBase(123456789000,62)) | Python | zaydzuhri_stack_edu_python |
import pygame , os , _thread , queue , socket , pickle
from tkinter import *
comment battleship class
class Battleship
begin
function __init__ self id size startpos
begin
set id = id
comment num of boxes length
set size = size
comment where it is drawn on the right selection screen
set startpos = startpos
comment dimen... | import pygame, os, _thread, queue, socket, pickle
from tkinter import *
# battleship class
class Battleship:
def __init__(self,id,size,startpos):
self.id = id
# num of boxes length
self.size = size
# where it is drawn on the right selection screen
self.startpos = startpos
... | Python | zaydzuhri_stack_edu_python |
import sqlite3 as sql
comment sqlite_file = 'itech_tutor_program_db.sq'
set sqlite_file = string itech_tutor_program_db.sqlite
function find_daily_tutors
begin
print string checking...
comment # get current day using datetime, blah blah List of strings with weekday number
comment day = "tuesday"
comment find_tutor_quer... | import sqlite3 as sql
# sqlite_file = 'itech_tutor_program_db.sq'
sqlite_file = 'itech_tutor_program_db.sqlite'
def find_daily_tutors():
print("checking...")
# # get current day using datetime, blah blah List of strings with weekday number
# day = "tuesday"
# find_tutor_query = "SELECT name, courses,... | Python | zaydzuhri_stack_edu_python |
comment 수영장청소 final
comment 오후 3:34 2021-05-12
comment core contents ; consecutive move of BFS; bfs variation, with itertools.product
comment step of Main
comment 1. input and numbering the fauset and record the COORD to find certain fauset
comment 2. cleaned area by circular fauset
comment !! indexing the 4way directi... | # 수영장청소 final
# 오후 3:34 2021-05-12
# core contents ; consecutive move of BFS; bfs variation, with itertools.product
# step of Main
# 1. input and numbering the fauset and record the COORD to find certain fauset
# 2. cleaned area by circular fauset
# !! indexing the 4way direction as a standard and expansion with 4way... | Python | zaydzuhri_stack_edu_python |
function _add_missing_routes route_spec failed_ips chosen_routers vpc_info con routes_in_rts
begin
for tuple dcidr hosts in items route_spec
begin
set new_router_ip = get chosen_routers dcidr
comment Look at the routes we have seen in each of the route tables.
for tuple rt_id dcidr_list in items routes_in_rts
begin
if ... | def _add_missing_routes(route_spec, failed_ips, chosen_routers,
vpc_info, con, routes_in_rts):
for dcidr, hosts in route_spec.items():
new_router_ip = chosen_routers.get(dcidr)
# Look at the routes we have seen in each of the route tables.
for rt_id, dcidr_list in rou... | Python | nomic_cornstack_python_v1 |
function haveLessVisits self other
begin
if timer == none
begin
return false
end
else
if timer == none
begin
return true
end
else
begin
return timer < timer
end
end function | def haveLessVisits(self, other):
if self.timer == None:
return False
elif other.timer == None:
return True
else:
return self.timer<other.timer | Python | nomic_cornstack_python_v1 |
comment https://www.shiyanlou.com/courses/370/labs/1191/document
from PIL import Image
import argparse
function init_args
begin
set parser = call ArgumentParser
call add_argument string -i string --input
call add_argument string -w string --width type=int default=60
call add_argument string --height type=int default=60... | # https://www.shiyanlou.com/courses/370/labs/1191/document
from PIL import Image
import argparse
def init_args():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input')
parser.add_argument('-w', '--width', type=int, default=60)
parser.add_argument('--height', type=int, default=60)
parser.a... | Python | zaydzuhri_stack_edu_python |
function conv_bn_relu_forward x w b conv_param gamma beta bn_param
begin
set tuple a conv_cache = call conv_forward_fast x w b conv_param
set tuple bn bn_cache = call spatial_batchnorm_forward a gamma beta bn_param
set tuple out relu_cache = call relu_forward bn
set cache = tuple conv_cache bn_cache relu_cache
return t... | def conv_bn_relu_forward(x, w, b, conv_param, gamma, beta, bn_param):
a, conv_cache = conv_forward_fast(x, w, b, conv_param)
bn, bn_cache = spatial_batchnorm_forward(a, gamma, beta, bn_param)
out, relu_cache = relu_forward(bn)
cache = (conv_cache, bn_cache, relu_cache)
return out, cache | Python | nomic_cornstack_python_v1 |
function GetUserComments self request context
begin
call set_code UNIMPLEMENTED
call set_details string Method not implemented!
raise call NotImplementedError string Method not implemented!
end function | def GetUserComments(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Python | nomic_cornstack_python_v1 |
function test_missing_main_file self
begin
call assert_that call with_args string file-that-does-not-exist raises RuntimeError string File .* doesn't exist!
end function | def test_missing_main_file(self):
assert_that(calling(Loader.load).with_args('file-that-does-not-exist'),
raises(RuntimeError, "File .* doesn't exist!")) | Python | nomic_cornstack_python_v1 |
function put self dot
begin
assert is instance dot Dot
assert dot is none msg string Tile must be empty in put()!
set dot = dot
set tile = self
end function | def put(self, dot):
assert isinstance(dot, Dot)
assert self.dot is None, "Tile must be empty in put()!"
self.dot = dot
dot.tile = self | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string script that creates the State “California” with the City “San Francisco”... ...from the database hbtn_0e_100_usa:
if __name__ == string __main__
begin
from sys import argv
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from relationship_state import Base , State... | #!/usr/bin/python3
""" script that creates the State “California” with the City “San Francisco”...
...from the database hbtn_0e_100_usa: """
if __name__ == "__main__":
from sys import argv
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from relationship_state import Base, ... | Python | zaydzuhri_stack_edu_python |
function test_tree_intersection_error
begin
with raises AttributeError
begin
assert call tree_intersection 1 2
end
end function | def test_tree_intersection_error():
with pytest.raises(AttributeError):
assert tree_intersection(1, 2) | Python | nomic_cornstack_python_v1 |
from mylib import *
import pickle
comment @author Eirini Mitsopoulou
comment -------------------------------Run this file---------------------------------
function createGreek7
begin
set filename = string greek.txt
set filename2 = string greek7.txt
set inFile = open filename string r encoding=string UTF8
set outFile = ... | from mylib import *
import pickle
# @author Eirini Mitsopoulou
#-------------------------------Run this file---------------------------------
def createGreek7():
filename = "greek.txt"
filename2 = "greek7.txt"
inFile = open(filename, 'r',encoding='UTF8')
outFile = open(filename2, 'w',encoding='UTF8')... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Mar 22 12:54:44 2020 @author: imran
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score , recall_score
from sklearn.metrics import f... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 12:54:44 2020
@author: imran
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.metrics import precision_score, recall_score
from sklearn.metrics import f1_score
fr... | Python | zaydzuhri_stack_edu_python |
from ann import *
comment Defining layers
set l1 = call Layer list - 0.4 0.2 x_vector=list list 1 0 1 w_vector=list list 0.2 0.4 - 0.5 list - 0.3 0.1 0.2
set l2 = call Layer list 0.1 below_layer=l1 w_vector=list list - 0.3 - 0.2
comment Defining NeuralNetwork
set nnet = call Nnet
set layers = list l1 l2
set labels = li... | from ann import *
#Defining layers
l1 = Layer([-0.4,0.2], x_vector=[[1,0,1]], w_vector=[[0.2, 0.4, -0.5],[-0.3, 0.1, 0.2]])
l2 = Layer([0.1], below_layer=l1, w_vector=[[-0.3,-0.2]])
#Defining NeuralNetwork
nnet = Nnet()
nnet.layers=[l1,l2]
nnet.labels=[[1]]
#print l1.feed_forward()
nnet.begin(0.1) | Python | zaydzuhri_stack_edu_python |
from itertools import groupby
from datetime import datetime
function group groups
begin
string Groups all the documents according to the AccessionNumber. This is done as a post processing step, because Solr doesn't support sub grouping.
for g in groups at string groups
begin
set grouped = dict
for tuple key value in g... | from itertools import groupby
from datetime import datetime
def group(groups):
"""
Groups all the documents according to the AccessionNumber. This is done
as a post processing step, because Solr doesn't support sub grouping.
"""
for g in groups['groups']:
grouped = {}
for key, ... | Python | zaydzuhri_stack_edu_python |
comment Performs all aspects necessary for k-fold cross validation
set __author__ = string katie
set __date__ = string $Apr 10, 2017 2:33:19 PM$
from eeg_windowing import *
from dtw_dist import *
from extract_features import *
import knn
import random_forest
import svm
import svd as svd_classifier
import random
import ... | # Performs all aspects necessary for k-fold cross validation
__author__ = "katie"
__date__ = "$Apr 10, 2017 2:33:19 PM$"
from eeg_windowing import *
from dtw_dist import *
from extract_features import *
import knn
import random_forest
import svm
import svd as svd_classifier
import random
import numpy
# Partitions w... | Python | zaydzuhri_stack_edu_python |
function downsample_weighted D W downsampling=4 allow_trim=true
begin
if shape != shape
begin
raise call ValueError string Arrays D, W must have the same shape.
end
if ndim != 2
begin
raise call ValueError string Arrays D, W must be 2D.
end
if any W < 0
begin
raise call ValueError string Array W contains negative value... | def downsample_weighted(D, W, downsampling=4, allow_trim=True):
if D.shape != W.shape:
raise ValueError('Arrays D, W must have the same shape.')
if D.ndim != 2:
raise ValueError('Arrays D, W must be 2D.')
if np.any(W < 0):
raise ValueError('Array W contains negative values.')
WD ... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from datetime import datetime
from dateutil import parser
from dateutil.relativedelta import relativedelta
function clean_dates df
begin
set date = apply date lambda x -> parse parser x
set df = df at date < end_time ? date >= start_time
return df
end function
set end_time = call ... | import pandas as pd
import numpy as np
from datetime import datetime
from dateutil import parser
from dateutil.relativedelta import relativedelta
def clean_dates(df):
df.date = df.date.apply(lambda x: parser.parse(x))
df = df[(df.date < end_time) & (df.date >= start_time)]
return df
end_time = datetime(2... | Python | zaydzuhri_stack_edu_python |
import requests
set starUrl = string https://www.runoob.com/python/python-100-examples.html
set headers = dict string User-Agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
comment 请求入口地址,获取100个a链接的href
set response = decode content st... | import requests
starUrl = 'https://www.runoob.com/python/python-100-examples.html'
headers = {
"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"
}
#请求入口地址,获取100个a链接的href
response = requests.get(starUrl,headers = headers).c... | Python | zaydzuhri_stack_edu_python |
function has_grouping_policy self *params
begin
return call has_named_grouping_policy string g *params
end function | def has_grouping_policy(self, *params):
return self.has_named_grouping_policy("g", *params) | Python | nomic_cornstack_python_v1 |
from rdflib.plugins.sparql.parser import parseQuery
from rdflib.plugins.sparql.parserutils import CompValue , Variable
class Node
begin
function __init__ self name prefix isVariable
begin
set name = name
set prefix = prefix
set isVariable = isVariable
end function
function __str__ self
begin
set ret_str = string
comme... | from rdflib.plugins.sparql.parser import parseQuery
from rdflib.plugins.sparql.parserutils import CompValue, Variable
class Node:
def __init__(self,name,prefix,isVariable):
self.name = name
self.prefix = prefix
self.isVariable = isVariable
def __str__(self):
ret_str =... | Python | zaydzuhri_stack_edu_python |
while c > 0
begin
set b = b * 10 + c % 10
set c = c / 10
end | while c > 0:
b = b * 10 + c % 10
c = c / 10 | Python | zaydzuhri_stack_edu_python |
comment We will add in our new version of the homework
function max_tweet
begin
return input string What is the maximum number of characters permitted in twitter posts?
end function
function convert_int twitter_max
begin
return integer twitter_max
end function
function tweet
begin
return input string What would you lik... | # We will add in our new version of the homework
def max_tweet():
return input("What is the maximum number of characters permitted in twitter posts?\n")
def convert_int(twitter_max):
return int(twitter_max)
def tweet():
return input("What would you like to tweet?\n")
def tw_length(tweet):
return... | Python | zaydzuhri_stack_edu_python |
function test_honor_Min self
begin
set whitelist = list string KnownRVPlanetsUniverse
for mod in allmods
begin
if __name__ in whitelist
begin
continue
end
comment Test Min = None first
set obj = call instantiate_mod mod
if nPlans > 1
begin
assert true M0 at 0 != M0 at 1 string Initial M0 must be randomly set
end
commen... | def test_honor_Min(self):
whitelist = ["KnownRVPlanetsUniverse"]
for mod in self.allmods:
if mod.__name__ in whitelist:
continue
# Test Min = None first
obj = self.instantiate_mod(mod)
if obj.nPlans > 1:
self.assertTrue(
... | Python | nomic_cornstack_python_v1 |
if c % 1 > 0
begin
print integer c + 1
end
else
begin
print integer c
end | if c%1>0:
print(int(c+1))
else:
print(int(c))
| Python | zaydzuhri_stack_edu_python |
function flush_mod self
begin
string Flush all pending LDAP modifications.
for dn in __pending_mod_dn__
begin
try
begin
if __ro__
begin
for mod in __mod_queue__ at dn
begin
if mod at 0 == MOD_DELETE
begin
set mod_str = string DELETE
end
else
if mod at 0 == MOD_ADD
begin
set mod_str = string ADD
end
else
begin
set mod_s... | def flush_mod(self):
"""Flush all pending LDAP modifications."""
for dn in self.__pending_mod_dn__:
try:
if self.__ro__:
for mod in self.__mod_queue__[dn]:
if mod[0] == ldap.MOD_DELETE:
mod_str = "DELETE"... | Python | jtatman_500k |
function lookup self token
begin
pass
end function | def lookup(self, token):
pass | Python | nomic_cornstack_python_v1 |
from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.db.models import Sum , Avg
from collections import OrderedDict
from mysites.models import MySite , MySiteValues
class ListMySites extends ListView
begin
string List all my si... | from django.shortcuts import render
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.db.models import Sum, Avg
from collections import OrderedDict
from mysites.models import MySite, MySiteValues
class ListMySites(ListView):
'''
List all my sites
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from time import time
comment should have this soon
comment global_set_debug_level = 0
comment levle 0 print inside/outside function infromation
comment level 1 print run timing information
comment level 2 print basic parameters information from algrithm
comment level 3 print detailed paprameter info... | import numpy as np
from time import time
# should have this soon
#global_set_debug_level = 0
#levle 0 print inside/outside function infromation
#level 1 print run timing information
#level 2 print basic parameters information from algrithm
#level 3 print detailed paprameter information
#level 4 print warning, e.g. di... | Python | zaydzuhri_stack_edu_python |
class Zamestnanec
begin
function vybrat_dovolenou self pocet_dni
begin
if pocet_dni <= dny_dovolene
begin
set dny_dovolene = dny_dovolene - pocet_dni
return string Užij si to.
end
else
begin
return string To už je moc.
end
end function
function __str__ self
begin
return string Zaměstnanec se jmenuje { jmeno } a pracuje... | class Zamestnanec:
def vybrat_dovolenou(self, pocet_dni):
if pocet_dni <= self.dny_dovolene:
self.dny_dovolene = self.dny_dovolene - pocet_dni
return "Užij si to."
else:
return "To už je moc."
def __str__(self):
return f"Zaměstnanec se jmenuje {self.jm... | Python | zaydzuhri_stack_edu_python |
function add_gtf self gtf_line show_id=false
begin
if is instance gtf_line Transcript
begin
set gtf_line = deep copy gtf_line
if start < start
begin
set start = start
end
if end > end
begin
set end = end
end
set __transcripts__ at transcript = gtf_line
end
else
if feature in list string transcript string CDS
begin
if t... | def add_gtf(self, gtf_line, show_id: bool = False):
if isinstance(gtf_line, Transcript):
gtf_line = deepcopy(gtf_line)
if gtf_line.start < self.start:
gtf_line.start = self.start
if gtf_line.end > self.end:
gtf_line.end = self.end
... | Python | nomic_cornstack_python_v1 |
import flask
import importlib
from flask import request
set app = call Flask __name__
function show_Status status_code
begin
set status_code_mapping = dict 200 string ok ; 400 string parameters error ; 404 string Server not found
set msg = dict string status status_code ; string status_msg status_code_mapping at status... | import flask
import importlib
from flask import request
app = flask.Flask(__name__)
def show_Status(status_code):
status_code_mapping = {
200:"ok",
400:"parameters error",
404:"Server not found",
}
msg = {
"status": status_code,
"status_msg": status_code_mapping[st... | Python | zaydzuhri_stack_edu_python |
function get_normalized_direction self direction
begin
return round normal_joystick_slope * direction + normal_joystick_intercept 2
end function | def get_normalized_direction(self, direction):
return round(self.normal_joystick_slope * direction + self.normal_joystick_intercept, 2) | Python | nomic_cornstack_python_v1 |
string Load a pickled object using namespace of different module than the module the obj was first pickled with reference to i.e. reassign module from which to load objects.
import pickle
comment from code based on https://stackoverflow.com/a/40916570/9426242 already in notes
class ModuleSwapUnpickler extends Unpickler... | '''
Load a pickled object using namespace of different module than the
module the obj was first pickled with reference to i.e. reassign module from
which to load objects.
'''
import pickle
# from code based on https://stackoverflow.com/a/40916570/9426242 already in notes
class ModuleSwapUnpickler(pickle.Unpickler):
... | Python | zaydzuhri_stack_edu_python |
function path_comp_service self
begin
return _path_comp_service
end function | def path_comp_service(self) -> List[PathComputationService]:
return self._path_comp_service | Python | nomic_cornstack_python_v1 |
comment this function take list arguments
function print_two *args
begin
set tuple arg1 arg2 = args
end function | # this function take list arguments
def print_two(*args):
arg1, arg2 = args | Python | zaydzuhri_stack_edu_python |
for i in range 1 length array
begin
set maxProductUntilHere = max maxProductUntilHere maxProductUntilHere * array at i
comment print (maxPronductUntilHere)
set maxProduct = max maxProduct maxProductUntilHere
end
print maxProduct | for i in range(1, len(array)):
maxProductUntilHere = max(maxProductUntilHere, maxProductUntilHere * array[i])
# print (maxPronductUntilHere)
maxProduct = max(maxProduct, maxProductUntilHere)
print (maxProduct) | Python | zaydzuhri_stack_edu_python |
function gtest_add_use self
begin
if call testsDisabled
begin
return
end
set use = call to_list get attribute self string use list
if not USE_GTEST in use
begin
append use USE_GTEST
end
end function | def gtest_add_use(self):
if self.testsDisabled():
return
self.use = self.to_list(getattr(self, "use", []))
if not USE_GTEST in self.use:
self.use.append(USE_GTEST) | Python | nomic_cornstack_python_v1 |
function _set_all self red green blue
begin
call WriteValue list 6 1 red green blue tuple
end function | def _set_all(self, red, green, blue):
self.blinkt_iface.WriteValue([0x06, 0x01, red, green, blue], ()) | Python | nomic_cornstack_python_v1 |
function pipe self other_task
begin
string Add a pipe listener to the execution of this task. The output of this task is required to be an iterable. Each item in the iterable will be queued as the sole argument to an execution of the listener task. Can also be written as:: pipeline = task1 | task2
set _source = self
ap... | def pipe(self, other_task):
""" Add a pipe listener to the execution of this task. The
output of this task is required to be an iterable. Each item in
the iterable will be queued as the sole argument to an execution
of the listener task.
Can also be written as::
pip... | Python | jtatman_500k |
function __init__ self win
begin
comment draw the base shot of the launcher
set base = call Circle call Point 0 0 3
call setFill string red
call setOutline string red
call draw win
comment save the window and create initial angle and velocity
set win = win
set angle = call radians 45.0
set vel = 40.0
comment create ini... | def __init__(self, win):
# draw the base shot of the launcher
base = Circle(Point(0,0), 3)
base.setFill("red")
base.setOutline("red")
base.draw(win)
# save the window and create initial angle and velocity
self.win = win
self.angle = radians(45.0)... | Python | nomic_cornstack_python_v1 |
function gauss self
begin
string Get the magnetometer values as gauss for each axis as a tuple (x,y,z) :example: >>> sensor = HMC5883L(gw) >>> sensor.gauss() (16.56, 21.2888, 26.017599999999998)
set raw = call raw
set factors = dict 1370 0.73 ; 1090 0.92 ; 820 1.22 ; 660 1.52 ; 440 2.27 ; 390 2.56 ; 330 3.03 ; 230 4.35... | def gauss(self):
"""
Get the magnetometer values as gauss for each axis as a tuple (x,y,z)
:example:
>>> sensor = HMC5883L(gw)
>>> sensor.gauss()
(16.56, 21.2888, 26.017599999999998)
"""
raw = self.raw()
factors = {
1370: 0.73,
... | Python | jtatman_500k |
comment importing library
import matplotlib.pyplot as plt
comment creating the details of students
set student_name = list string Divya string Anil string Lokesh string Ramya string Lokesh
set student_marks = list 30 50 20 50 25
set marks_percentage = list 30 * 100 / 50 50 * 100 / 50 20 * 100 / 50 50 * 100 / 50 25 * 10... | #importing library
import matplotlib.pyplot as plt
#creating the details of students
student_name=["Divya","Anil","Lokesh","Ramya","Lokesh"]
student_marks=[30,50,20,50,25]
marks_percentage=[30*100/50,50*100/50,20*100/50,50*100/50,25*100/50]
#defining a function for line graph
def Line_chart_of_student_an... | Python | zaydzuhri_stack_edu_python |
import random
import string
import time
from tkinter import *
set Root = call Tk
call geometry string 400x400
title Root string Random Password Generator
call config bg=string darkgoldenrod
call resizable false false
set option_characters = string none
set option_numbers = string none
set option_length = 4
set title_la... | import random
import string
import time
from tkinter import *
Root = Tk()
Root.geometry("400x400")
Root.title("Random Password Generator")
Root.config(bg="darkgoldenrod")
Root.resizable(False, False)
option_characters = "none"
option_numbers = "none"
option_length = 4
title_label = Label(Root, text="P... | Python | zaydzuhri_stack_edu_python |
import urllib2
import json
from pprint import pprint
function get_page_data page_id access_token
begin
set api_endpoint = string https://graph.facebook.com/v2.8/search
set fb_graph_url = api_endpoint + string ?type=page&q=Smooning&fields=id,name&access_token= + access_token
end function | import urllib2
import json
from pprint import pprint
def get_page_data(page_id,access_token):
api_endpoint = "https://graph.facebook.com/v2.8/search"
fb_graph_url = api_endpoint+"?type=page&q=Smooning&fields=id,name&access_token="+access_token | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
class Recommender extends object
begin
function __init__ self
begin
set actions = none
set user_id_to_ind = none
set ind_to_user_id = none
set item_id_to_ind = none
set ind_to_item_id = none
end function
end class | import numpy as np
import pandas as pd
class Recommender(object):
def __init__(self):
self.actions = None
self.user_id_to_ind = None
self.ind_to_user_id = None
self.item_id_to_ind = None
self.ind_to_item_id = None
| Python | zaydzuhri_stack_edu_python |
function heatmap data row_labels col_labels ax=none cbar_kw=dict cbarlabel=string annotate=true **kwargs
begin
if not ax
begin
set ax = call gca
end
comment Plot the heatmap
set im = image show data keyword kwargs
comment Create colorbar
set cbar = call colorbar im ax=ax keyword cbar_kw
call set_ylabel cbarlabel rota... | def heatmap(data, row_labels, col_labels, ax=None,
cbar_kw={}, cbarlabel="", annotate=True, **kwargs):
if not ax:
ax = plt.gca()
# Plot the heatmap
im = ax.imshow(data, **kwargs)
# Create colorbar
cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)
cbar.ax.set_ylabel(cbarlabel... | Python | nomic_cornstack_python_v1 |
function check_if_odinakov s
begin
set sk = s at 0
for sym in s
begin
if sym == sk
begin
pass
end
else
begin
return 0
end
end
return 1
end function
for bin_num in nums
begin
set a = list bin_num
if call check_if_odinakov a
begin
set a at length a - 1 = string integer not boolean string a at length a - 1
append final jo... | def check_if_odinakov(s):
sk = s[0]
for sym in s:
if sym == sk:
pass
else:
return 0
return 1
for bin_num in nums:
a = list(bin_num)
if check_if_odinakov(a):
a[len(a)-1] = str(int(not bool(str(a[len(a)-1]))))
final.append("".join(a))
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import os
import sys
import json
from mutagen.mp4 import MP4
from mutagen.id3 import ID3
from mutagen.id3 import ID3NoHeaderError
from gmusicapi import Mobileclient
set EMAIL = string YOUR-EMAIL-HERE
set PASSWORD = string YOUR-PASSWORD-HERE
function remove_dups tracks
begin
set track_set = ... | #!/usr/bin/env python
import os
import sys
import json
from mutagen.mp4 import MP4
from mutagen.id3 import ID3
from mutagen.id3 import ID3NoHeaderError
from gmusicapi import Mobileclient
EMAIL = "YOUR-EMAIL-HERE"
PASSWORD = "YOUR-PASSWORD-HERE"
def remove_dups(tracks):
track_set = []
for track in tracks:
... | Python | zaydzuhri_stack_edu_python |
function __iter__ self
begin
set N = length all_paths
for tuple idx current_path in enumerate all_paths
begin
if verbose
begin
call fwrite string %d/%d % tuple idx N
flush stdout
end
for line in open current_path string r
begin
set L = decode line string utf-8
set sentences = split re string [.][^.] L
for s in sentence... | def __iter__(self):
N = len(self.all_paths)
for idx,current_path in enumerate(self.all_paths):
if self.verbose:
fwrite('%d/%d\r' % (idx, N))
sys.stdout.flush()
for line in open(current_path,'r'):
L = line.decode('utf-8')
... | Python | nomic_cornstack_python_v1 |
function login_token self token
begin
comment this will also set the refresh_token to None
set token = token
end function | def login_token(self, token):
self.token = token # this will also set the refresh_token to None | Python | nomic_cornstack_python_v1 |
class PriorityQueue
begin
function __init__ self n
begin
set q = list none * n
set head = 0
set tail = - 1
set elements = 0
end function
function put self x distances
begin
set tail = tail + 1
set elements = elements + 1
set q at tail = x
set i = tail
while i > head and distances at x at 0 < distances at q at i - 1 at ... | class PriorityQueue:
def __init__(self,n):
self.q=[None]*n
self.head=0
self.tail=-1
self.elements=0
def put(self,x,distances):
self.tail+=1
self.elements+=1
self.q[self.tail]=x
i=self.tail
while i>self.head and distances[x[0]]<di... | Python | zaydzuhri_stack_edu_python |
async function _brawlcord self ctx
begin
from brawlcord import __version__
set info = string Brawlcord is a Discord bot which allows users to simulate a simple version of [Brawl Stars]( { BRAWLSTARS } ), a mobile game developed by Supercell. Brawlcord has features such as interactive 1v1 Brawls, diverse Brawlers and le... | async def _brawlcord(self, ctx: Context):
from .brawlcord import __version__
info = (
"Brawlcord is a Discord bot which allows users to simulate"
f" a simple version of [Brawl Stars]({BRAWLSTARS}), a mobile"
f" game developed by Supercell. \n\nBrawlcord has features... | Python | nomic_cornstack_python_v1 |
function run_workflow workdir_path workflow_dict input_dict
begin
call normalise_workflow workflow_dict
log string Normalised workflow: + dumps workflow_dict indent=4
log string Input: + dumps input_dict indent=4
set has_error = false
while call has_unexecuted_steps workflow_dict and not has_error
begin
for step in wor... | def run_workflow(workdir_path, workflow_dict, input_dict):
normalise_workflow(workflow_dict)
log("Normalised workflow: " + json.dumps(workflow_dict, indent=4))
log("Input: " + json.dumps(input_dict, indent=4))
has_error = False
while has_unexecuted_steps(workflow_dict) and not has_error:
for... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import scrapy
from MyCrawler.items import MycrawlerItem
class JobtosuityouSpider extends Spider
begin
set name = string jobtosuityou
set allowed_domains = list string jobtosuityou.co.uk
set start_urls = tuple string http://www.jobtosuityou.co.uk/directory/Industry/IT_and_Computing
end clas... | # -*- coding: utf-8 -*-
import scrapy
from MyCrawler.items import MycrawlerItem
class JobtosuityouSpider(scrapy.Spider):
name = "jobtosuityou"
allowed_domains = ["jobtosuityou.co.uk"]
start_urls = (
#'http://www.jobtosuityou.co.uk/',
'http://www.jobtosuityou.co.uk/directory/Industry/IT_and_... | Python | zaydzuhri_stack_edu_python |
from decimal import Decimal
from metrics import pmt
from abc import WithdrawalStrategy
class VPW extends WithdrawalStrategy
begin
comment From the VPW spreadsheet. These are taken from
comment the Credit Suisse 2016 Global Returns Yearbook for global
comment stocks and global bonds historical rates from 1900-2015
set S... | from decimal import Decimal
from metrics import pmt
from .abc import WithdrawalStrategy
class VPW(WithdrawalStrategy):
# From the VPW spreadsheet. These are taken from
# the Credit Suisse 2016 Global Returns Yearbook for global
# stocks and global bonds historical rates from 1900-2015
STOCK_GROWTH_RATE... | Python | zaydzuhri_stack_edu_python |
function idf term index length
begin
try
begin
return log length / length index at lower term
end
except KeyError
begin
return 0
end
end function | def idf(term, index, length):
try:
return log(length/len(index[term.lower()]))
except KeyError:
return 0 | Python | nomic_cornstack_python_v1 |
for i in li1
begin
print i
end | for i in li1:
print(i)
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sat Apr 11 22:42:14 2020 @author: Zpaffled
from dim import bcnt
from fracgen import sierpinsky
from time import time
import numpy as np
import matplotlib.pyplot as ptl
function intersect seg x y
begin
comment in sierpinsk x1!=x2
set tuple tuple x1 y1 tuple x2 y2 = seg
if ... | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 22:42:14 2020
@author: Zpaffled
"""
from dim import bcnt
from fracgen import sierpinsky
from time import time
import numpy as np
import matplotlib.pyplot as ptl
def intersect(seg,x,y):
# in sierpinsk x1!=x2
(x1,y1),(x2,y2) = seg
if min... | Python | zaydzuhri_stack_edu_python |
function test_empty_version_string self
begin
assert equal call _convert_tpr string version string 0
end function | def test_empty_version_string(self):
self.assertEqual(selectors._convert_tpr(""), Version("0")) | Python | nomic_cornstack_python_v1 |
function test_registration_with_all_information self
begin
set response = post reverse string aiuts:create_acc dict string fullname string Testing01 ; string password string Asd,car15 follow=true
assert equal status_code 200
call assertContains response string afe600a43cea6bdaf6c362905db6b883 has been created!
end func... | def test_registration_with_all_information(self):
response = self.client.post(reverse('aiuts:create_acc'), {"fullname": "Testing01", "password": "Asd,car15"}, follow=True)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "afe600a43cea6bdaf6c362905db6b883 has been created... | Python | nomic_cornstack_python_v1 |
function schmidt_quasi_normalisation max_n
begin
set schmidt = call _gen_2d_array max_n max_n 0.0
for n in range max_n
begin
for m in range n + 1
begin
if n == 0
begin
comment This is a bit of a hack to get round 2n-1 evaluating to
comment -1 and erroring when it should be returning 1
set double_fact = 1.0
end
else
beg... | def schmidt_quasi_normalisation(max_n):
schmidt = _gen_2d_array(max_n, max_n, 0.0)
for n in range(max_n):
for m in range(n + 1):
if n == 0:
# This is a bit of a hack to get round 2n-1 evaluating to
# -1 and erroring when it should be returning 1
... | Python | nomic_cornstack_python_v1 |
function exists self name
begin
return name in cache
end function | def exists(self, name):
return name in self.cache | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
string @author: Lena Schiffer This is the Parsing module. It contains function to download and parse a HTML-Source of an AGB into strict XML.
import sys
import os.path
import logging
import sqlite3 as lite
from urllib.request import urlopen
from urllib.error import HTTPError , URLError
from soc... | #!/usr/bin/python
"""
@author: Lena Schiffer
This is the Parsing module. It contains function to download and parse a HTML-Source of an AGB into strict XML.
"""
import sys
import os.path
import logging
import sqlite3 as lite
from urllib.request import urlopen
from urllib.error import HTTPError, URLError
from s... | Python | zaydzuhri_stack_edu_python |
function main tetrode_number=TETRODE_NUMBER num_hidden_units=300 num_hidden_units_2=200 num_code_units=50
begin
print string Loading the data...
set dataset = call load_data tetrode_number
print string Done!
print format string Tetrode number: {}, Num outputs: {} tetrode_number dataset at string output_dim
print datase... | def main(tetrode_number=TETRODE_NUMBER,num_hidden_units=300,num_hidden_units_2=200,num_code_units=50):
print("Loading the data...")
dataset = load_data(tetrode_number)
print("Done!")
print("Tetrode number: {}, Num outputs: {}".format(tetrode_number,dataset['output_dim']))
print(dataset['input_shap... | Python | nomic_cornstack_python_v1 |
import cv2
import math
import numpy as np
comment from shapely.geometry import Polygon
class Maze
begin
function __init__ self filename scale
begin
comment instatiates an object of class maze
set filename = filename
set scale = scale
call read_obstacles
set image = zeros tuple height * scale width * scale 3 uint8
set m... | import cv2
import math
import numpy as np
# from shapely.geometry import Polygon
class Maze:
def __init__(self,filename,scale):
# instatiates an object of class maze
self.filename = filename
self.scale = scale
self.read_obstacles()
self.image = np.zeros((self.heigh... | Python | zaydzuhri_stack_edu_python |
import nltk
from nltk.tokenize import word_tokenize
import string
function preprocess_text paragraph
begin
comment Convert to lowercase
set paragraph = lower paragraph
comment Remove punctuation marks
set paragraph = call translate call maketrans string string punctuation
comment Tokenize the paragraph
set tokens = c... | import nltk
from nltk.tokenize import word_tokenize
import string
def preprocess_text(paragraph):
# Convert to lowercase
paragraph = paragraph.lower()
# Remove punctuation marks
paragraph = paragraph.translate(str.maketrans('', '', string.punctuation))
# Tokenize the paragraph
tokens... | Python | jtatman_500k |
function prepare_jobs batch_iterator model_params schema_params num_features model_weights enable_local_indexing job_queue has_intercept
begin
info string Kicking off job producer with enable_local_indexing = { enable_local_indexing } .
for tuple features_val labels_val in call dataset_reader call batch_iterator
begin
... | def prepare_jobs(batch_iterator, model_params, schema_params, num_features, model_weights: dict,
enable_local_indexing: bool, job_queue: BaseProxy, has_intercept: bool):
logger.info(f"Kicking off job producer with enable_local_indexing = {enable_local_indexing}.")
for features_val, labels_val i... | Python | nomic_cornstack_python_v1 |
import socket
import pickle
import data_collection_client
function main_client
begin
set host = string 10.42.43.1
set port = 65432
set sock = call socket AF_INET SOCK_STREAM
try
begin
call connect tuple host port
print string [LOG] Connected to: { host }
while true
begin
set data = call recv 4096
if not data
begin
brea... | import socket
import pickle
import data_collection_client
def main_client():
host = '10.42.43.1'
port = 65432
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
print(f'[LOG] Connected to: {host}')
while True:
... | Python | zaydzuhri_stack_edu_python |
function mkccj_create_parser prog
begin
set parser = call ArgumentParser prog=prog description=string Produce a JSON format compilation database from a text build log
call add_argument string input_file help=string Input text filename
call add_argument string -c dest=string compiler help=string name of compiler, used t... | def mkccj_create_parser(prog):
parser = argparse.ArgumentParser(prog=prog, description="Produce a JSON format compilation database from a text build log")
parser.add_argument('input_file', help='Input text filename')
parser.add_argument('-c', dest='compiler', help='name of compiler, used to recogn... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment coding=utf-8
import random
from weixin.utils.httpclient import HttpClient
from weixin.settings import LOGGER
class TuringClient extends object
begin
set API_KEY = list string 14c218cb6cb23bb27b7dc89e18eb9689
set _HTTP_CLIENT = none
set URL = string http://openapi.tuling123.com/openapi/a... | #!/usr/bin/python
# coding=utf-8
import random
from weixin.utils.httpclient import HttpClient
from weixin.settings import LOGGER
class TuringClient(object):
API_KEY = ['14c218cb6cb23bb27b7dc89e18eb9689']
_HTTP_CLIENT = None
URL = 'http://openapi.tuling123.com/openapi/api/v2'
DEFAULT_UID = '14c218cb6... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sat Feb 15 14:48:11 2020 @author: 666292 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 15 14:48:11 2020
@author: 666292
"""
| Python | zaydzuhri_stack_edu_python |
function pause self
begin
if is_playing
begin
set is_playing = false
set pause_time = time
if call is_playing == 1
begin
call pause
end
end
end function | def pause(self):
if self.is_playing:
self.is_playing = False
self.pause_time = time.time()
if self.player.is_playing() == 1:
self.player.pause() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
from pwn import *
from dateutil import parser
import datetime , time
import getpass
comment Choose a file
set value = 0
while value not in list 6 7 8
begin
try
begin
set value = integer input string Which binary do you want to exploit? 133[6,7,8]:
if value not in list 6 7 8
begin
print string ... | #!/usr/bin/python3
from pwn import *
from dateutil import parser
import datetime, time
import getpass
# Choose a file
value = 0
while value not in [6,7,8]:
try:
value = int(input("Which binary do you want to exploit? 133[6,7,8]: "))
if value not in [6,7,8]:
print("Value not in [6,7... | Python | zaydzuhri_stack_edu_python |
comment def a():
comment print("helllow")
comment a()
comment concatenate string
function a name=string nirpesh
begin
print string hellow + name
end function
call a | #def a():
# print("helllow")
# a()
#concatenate string
def a(name="nirpesh"):
print("hellow"+name)
a()
| Python | zaydzuhri_stack_edu_python |
function cache prefix=none key=none expires_in=3600
begin
function _decorator func
begin
decorator coroutine
decorator wraps func
function _wrapper *args **kwargs
begin
set cached_key = call _get_cached_key func args kwargs prefix key
set data = get call get_redis_client cached_key
if data
begin
debug string get cached... | def cache(prefix = None, key = None, expires_in = 3600):
def _decorator(func):
@coroutine
@wraps(func)
def _wrapper(*args, **kwargs):
cached_key = _get_cached_key(func, args, kwargs, prefix, key)
data = get_redis_client().get(cached_key)
i... | Python | nomic_cornstack_python_v1 |
function drawFace self position
begin
set x = position at 0
set y = position at 1
call circle surface tuple 255 0 0 position 50 0
call circle surface tuple 0 0 255 tuple x - 25 y - 18 10 0
call circle surface tuple 0 255 0 tuple x + 25 y - 18 10 0
call polygon surface tuple 255 255 255 tuple tuple x y - 5 tuple x + 10 ... | def drawFace(self, position):
x = position[0]
y = position[1]
pygame.draw.circle(self.surface, (255, 0, 0), (position), 50, 0)
pygame.draw.circle(self.surface, (0, 0, 255), (x-25, y-18), 10, 0)
pygame.draw.circle(self.surface, (0, 255, 0), (x+25, y-18), 10, 0)
pygame.draw... | Python | nomic_cornstack_python_v1 |
for _ in range integer input
begin
set tuple command *params = split input
if command == string print
begin
print lst
end
else
if command == string insert
begin
insert lst integer params at 0 integer params at 1
end
else
if command == string remove
begin
remove lst integer params at 0
end
else
if command == string pop
... | for _ in range(int(input())):
command, *params = input().split()
if command == "print":
print(lst)
elif command == "insert":
lst.insert(int(params[0]), int(params[1]))
elif command == "remove":
lst.remove(int(params[0]))
elif command == "pop":
lst.pop(len(lst)-1)
... | Python | zaydzuhri_stack_edu_python |
function test_fetch_system_panel_200 self
begin
set response = get app string /api/admin/system
set res = decode data string ASCII
set res = loads res
assert equal status_code 200
assert equal res at string message string Data fetched successfully!
assert true is instance res at string data dict
end function | def test_fetch_system_panel_200(self):
response = self.app.get("/api/admin/system")
res = response.data.decode("ASCII")
res = json.loads(res)
self.assertEqual(response.status_code, 200)
self.assertEqual(res["message"], "Data fetched successfully!")
self.assertTrue(i... | Python | nomic_cornstack_python_v1 |
function product a b
begin
string >>> product(3,2) 6 >>> product(0,2) 0 >>> product(2,2) 2
return a * b
end function | def product(a,b):
"""
>>> product(3,2)
6
>>> product(0,2)
0
>>> product(2,2)
2
"""
return a * b | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
function compute_optical_flow image1 image2
begin
set prvs = call cvtColor image1 COLOR_BGR2GRAY
set hsv = zeros like image1
set hsv at tuple Ellipsis 1 = 255
set next = call cvtColor image2 COLOR_BGR2GRAY
set flow = call calcOpticalFlowFarneback prvs next none 0.5 3 15 3 5 1.2 0
set tuple... | import cv2
import numpy as np
def compute_optical_flow(image1, image2):
prvs = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
hsv = np.zeros_like(image1)
hsv[..., 1] = 255
next = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
flow = cv2.calcOpticalFlowFarneback(prvs, next, None, 0.5, 3, 15, 3, 5, 1.2, 0)
... | Python | zaydzuhri_stack_edu_python |
function tick self
begin
comment Get new comments from /r/all
print string Retrieving comments... end=string
set comments = list call get_comments string all limit=none
print string [DONE]
set comment_count = call __len__
print string Comments to read: + string comment_count
for i in range 0 comment_count
begin
set com... | def tick(self):
# Get new comments from /r/all
print('\n\nRetrieving comments...', end="")
comments = list(self.reddit.get_comments('all', limit=None))
print('[DONE]')
comment_count = comments.__len__()
print('Comments to read: ' + str(comment_count))
for i in r... | Python | nomic_cornstack_python_v1 |
function describe_element name df normal=false text=false color=false
begin
set property_formats = dict string f string float ; string u string uchar ; string i string int
set element = list string element + name + string + string length df
if name == string face
begin
append element string property list uchar int ver... | def describe_element(name, df, normal=False, text = False, color=False):
property_formats = {'f': 'float', 'u': 'uchar', 'i': 'int'}
element = ['element ' + name + ' ' + str(len(df))]
if name == 'face':
element.append("property list uchar int vertex_indices")
else:
element.append('prop... | Python | nomic_cornstack_python_v1 |
comment reading
set fp = open string hello.txt string r
set t = read fp
print t
close fp | # reading
fp=open("hello.txt","r")
t=fp.read()
print(t)
fp.close() | Python | zaydzuhri_stack_edu_python |
function string_na_clean_list string
begin
set txt = call splitlines
set t = list
for i in txt
begin
set a = strip i
if a is not string
begin
append t strip i
end
end
return t
end function
function wyklucz_z_listy set_ex list_txt
begin
return list comprehension i for i in list_txt if i not in set_ex or i not in list_... | def string_na_clean_list(string):
txt = string.splitlines()
t = []
for i in txt:
a = i.strip()
if a is not '':
t.append(i.strip())
return t
def wyklucz_z_listy(set_ex, list_txt):
return [i for i in list_txt if i not in set_ex or i not in list_txt] | Python | zaydzuhri_stack_edu_python |
function _build_rnn self input_tensor
begin
set w_trainable = false
set x_shift_trainable = false
set eta_trainable = true
set input_shape = call as_list
set input_area = call prod input_shape at slice 1 : :
set batch_input_shape = tuple - 1 input_area
set filters = filters + bias_neurons
set hidden_size = list filter... | def _build_rnn(self, input_tensor):
w_trainable = False
x_shift_trainable = False
eta_trainable = True
input_shape = input_tensor.get_shape().as_list()
input_area = np.prod(input_shape[1:])
batch_input_shape = (-1, input_area)
filters = self._hparams.filters + self._hparams.bias_neurons
... | Python | nomic_cornstack_python_v1 |
function backend_model self backend_model
begin
set _backend_model = backend_model
end function | def backend_model(self, backend_model):
self._backend_model = backend_model | Python | nomic_cornstack_python_v1 |
from Tkinter import *
set root = call Tk
title root string Project#2
set user_input = call StringVar
set user_input_copy = call StringVar
set label = grid row=0 column=0
set inputVar = grid row=1 column=0
function submit
begin
import urllib.request , re
set infile = open string icd10cm.txt string r
set regexp = compile... | from Tkinter import *
root = Tk()
root.title("Project#2")
user_input = StringVar()
user_input_copy = StringVar()
label = Label(root, text="Please Enter a Code").grid(row=0, column=0)
inputVar = Entry(root, textvariable=user_input).grid(row=1, column=0)
def submit():
import urllib.request, re
infile =... | Python | zaydzuhri_stack_edu_python |
string * user: VR424867 * fname: CONSOLARO * lname: GIANPIETRO * task: bit_edit_to_zero * score: 0.0 * date: 2019-02-26 09:47:43.672702
function lsp n
begin
return n ? - n
end function
function potenza_2 n
begin
return n == call lsp n
end function
function nmosse_p_2 n
begin
assert call potenza_2 n
return 2 * n - 1
end... | """
* user: VR424867
* fname: CONSOLARO
* lname: GIANPIETRO
* task: bit_edit_to_zero
* score: 0.0
* date: 2019-02-26 09:47:43.672702
"""
def lsp(n):
return n & (-n)
def potenza_2(n):
return n == lsp(n)
def nmosse_p_2(n):
assert potenza_2(n)
return 2*n-1
def numero_uni(n):
if n == 0:
re... | Python | zaydzuhri_stack_edu_python |
function scrape_wiki_page line knowledgeProcessor freqDict corrDict
begin
comment number of days since June 29 2019 when page was loaded
set loadDate = integer time / 86400 - 18076
comment get everything after the first comma
set commaLoc = find line string ,
set rawText = line at slice commaLoc + 2 : :
comment pull ... | def scrape_wiki_page(line, knowledgeProcessor, freqDict, corrDict):
# number of days since June 29 2019 when page was loaded
loadDate = int(time() / (86400)) - 18076
# get everything after the first comma
commaLoc = line.find(',')
rawText = line[(commaLoc+2):]
# pull out the title
titleEnd =... | 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.