code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function replace_user_data self new_data
begin
set _user_data = new_data
end function | def replace_user_data(self, new_data):
self._user_data = new_data | Python | nomic_cornstack_python_v1 |
function test_conform_method_will_set_the_version_extension test_data
begin
assert extension != string .ztl
set external_env = call ExternalDCC name=string ZBrush extensions=list string .ztl
call conform test_data at string version
assert extension == string .ztl
end function | def test_conform_method_will_set_the_version_extension(test_data):
assert test_data["version"].extension != ".ztl"
external_env = ExternalDCC(name="ZBrush", extensions=[".ztl"])
external_env.conform(test_data["version"])
assert test_data["version"].extension == ".ztl" | Python | nomic_cornstack_python_v1 |
function posOfRightMostDiffBit m n
begin
comment Your code here
set i = 1
set p = 1
if m == n
begin
print - 1
end
while true
begin
set x = m ? i
set y = n ? i
if x ? y == 0
begin
set i = i ? 1
set p = p + 1
continue
end
else
begin
return p
end
end
end function | def posOfRightMostDiffBit(m,n):
#Your code here
i=1
p=1
if m==n:
print(-1)
while True:
x=m&i
y=n&i
if x^y==0:
i=i<<1
p+=1
continue
else:
return p
| Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function countGoodTriplets self arr a b c
begin
string :type arr: List[int] :type a: int :type b: int :type c: int :rtype: int
set n = length arr
set z = 0
for i in call xrange n
begin
for j in call xrange i + 1 n
begin
if absolute arr at i - arr at j > a
begin
continue
end
for k in ... | class Solution(object):
def countGoodTriplets(self, arr, a, b, c):
"""
:type arr: List[int]
:type a: int
:type b: int
:type c: int
:rtype: int
"""
n = len(arr)
z = 0
for i in xrange(n):
for j in xrange(i+1, n):
... | Python | zaydzuhri_stack_edu_python |
comment Date: 8th Jan, 2019
comment Author: Tian Lin
comment Email: lint17@fudan.edu.cn
comment newest modification: 13th Jan, 2019
import tensorflow as tf
comment debugging with dynamic graph
call enable_eager_execution
comment load the samples generated by MATLAB
from BFNN.load_samples import *
comment the basic cons... | # Date: 8th Jan, 2019
# Author: Tian Lin
# Email: lint17@fudan.edu.cn
# newest modification: 13th Jan, 2019
import tensorflow as tf
tf.enable_eager_execution() # debugging with dynamic graph
from BFNN.load_samples import * # load the samples generated by MATLAB
from BFNN.BFNN_Model import * # the basic constructi... | Python | zaydzuhri_stack_edu_python |
function binario n bin
begin
if n == 0
begin
return bin
end
append bin n % 2
if n != 0
begin
return call binario n // 2 bin
end
end function
set lista = list
set n = integer input
if n == 0
begin
print n
end
else
begin
set num_binario = call binario n lista
for x in range length num_binario - 1 - 1 - 1
begin
print num... | def binario(n, bin):
if n == 0:
return bin
bin.append(n % 2)
if n != 0:
return binario(n // 2, bin)
lista = []
n = int(input())
if n == 0:
print(n)
else:
num_binario = binario(n, lista)
for x in range(len(num_binario) - 1, -1, -1):
print(num_binario[x]) | Python | zaydzuhri_stack_edu_python |
function test_get_queued self
begin
set kwargs = dict string to string to@example.com ; string from_email string bob@example.com ; string subject string Test ; string message string Message
assert equal list call get_queued list
comment Emails with statuses failed, sent or None shouldn't be returned
call create status=... | def test_get_queued(self):
kwargs = {
'to': 'to@example.com',
'from_email': 'bob@example.com',
'subject': 'Test',
'message': 'Message',
}
self.assertEqual(list(get_queued()), [])
# Emails with statuses failed, sent or None shouldn't be ret... | Python | nomic_cornstack_python_v1 |
comment Digital OCEAN FLASK SERVER RECEIVES IMAGE
from flask import Flask , request , jsonify
import classify
import base64
import json
import firebase
import env
comment Instantiate Flask
set app = call Flask __name__
decorator call route string /status
comment health check
function health_check
begin
return string Ru... | # Digital OCEAN FLASK SERVER RECEIVES IMAGE
from flask import Flask, request, jsonify
import classify
import base64
import json
import firebase
import env
# Instantiate Flask
app = Flask(__name__)
# health check
@app.route("/status")
def health_check():
return "Running!"
# Performing image Recognition on Image... | Python | jtatman_500k |
function ks_categories_json_data self all_categories wcapi
begin
set woo_category = list
if all_categories
begin
for each_category in all_categories
begin
set category_data = call _prepare_odoo_product_category_data each_category
if ks_woo_id
begin
set record_exist_status = get wcapi string products/categories/%s % ks... | def ks_categories_json_data(self, all_categories, wcapi):
woo_category = []
if all_categories:
for each_category in all_categories:
category_data = self.env['product.category']._prepare_odoo_product_category_data(each_category)
if each_category.ks_woo_id:
... | Python | nomic_cornstack_python_v1 |
function isprime x
begin
for divisor in range 2 integer x ^ 0.5 + 1
begin
if x / divisor == integer x / divisor
begin
return false
end
end
return true
end function | def isprime(x):
for divisor in range(2, int(x**0.5)+1):
if x / divisor == int(x / divisor):
return False
return True | Python | nomic_cornstack_python_v1 |
function outside self region
begin
set fs = call FeatureSet
for f in self
begin
if call isNotContainedWithin region
begin
append fs f
end
end
return fs
end function | def outside(self,region):
fs = FeatureSet()
for f in self:
if(f.isNotContainedWithin(region)):
fs.append(f)
return fs | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python3
string processData.py This module reads people data from a JSON file and determines number of people alive per year and per decade. This is written in Python 3. The data it creates won't have the correct form if compiled in Python 2.
import os
import csv
import json
class DataProcessor
be... | #! /usr/bin/env python3
"""
processData.py
This module reads people data from a JSON file and determines
number of people alive per year and per decade.
This is written in Python 3. The data it creates won't have the correct
form if compiled in Python 2.
"""
import os
import csv
import json
class DataProcessor():
... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
string C. Крестики-нолики ограничение по времени на тест:1 second ограничение по памяти на тест:64 megabytes ввод:standard input вывод:standard output Все, наверное, знакомы с игрой крестики-нолики. Правила в самом деле очень просты. Игроки по очереди ставят на свободные клетки поля 3 × 3 знаки (од... | # coding=utf-8
"""
C. Крестики-нолики
ограничение по времени на тест:1 second
ограничение по памяти на тест:64 megabytes
ввод:standard input
вывод:standard output
Все, наверное, знакомы с игрой крестики-нолики. Правила в самом деле очень просты. Игроки по очереди ставят на свободные клетки поля 3 × 3 знаки (один всегд... | Python | zaydzuhri_stack_edu_python |
set tuple A B = generator expression integer T for T in split input
print A + B % 24 | A,B = (int(T) for T in input().split())
print((A+B)%24) | Python | zaydzuhri_stack_edu_python |
function move self
begin
set new_x = call getX + speed at 0
set new_y = call getY + speed at 1
call setX new_x
call setY new_y
end function | def move(self) -> None:
new_x = self.getX() + self.speed[0]
new_y = self.getY() + self.speed[1]
self.setX(new_x)
self.setY(new_y) | Python | nomic_cornstack_python_v1 |
from multiprocessing import Process
import time
class MyProcess extends Process
begin
function __init__ self n
begin
call __init__
set n = n
end function
function fun1 self
begin
for i in range n
begin
print string 子进程在做事
sleep 1
end
end function
comment 重写run方法,父类中对此方法做了自动化处理,如果换了方法就找不到了
function run self
begin
call f... | from multiprocessing import Process
import time
class MyProcess(Process):
def __init__(self,n):
super().__init__()
self.n = n
def fun1(self):
for i in range(self.n):
print("子进程在做事")
time.sleep(1)
#重写run方法,父类中对此方法做了自动化处理,如果换了方法就找不到了
def run(self):
... | Python | zaydzuhri_stack_edu_python |
from data_structure import print_all_friends , print_all_friends_and_closeness
set name_list = list string Summer string John string Justin string Mike string May string Kim string Tom string Jerry
set fr_info = dict string Summer list name_list at 1 name_list at 2 name_list at 3 ; string John list name_list at 0 name_... | from data_structure import print_all_friends, print_all_friends_and_closeness
name_list = ['Summer' , 'John', 'Justin', 'Mike', 'May', 'Kim', 'Tom', 'Jerry']
fr_info = {'Summer': [name_list[1],name_list[2],name_list[3]], 'John':[name_list[0],name_list[3]], 'Justin':[name_list[1],name_list[0],name_list[3],name_list[4]]... | Python | zaydzuhri_stack_edu_python |
function mde simulated_array observed_array replace_nan=none replace_inf=none remove_neg=false remove_zero=false
begin
comment Checking and cleaning the data
set tuple simulated_array observed_array = call treat_values simulated_array observed_array replace_nan=replace_nan replace_inf=replace_inf remove_neg=remove_neg ... | def mde(simulated_array, observed_array, replace_nan=None, replace_inf=None,
remove_neg=False, remove_zero=False):
# Checking and cleaning the data
simulated_array, observed_array = treat_values(
simulated_array,
observed_array,
replace_nan=replace_nan,
replace_inf=... | Python | nomic_cornstack_python_v1 |
from random import randint
from agent import Villager , Role , Faction
class Mayor extends Villager
begin
function __init__ self unique_id model interactions=false
begin
call __init__ unique_id model MAYOR interactions VILLAGER
set revealed = false
end function
comment Reveal yourself as the mayor to the townspeople.
f... | from random import randint
from .agent import Villager, Role, Faction
class Mayor(Villager):
def __init__(self, unique_id, model, interactions=False):
super().__init__(unique_id, model, Role.MAYOR, interactions, Faction.VILLAGER)
self.revealed = False
# Reveal yourself as the mayor to the to... | Python | zaydzuhri_stack_edu_python |
function get_skeleton_path self
begin
set skeleton_path = get settings string tsdb_skeleton_dir
if not skeleton_path or skeleton_path == string
begin
set testsuite_path = call file_name
set skeleton_path = join string / split testsuite_path string / at slice : - 1 :
end
if not skeleton_path at - 1 == string /
begin
s... | def get_skeleton_path(self):
skeleton_path = self.settings.get('tsdb_skeleton_dir')
if not skeleton_path or skeleton_path == '':
testsuite_path = self.view.file_name()
skeleton_path = '/'.join(testsuite_path.split('/')[:-1])
if not skeleton_path[-1] == '/':
... | Python | nomic_cornstack_python_v1 |
comment ===============================================================================
comment Project Euler - #1
comment If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
comment Find the sum of all the multiples of 3 or 5 below 1000.
com... | #===============================================================================
# Project Euler - #1
#
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
#
# Hüseyin KELEŞ - a... | Python | zaydzuhri_stack_edu_python |
function apply_commission price is_buying=true
begin
set rate = 1 + if expression is_buying then 1 else - 1 * COMMISSION_RATE
return price * rate
end function | def apply_commission(price: float, is_buying: bool = True):
rate = 1 + (1 if is_buying else -1) * settings.COMMISSION_RATE
return price * rate | Python | nomic_cornstack_python_v1 |
if name is string rafaiy
begin
print string hello rafaiy abdul rehman
end
else
if name is string any
begin
print string hii any
end
else
begin
print string hello there
end | if name is 'rafaiy':
print("hello rafaiy abdul rehman")
elif name is 'any':
print('hii any')
else :
print("hello there ") | Python | zaydzuhri_stack_edu_python |
from keras.datasets import mnist
import numpy as np
from PIL import Image
function invert_pixels img
begin
set result = copy np img
set tuple n m = shape
for i in range m
begin
for j in range m
begin
if result at i at j == 0
begin
set result at i at j = 1
end
else
begin
set result at i at j = - 1
end
end
end
return res... | from keras.datasets import mnist
import numpy as np
from PIL import Image
def invert_pixels(img):
result = np.copy(img)
(n, m) = img.shape
for i in range(m):
for j in range(m):
if result[i][j] == 0:
result[i][j] = 1
else:
result[i][j] = -1
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @Author: LC
comment @Date: 2016-06-20 23:14:57
comment @Last modified by: WuLC
comment @Last Modified time: 2016-06-20 23:15:29
comment @Email: liangchaowu5@gmail.com
class Solution extends object
begin
function reverseWords self s
begin
string :type s: str :rtype: str
set words = ... | # -*- coding: utf-8 -*-
# @Author: LC
# @Date: 2016-06-20 23:14:57
# @Last modified by: WuLC
# @Last Modified time: 2016-06-20 23:15:29
# @Email: liangchaowu5@gmail.com
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
words = s.split()
... | Python | zaydzuhri_stack_edu_python |
function get_statuses self
begin
raise call NotImplementedError
end function | def get_statuses(self):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function plot_transfer_effect self port
begin
if is instance port str
begin
set orig_port = port
set port = call find_port port
if port is none
begin
raise call ValueError string Unable to associate port with port name ' { orig_port } '
end
end
set transfer_trainings = call load_trainings port output_dir=output_dir rou... | def plot_transfer_effect(self, port: Union[str, Port]) -> None:
if isinstance(port, str):
orig_port = port
port = self.pm.find_port(port)
if port is None:
raise ValueError(f"Unable to associate port with port name '{orig_port}'")
transfer_trainings = s... | Python | nomic_cornstack_python_v1 |
function test_no_next_token self
begin
set response1 = dict string meta dict string result_count 500
set wk = directory name path absolute path path __file__
set f = join path wk string search_tweets.config
set thing = call SearchTweets db f
with call object thing string _SearchTweets__twitter_n_results new_callable=ca... | def test_no_next_token(self):
response1 = {'meta': {'result_count': 500}}
wk = os.path.dirname(os.path.abspath(__file__))
f = os.path.join(wk, "search_tweets.config")
thing = SearchTweets(self.db, f)
with patch.object(thing, '_SearchTweets__twitter_n_results', new_callable=Prope... | Python | nomic_cornstack_python_v1 |
class Employee
begin
set raise_amt = 1.05
function __init__ self first last pay
begin
set first = first
set last = last
set fullname = first + string + last
set pay = pay
end function
function pay_amt self
begin
return pay * raise_amt
end function
end class
comment inheritance
class Devloper extends Employee
begin
set... | class Employee:
raise_amt=1.05
def __init__(self,first,last,pay):
self.first=first
self.last=last
self.fullname=first+" "+last
self.pay=pay
def pay_amt(self):
return self.pay * self.raise_amt
class Devloper(Employee): #inheritance
raise_amt = 1.10
def __in... | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ rule ranges=none
begin
set __self__ string rule rule
if ranges is not none
begin
set __self__ string ranges ranges
end
end function | def __init__(__self__, *,
rule: pulumi.Input[str],
ranges: Optional[pulumi.Input[Sequence[pulumi.Input['IDRangeArgs']]]] = None):
pulumi.set(__self__, "rule", rule)
if ranges is not None:
pulumi.set(__self__, "ranges", ranges) | Python | nomic_cornstack_python_v1 |
function logout self
begin
pass
end function | def logout(self):
pass | Python | nomic_cornstack_python_v1 |
import numpy as np
set a1 = reshape array range 15 3 5
for eachCell in flatten a1
begin
print eachCell
end
set a2 = reshape array range 4 2 2
comment Fortran Order
string [[0 1] [2 3]] 0 2 1 3
print a2
for i in call nditer a2 order=string F
begin
print i
end
comment C order - Same as flatten
string [[0 1] [2 3]] 0 1 2 ... | import numpy as np
a1 = np.arange(15).reshape(3,5)
for eachCell in a1.flatten():
print(eachCell)
a2 = np.arange(4).reshape(2,2)
#Fortran Order
'''
[[0 1]
[2 3]]
0
2
1
3
'''
print(a2)
for i in np.nditer(a2,order='F'):
print(i)
#C order - Same as flatten
'''
[[0 1]
[2 3]]
0
1
2
3
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import folium , time
string SCREENING CENTERS IN PUBLIC ACCESS
function clean_public_centers depis_grand_public
begin
string We clean and complete the dataframe 'depis_grand_public' by adding missing informations. We add a column who indicates the department code. :param depis_gra... | import pandas as pd
import numpy as np
import folium, time
"""
SCREENING CENTERS IN PUBLIC ACCESS
"""
def clean_public_centers(depis_grand_public):
"""
We clean and complete the dataframe 'depis_grand_public' by adding missing informations.
We add a column who indicates the department code.
:param ... | Python | zaydzuhri_stack_edu_python |
comment simple class definition
class A
begin
function __init__ self message
begin
set message = message
end function
function __repr__ self
begin
set rep = string Class A:
set rep = rep + string message = { message }
return rep
end function
end class
comment second simple class definition - contains two instances of c... | # simple class definition
class A:
def __init__(self, message):
self.message = message
def __repr__(self):
rep = f"Class A:\n"
rep = rep + f" message = {self.message}\n"
return rep
# second simple class definition - contains two instances of class A
class B:
def __init... | Python | zaydzuhri_stack_edu_python |
function match_indices match
begin
string Yield index tuples (old_index, new_index) for each place in the match.
set tuple a b size = match
for i in range size
begin
yield tuple a + i b + i
end
end function | def match_indices(match):
"""Yield index tuples (old_index, new_index) for each place in the match."""
a, b, size = match
for i in range(size):
yield a + i, b + i | Python | jtatman_500k |
from Environment import Environment
import numpy as np
set num_samples = 5
set gamma = 1
class Agent
begin
function __init__ self
begin
set value_dict = dict
set need_update = list
end function
function getValue self state env
begin
set value = get value_dict state call getHeuristic state env
return value
end functio... | from Environment import Environment
import numpy as np
num_samples = 5
gamma = 1
class Agent:
def __init__(self) :
self.value_dict = {}
self.need_update = []
def getValue(self, state, env) :
value = self.value_dict.get(state, self.getHeuristic(state, env))
return value
de... | Python | zaydzuhri_stack_edu_python |
for _ in range integer input
begin
set R = integer input
set reds = list map int split input
set B = integer input
set blues = list map int split input
set tuple max_red total_red = tuple 0 0
for r in reds
begin
set total_red = total_red + r
set max_red = max max_red total_red
end
set tuple max_blue total_blue = tuple ... | for _ in range(int(input())):
R = int(input())
reds = list(map(int, input().split()))
B = int(input())
blues = list(map(int, input().split()))
max_red, total_red = 0, 0
for r in reds:
total_red += r
max_red = max(max_red, total_red)
max_blue, total_blue = 0, 0
for b in ... | Python | zaydzuhri_stack_edu_python |
function save_replay_buffer self
begin
if experience_replay is not none
begin
info string Saving experience replay buffer to "%s". save_file
call incremental_save true
end
end function | def save_replay_buffer(self):
if self.model.experience_replay is not None:
logging.info('Saving experience replay buffer to "%s".',
self.model.experience_replay.save_file)
self.model.experience_replay.incremental_save(True) | Python | nomic_cornstack_python_v1 |
comment import cv2 package
import cv2
import numpy as np
set events = list comprehension i for i in directory cv2 if string EVENT in i
print events
comment interrupt handler for mouse click events###########
function click_event event x y flags param
begin
if event == EVENT_LBUTTONDOWN
begin
set xy_val = string x + str... | import cv2 #import cv2 package
import numpy as np
events =[i for i in dir(cv2) if 'EVENT' in i]
print(events)
#interrupt handler for mouse click events###########
def click_event(event,x,y,flags,param):
if event == cv2.EVENT_LBUTTONDOWN:
xy_val=str(x)+','+str(y)
print(xy_val)
font =cv2.FONT... | Python | zaydzuhri_stack_edu_python |
function SetProxy self value
begin
if search value is none
begin
set _proxy = none
end
end function | def SetProxy(self, value):
if urlparse.URI_RE_STRICT.search(value) is None:
self._proxy = None | Python | nomic_cornstack_python_v1 |
function setup bot
begin
call add_cog call Keywords bot
end function | def setup(bot: Bot) -> None:
bot.add_cog(Keywords(bot)) | Python | nomic_cornstack_python_v1 |
set x = list comprehension x for x in range 1 101 if x % 3 != 0 and x % 7 == 0
print x |
x = [x for x in range(1,101) if x%3!=0 and x%7==0]
print(x)
| Python | zaydzuhri_stack_edu_python |
import json , argparse
set parser = call ArgumentParser
call add_argument string --file type=str
call add_argument string --outfile type=str
set arg = variables call parse_args
print string arg string
set res = load json open arg at string file
set tuple pred true files = tuple res at string pred res at string true re... | import json, argparse
parser = argparse.ArgumentParser()
parser.add_argument('--file', type=str)
parser.add_argument('--outfile', type=str)
arg = vars(parser.parse_args())
print('\n', arg, '\n')
res = json.load(open(arg['file']))
pred, true, files = res['pred'], res['true'], res['labels']
gender_wrong, race_wrong = ... | Python | zaydzuhri_stack_edu_python |
import sqlite3
set connection = call connect string shop
set cursorObj = call cursor
set sql = string CREATE TABLE products (ID INTEGER PRIMARY KEY AUTOINCREMENT,Brand TEXT, Model TEXT, Description TEXT)
execute cursorObj sql
set values = list list string Tecno string W2 string smartphone with 4 inch display 2MP front ... | import sqlite3
connection = sqlite3.connect('shop')
cursorObj = connection.cursor()
sql = "CREATE TABLE products (ID INTEGER PRIMARY KEY AUTOINCREMENT,Brand TEXT, Model TEXT, Description TEXT)"
cursorObj.execute(sql)
values = [['Tecno','W2','smartphone with 4 inch display 2MP front camera and 4Mp rear camera'],
... | Python | zaydzuhri_stack_edu_python |
import sys
from PyQt4 import QtCore , QtGui , uic
from user import User
set qtCreatorFile = string passwords.ui
set tuple Ui_MainWindow QtBaseClass = call loadUiType qtCreatorFile
class PasswordApp extends QMainWindow Ui_MainWindow
begin
function __init__ self
begin
call __init__ self
call __init__ self
call setupUi se... | import sys
from PyQt4 import QtCore, QtGui, uic
from user import User
qtCreatorFile = "passwords.ui"
Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile)
class PasswordApp(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
Ui_MainWindow.__init__(self)
... | Python | zaydzuhri_stack_edu_python |
function find_primes input_list
begin
string Returns a new list containing only prime numbers within the input list, sorted in ascending order.
set primes = list
for num in input_list
begin
if num > 1
begin
for i in range 2 num
begin
if num % i == 0
begin
break
end
end
for else
begin
append primes num
end
end
end
sort... | def find_primes(input_list):
"""
Returns a new list containing only prime numbers within the input list, sorted in ascending order.
"""
primes = []
for num in input_list:
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
... | Python | jtatman_500k |
from sklearn.feature_extraction.text import TfidfTransformer
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_matrix
c... | from sklearn.feature_extraction.text import TfidfTransformer
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import KFold
from sklearn.metrics import confusion_ma... | Python | zaydzuhri_stack_edu_python |
import sublime
import sublime_plugin
class TargetError extends WindowCommand
begin
function run self
begin
comment add bookmarks
set RegionsResult = find all call active_view string ERROR IGNORECASE
call add_regions string bookmarks RegionsResult string bookmarks string bookmark HIDDEN ? PERSISTENT
comment go to the fi... | import sublime
import sublime_plugin
class TargetError(sublime_plugin.WindowCommand):
def run(self):
# add bookmarks
RegionsResult = self.window.active_view().find_all(" ERROR ", sublime.IGNORECASE)
self.window.active_view().add_regions("bookmarks", RegionsResult, "bookmarks", "bookmark", sublime.HIDDEN | subl... | Python | zaydzuhri_stack_edu_python |
function random_data N
begin
set index = call binomial n=4 p=0.5
set distributions = dict string binomial_a call binomial n=20 p=0.6 size=N ; string binomial_b call binomial n=200 p=0.6 size=N ; string chisquare call chisquare df=10 size=N ; string exponential_a call exponential scale=0.1 size=N ; string exponential_b ... | def random_data(N):
index = np.random.binomial(n = 4, p = 0.5)
distributions = {
'binomial_a': np.random.binomial(n = 20, p = 0.6, size = N ),
'binomial_b': np.random.binomial(n = 200, p = 0.6, size = N ),
'chisquare': np.random.chisquare(df = 10, size = N ),... | Python | nomic_cornstack_python_v1 |
comment 線形探索 その2
set data = list 57 48 46 52 45 59 61 60 49 71
set n = length data
comment 目的の値
set key = 60
set i = 0
while i < n and data at i != key
begin
set i = i + 1
end
comment iの値がデータの終わりに達したら
if i == n
begin
print string key + string 存在しません
end
else
begin
print format string data[{}]が{}です i key
end | # 線形探索 その2
data = [57,48,46,52,45,59,61,60,49,71]
n = len(data)
key = 60 # 目的の値
i = 0
while i < n and data[i] != key:
i += 1
if i == n: # iの値がデータの終わりに達したら
print(str(key) + "存在しません")
else:
print('data[{}]が{}です'.format(i,key)) | Python | zaydzuhri_stack_edu_python |
from class_quadratic import *
function main
begin
print string Input a,b and c from an equation ax^2 + bx + c :
set p1 = call QuadraticEquation 1 0 - 9
set x1 = call x1
set x2 = call x2
print string Discriminant = call Discriminant
print string x1 = x1 string x2 = x2
end function
if __name__ == string __main__
begin
ca... | from class_quadratic import *
def main():
print("Input a,b and c from an equation ax^2 + bx + c : ")
p1 = QuadraticEquation(1,0,-9)
x1 = p1.x1()
x2 = p1.x2()
print ("Discriminant = ",p1.Discriminant())
print ("x1 = ",x1," x2 = ",x2)
if __name__ == "__main__":
main()
| Python | zaydzuhri_stack_edu_python |
function mark_playfield_active_from_device_action self
begin
call _playfield_switch_hit
end function | def mark_playfield_active_from_device_action(self):
self._playfield_switch_hit() | Python | nomic_cornstack_python_v1 |
function connect self
begin
set conf = conf
if not uris or not base
begin
raise call ConfigError string Base DN and LDAP URI(s) must be provided. 1
end
if tls_require_cert is not none
begin
if tls_require_cert not in list OPT_X_TLS_DEMAND OPT_X_TLS_HARD
begin
print BAD_REQCERT_WARNING file=stderr
end
comment this is a ... | def connect(self):
conf = self.conf
if not conf.uris or not conf.base:
raise ConfigError('Base DN and LDAP URI(s) must be provided.', 1)
if conf.tls_require_cert is not None:
if conf.tls_require_cert not in [ldap.OPT_X_TLS_DEMAND, ldap.OPT_X_TLS_HARD]:
p... | Python | nomic_cornstack_python_v1 |
function apply self df_events
begin
set all_gate_results = list
for gate_ref_dict in gate_refs
begin
set res_key = tuple gate_ref_dict at string ref join string / gate_ref_dict at string path
set gate_ref_events = df_events at res_key
if gate_ref_dict at string complement
begin
set gate_ref_events = ? gate_ref_events
... | def apply(self, df_events):
all_gate_results = []
for gate_ref_dict in self.gate_refs:
res_key = (gate_ref_dict['ref'], "/".join(gate_ref_dict['path']))
gate_ref_events = df_events[res_key]
if gate_ref_dict['complement']:
gate_ref_events = ~gate_ref_... | Python | nomic_cornstack_python_v1 |
from vgg_blocks import *
import torch
import torch.nn as nn
class VGG19 extends Module
begin
function __init__ self
begin
call __init__
comment input: 224x224 RGB images
set double_conv_1 = call DoubleConv 3 64
set double_conv_2 = call DoubleConv 64 128
set fourth_conv_1 = call FourthConv 128 256
set fourth_conv_2 = ca... | from vgg_blocks import *
import torch
import torch.nn as nn
class VGG19(nn.Module):
def __init__(self):
super(VGG19, self).__init__()
# input: 224x224 RGB images
self.double_conv_1 = DoubleConv(3, 64)
self.double_conv_2 = DoubleConv(64, 128)
self.fourth_conv_1 ... | Python | zaydzuhri_stack_edu_python |
function handle_event self event
begin
if type == KEYDOWN
begin
if key == K_LEFT
begin
call update_physics - 10
call detect_collisions
end
else
if key == K_RIGHT
begin
call update_physics 10
call detect_collisions
end
if key == K_UP
begin
call jump
call detect_collisions
end
end
end function | def handle_event(self, event):
if event.type == KEYDOWN:
if event.key == pygame.K_LEFT:
self.model.update_physics(-10)
self.model.detect_collisions()
elif event.key == pygame.K_RIGHT:
self.model.update_physics(10)
self.model.detect_collisions()
if event.key == pygame.K_UP:
self.model.jump... | Python | nomic_cornstack_python_v1 |
import cv2 as cv
import numpy as np
set img = call imread string lines.jpg
set gray = call cvtColor img COLOR_BGR2GRAY
set edges = call Canny gray 50 120
set minLineLength = 20
set maxLineGap = 5
set lines = call HoughLinesP edges 1 pi / 180.0 20 minLineLength maxLineGap
for tuple x1 y1 x2 y2 in lines at index
begin
ca... | import cv2 as cv
import numpy as np
img = cv.imread('lines.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray, 50, 120)
minLineLength = 20
maxLineGap = 5
lines = cv.HoughLinesP(edges, 1, np.pi/180.0, 20, minLineLength, maxLineGap)
for x1, y1, x2, y2 in lines[index]:
cv.line(img, (x1, y1), (x... | Python | zaydzuhri_stack_edu_python |
function turn_off self
begin
if not call socket_connect
begin
return - 1
end
if expression device_type != 4 then call send_bytes 113 36 15 164 else call send_bytes 204 36 51
close s
return 0
end function | def turn_off(self):
if not self.socket_connect():
return -1
self.send_bytes(0x71, 0x24, 0x0F, 0xA4) if self.device_type != 4 else self.send_bytes(0xCC, 0x24, 0x33)
self.s.close()
return 0 | Python | nomic_cornstack_python_v1 |
from MetricEvaluator.evaluate_metrics import MetricOnSaliencyExtractor as MOSE
import time
class ElapsedTime extends MOSE
begin
function __init__ self name result=0.0 nimgs=0.0
begin
call __init__ name result
set nimgs = nimgs
set step = 0
end function
function update self *args
begin
if step % 2 == 0
begin
set now = t... | from MetricEvaluator.evaluate_metrics import MetricOnSaliencyExtractor as MOSE
import time
class ElapsedTime(MOSE):
def __init__(self,name,result=0.,nimgs=0.):
super().__init__(name,result)
self.nimgs=nimgs
self.step=0
def update(self,*args):
if self.step % 2 == 0:
... | Python | zaydzuhri_stack_edu_python |
function __draw_title self
begin
if title is not none
begin
call suptitle title y=otherParams at string figure.title.yposition
end
end function | def __draw_title(self):
if self.title is not None:
self.fig.suptitle(
self.title, y=self.settings.otherParams["figure.title.yposition"]) | Python | nomic_cornstack_python_v1 |
comment read with files
set f = open string text.txt
set output = read f
comment readline(s), one by one
print output
close f
print string
with open string text.txt as f
begin
set output = read f
print output
end
comment writing to file
set f = open string new_text.txt mode=string w
write f string I love python + strin... | # read with files
f = open("text.txt")
output = f.read()
# readline(s), one by one
print(output)
f.close()
print("\n")
with open("text.txt") as f:
output = f.read()
print(output)
# writing to file
f = open("new_text.txt", mode="w")
f.write(("I love python" + "\n") * 50)
f.flush()
f.close()
with open("new... | Python | zaydzuhri_stack_edu_python |
function test_search_index_with_template_get self
begin
pass
end function | def test_search_index_with_template_get(self):
pass | Python | nomic_cornstack_python_v1 |
function __iadd__ self other
begin
if not is instance other NNNCrossCorrelation
begin
raise call TypeError string Can only add another NNNCrossCorrelation object
end
set n1n2n3 = n1n2n3 + n1n2n3
set n1n3n2 = n1n3n2 + n1n3n2
set n2n1n3 = n2n1n3 + n2n1n3
set n2n3n1 = n2n3n1 + n2n3n1
set n3n1n2 = n3n1n2 + n3n1n2
set n3n2n... | def __iadd__(self, other):
if not isinstance(other, NNNCrossCorrelation):
raise TypeError("Can only add another NNNCrossCorrelation object")
self.n1n2n3 += other.n1n2n3
self.n1n3n2 += other.n1n3n2
self.n2n1n3 += other.n2n1n3
self.n2n3n1 += other.n2n3n1
self.n3... | Python | nomic_cornstack_python_v1 |
string Module to deal with metadata acquisition.
comment pylint:disable=W0603
from __future__ import absolute_import
import contextlib
import logging
import os
import re
import shutil
import tarfile
import tempfile
from rdflib import plugin
from rdflib.graph import Graph
from rdflib.term import URIRef
from rdflib.store... | """Module to deal with metadata acquisition."""
# pylint:disable=W0603
from __future__ import absolute_import
import contextlib
import logging
import os
import re
import shutil
import tarfile
import tempfile
from rdflib import plugin
from rdflib.graph import Graph
from rdflib.term import URIRef
from rdflib.store imp... | Python | zaydzuhri_stack_edu_python |
set tuple H W = map int split input
set tuple h w = map int split input
set hyo = H * W
set hr = h * W
set wr = w * H - h
set ans = hyo - hr + wr
print ans | H, W = map(int, input().split())
h, w = map(int, input().split())
hyo = H * W
hr = h * W
wr = w * (H-h)
ans = (hyo - (hr+wr))
print(ans) | Python | zaydzuhri_stack_edu_python |
function create self data
begin
set db_obj = call App
set id = call generate_uuid
set user_id = user
set project_id = tenant
set deleted = false
comment create a delegation trust_id\token, if required
set trust_id = call create_delegation_token context
set trust_user = user_name
set name = get data string name
set desc... | def create(self, data):
db_obj = objects.registry.App()
db_obj.id = uuidutils.generate_uuid()
db_obj.user_id = self.context.user
db_obj.project_id = self.context.tenant
db_obj.deleted = False
# create a delegation trust_id\token, if required
db_obj.trust_id = key... | Python | nomic_cornstack_python_v1 |
function SetNumberOfBinsPerAxis self arg0
begin
return call itkScalarImageToRunLengthFeaturesFilterISS2_SetNumberOfBinsPerAxis self arg0
end function | def SetNumberOfBinsPerAxis(self, arg0: 'unsigned int') -> "void":
return _itkScalarImageToRunLengthFeaturesFilterPython.itkScalarImageToRunLengthFeaturesFilterISS2_SetNumberOfBinsPerAxis(self, arg0) | Python | nomic_cornstack_python_v1 |
function _get_correct_module mod
begin
set module_location = get attribute mod string leonardo_module_conf get attribute mod string LEONARDO_MODULE_CONF none
if module_location
begin
set mod = call import_module module_location
end
else
if has attribute mod string default_app_config
begin
comment use django behavior
se... | def _get_correct_module(mod):
module_location = getattr(
mod, 'leonardo_module_conf',
getattr(mod, "LEONARDO_MODULE_CONF", None))
if module_location:
mod = import_module(module_location)
elif hasattr(mod, 'default_app_config'):
# use django behavior
mod_path, _, cls... | Python | nomic_cornstack_python_v1 |
function author_view self context=none
begin
comment Setup last uploaded datetime
set upload_dt = string
if nb_upload_datetime
begin
set dt = call parse_datetime nb_upload_datetime
set upload_dt = string format time dt string %Y-%m-%d %H:%M:%S + string UTC
end
set req = call get_requirements string course_id
call init... | def author_view(self, context=None):
# Setup last uploaded datetime
upload_dt = ''
if self.nb_upload_datetime:
dt = dateparse.parse_datetime(self.nb_upload_datetime)
upload_dt = dt.strftime("%Y-%m-%d %H:%M:%S") + " UTC"
req = nbu.get_requirements(str(self.course_i... | Python | nomic_cornstack_python_v1 |
function render_output self
begin
comment TODO Setup license before output.
comment Select file to save as
set opts = dict
set opts at string title = string Select Output file to save.
set opts at string defaultextension = string .script
set opts at string initialfile = string output.script
set filename = call asksave... | def render_output(self):
#TODO Setup license before output.
# Select file to save as
opts = {}
opts['title'] = 'Select Output file to save.'
opts['defaultextension'] = '.script'
opts['initialfile'] = 'output.script'
filename = tkFileDialog.asksaveasfilename(**opts... | Python | nomic_cornstack_python_v1 |
comment Implementing the Decision Tree
set training_dataset = list list string Green 3 string Mango list string Yellow 3 string Mango list string Red 1 string Grape list string Red 1 string Grape list string Yellow 3 string Lemon
comment [Feature, Feature, Label]
comment Column labels
comment These are used to printthe... | #Implementing the Decision Tree
training_dataset = [
['Green', 3, 'Mango'],
['Yellow', 3, 'Mango'],
['Red', 1, 'Grape'],
['Red', 1, 'Grape'],
['Yellow', 3, 'Lemon']
] #[Feature, Feature, Label]
#Column labels
#These are used to printthe tree
header = ['color', 'diameter', 'label']
#A function of... | Python | zaydzuhri_stack_edu_python |
comment good
if a == string PythonMentoring
begin
print string Pass
end
else
begin
print string Non-Pass
end | #good
if a == "PythonMentoring":
print("Pass")
else:
print("Non-Pass")
| Python | zaydzuhri_stack_edu_python |
function SetEnabled self state=true
begin
set callResult = call _Call string SetEnabled state
end function | def SetEnabled(self, state=True):
callResult = self._Call("SetEnabled", state) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python2
comment Filename is method.py | #!/usr/bin/python2
#Filename is method.py
| Python | zaydzuhri_stack_edu_python |
import numpy as np
function __interchange__ matrix row1 row2
begin
string Interchange two rows
set temp = copy matrix at row1
set matrix at row1 = matrix at row2
set matrix at row2 = temp
end function
function __multiply__ matrix row number
begin
string Multiply a with a non-zero constant
set matrix at row = matrix at ... | import numpy as np
def __interchange__(matrix, row1, row2):
"""Interchange two rows"""
temp = matrix[row1].copy()
matrix[row1] = matrix[row2]
matrix[row2] = temp
def __multiply__(matrix, row, number):
"""Multiply a with a non-zero constant"""
matrix[row] = matrix[row] * number
... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
from tensorflow import keras
import pickle
from keras.preprocessing.sequence import pad_sequences
set model = call load_model string model/model.h5
set tokenizer = load pickle open string model/tokenizer.pkl string rb
set decode_map = dict 0 string NEGATIVE ; 2 string NEUTRAL ; 4 string POSITIVE... | import tensorflow as tf
from tensorflow import keras
import pickle
from keras.preprocessing.sequence import pad_sequences
model = tf.keras.models.load_model('model/model.h5')
tokenizer = pickle.load(open('model/tokenizer.pkl', 'rb'))
decode_map = {0: "NEGATIVE", 2: "NEUTRAL", 4: "POSITIVE"}
SENTIMENT_THRESHOLDS = (0... | Python | zaydzuhri_stack_edu_python |
string UDF- User defined Functions
string print() int() #built in function input() #Logic Separation def add(): #addition logic def sub(): #sub logic def mul(): #mul logic def div(): #div logic
function myfunction
begin
print string this is my function
end function
comment call a function
comment the print line comes t... | '''
UDF- User defined Functions
'''
'''
print()
int() #built in function
input()
#Logic Separation
def add():
#addition logic
def sub():
#sub logic
def mul():
#mul logic
d... | Python | zaydzuhri_stack_edu_python |
function build_checks_list
begin
comment Start to build a list of functions we will execute.
set uptux_checks = list
comment Get the name of this python script and all the functions inside it.
set current_module = modules at __name__
set all_functions = get members current_module isfunction
comment If the function nam... | def build_checks_list():
# Start to build a list of functions we will execute.
uptux_checks = []
# Get the name of this python script and all the functions inside it.
current_module = sys.modules[__name__]
all_functions = inspect.getmembers(current_module, inspect.isfunction)
# If the function... | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
from car_interfacing import CarConnection
from keras.models import load_model
from decimal import *
from time import time
comment oka mudel: conv_dense_gear_bigdata
comment conv_speshul_data_000001regL2_05dropout_LR
set model = call load_model string .\Models\conv_dense_gear_bigdata.h5
set... | import numpy as np
import cv2
from car_interfacing import CarConnection
from keras.models import load_model
from decimal import *
from time import time
# oka mudel: conv_dense_gear_bigdata
# conv_speshul_data_000001regL2_05dropout_LR
model = load_model(".\Models\conv_dense_gear_bigdata.h5")
connection = CarConnection... | Python | zaydzuhri_stack_edu_python |
function exptime_element lam cp cn wantsnr
begin
set DtSNR = zeros length lam
set i = cp > 0.0
set j = cp <= 0.0
comment (hr)
set DtSNR at i = wantsnr ^ 2.0 * cn at i / cp at i ^ 2.0 / 3600.0
set DtSNR at j = nan
return DtSNR
end function | def exptime_element(lam, cp, cn, wantsnr):
DtSNR = np.zeros(len(lam))
i = (cp > 0.)
j = (cp <= 0.0)
DtSNR[i] = (wantsnr**2.*cn[i])/cp[i]**2./3600. # (hr)
DtSNR[j] = np.nan
return DtSNR | Python | nomic_cornstack_python_v1 |
function Delete self
begin
string Delete public IP. >>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComplete() 0
set public_ip_set = list comprehension dict string public_ipId id for o in public_ips if o != self
set public_ips = list comprehension o for o in public_ips if o != self
return ca... | def Delete(self):
"""Delete public IP.
>>> clc.v2.Server("WA1BTDIX01").PublicIPs().public_ips[0].Delete().WaitUntilComplete()
0
"""
public_ip_set = [{'public_ipId': o.id} for o in self.parent.public_ips if o!=self]
self.parent.public_ips = [o for o in self.parent.public_ips if o!=self]
return(clc.v2.Re... | Python | jtatman_500k |
function job lamb flux fluxerr mask fluxmod extLaw **kwargs
begin
comment get attenuation
set tau = call getFluxAttenuation extLaw lamb keyword kwargs
comment deredden the observed flux (faster than adding reddening to all models
set deredflux = flux * exp tau
comment ind = (deredflux > 0.)
comment deredflux[ind] = der... | def job(lamb, flux, fluxerr, mask, fluxmod, extLaw, **kwargs):
#get attenuation
tau = getFluxAttenuation(extLaw, lamb, **kwargs)
#deredden the observed flux (faster than adding reddening to all models
deredflux = flux*exp(tau)
#ind = (deredflux > 0.)
#deredflux[ind] = deredflux[ind]
#ind = (fluxmod > 0.)
... | Python | nomic_cornstack_python_v1 |
function _was_called_with m *args **kwargs
begin
for item in call_args_list
begin
if item at 0 == args and item at 1 == kwargs
begin
return true
end
end
return false
end function | def _was_called_with(m, *args, **kwargs):
for item in m.call_args_list:
if item[0] == args and item[1] == kwargs:
return True
return False | Python | nomic_cornstack_python_v1 |
comment # functions
set avengers = list string hulk string captain string ironman string captain string black widow
set dc = list string wonderwoman string batman string joker string aquaman
set heroes = list string shaktiman string asterix string omniman
print string heroes = heroes
comment heroes.append(dc)
extend he... | # # functions
avengers = ['hulk', 'captain', 'ironman', 'captain', 'black widow']
dc = ['wonderwoman', 'batman', 'joker', 'aquaman']
heroes = ['shaktiman', 'asterix', 'omniman']
print("heroes = ", heroes)
# heroes.append(dc)
heroes.extend(dc)
print("heroes = ", heroes)
| Python | zaydzuhri_stack_edu_python |
function _create_qubo_matrix self
begin
comment Set properties
comment The Qubo matrix is an upper triangular matrix.
comment Diagonal elements in the QUBO matrix is for linear terms of the qubit operator
comment The other elements in the QUBO matrix is for quadratic terms of the qubit operator
set _qubo_matrix = zeros... | def _create_qubo_matrix(self):
# Set properties
# The Qubo matrix is an upper triangular matrix.
# Diagonal elements in the QUBO matrix is for linear terms of the qubit operator
# The other elements in the QUBO matrix is for quadratic terms of the qubit operator
self._qubo_matrix... | Python | nomic_cornstack_python_v1 |
function test_set_public_key_setter self
begin
set expected = decode pem_public_key
set encryptor = call DataEncryption
call set_public_key pem_public_key
comment pylint: disable=protected-access
set actual = decode call public_bytes PEM PKCS1
assert equal expected actual
end function | def test_set_public_key_setter(self) -> None:
expected = self.pem_public_key.decode()
encryptor = DataEncryption()
encryptor.set_public_key(self.pem_public_key)
# pylint: disable=protected-access
actual = encryptor._loaded_public_key.public_bytes(
serialization.Enc... | Python | nomic_cornstack_python_v1 |
function async_is_prime x
begin
if x < 2
begin
return false
end
for i in range 2 integer square root x + 1
begin
sleep 0.1
if x % i == 0
begin
return false
end
yield from call async_sleep 0
end
return true
end function | def async_is_prime(x):
if x < 2:
return False
for i in range(2, int(math.sqrt(x)) + 1):
time.sleep(0.1)
if x % i == 0:
return False
yield from async_sleep(0)
return True | Python | nomic_cornstack_python_v1 |
function process_html_page self html
begin
set html = html
set html_soup = call BeautifulSoup html
set text = call _remove_div_content
end function | def process_html_page(self, html):
self.html = html
self.html_soup = BeautifulSoup(html)
self.text = self._remove_div_content() | Python | nomic_cornstack_python_v1 |
function read_graph filename
begin
return call read_edgelist filename create_using=call DiGraph nodetype=str
end function | def read_graph(filename):
return nx.read_edgelist(filename, create_using=nx.DiGraph(), nodetype=str) | Python | nomic_cornstack_python_v1 |
set student_details = list dict string id 1 ; string subject dict string math tuple 70 82 ; string cs tuple 75 87 dict string id 2 ; string subject dict string math tuple 73 74 ; string cs tuple 78 79 dict string id 3 ; string subject dict string math tuple 75 86 ; string cs tuple 80 91
set averages = dictionary compre... | student_details= [
{'id' : 1, 'subject' : {'math': (70, 82), 'cs': (75, 87)}},
{'id' : 2, 'subject' : {'math': (73, 74), 'cs': (78, 79)}},
{'id' : 3, 'subject' : {'math': (75, 86), 'cs': (80, 91)}}
]
averages = {s['id']: {subject: sum(points)/2 for subject, points in s['subject'].items()} for s in student_detail... | Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ self data=none next=none
begin
set data = data
set next = next
end function
end class
class linkedList
begin
function __init__ self
begin
set head = none
end function
function insert_beg self data
begin
set node = call Node data head
set head = node
end function
function display self
... | class Node:
def __init__(self, data=None,next = None):
self.data = data
self.next = next
class linkedList:
def __init__(self):
self.head = None
def insert_beg(self,data):
node = Node(data,self.head)
self.head = node
def display(self):
if self.head is None:
return
itr = self.head
str_ll = ""
... | Python | zaydzuhri_stack_edu_python |
from equibasepdfScraper import equibasePdfScraper
from pdfhandling import pdfHandler
import os
class pdfControl
begin
set csvOutFile = string /Users/markusnotti/Documents/UCLA/Winter2016/170A-Mathmatical Modeling and Methods for Computer Science/horseRacing/data/decryptedResultsData/resultsCSV/raceResults.csv
set decry... | from equibasepdfScraper import equibasePdfScraper
from pdfhandling import pdfHandler
import os
class pdfControl:
csvOutFile= "/Users/markusnotti/Documents/UCLA/Winter2016/170A-Mathmatical Modeling and Methods for Computer Science/horseRacing/data/decryptedResultsData/resultsCSV/raceResults.csv"
decryptedPath="/Users... | Python | zaydzuhri_stack_edu_python |
comment Problem 3
comment Largest prime factor
function mpf n
begin
set p = - 1
while n % 2 == 0
begin
set p = 2
set n = n / 2
end
set sqN = n ^ 1 / 2 + 1
set sqN = integer sqN
for i in range 3 sqN 2
begin
while n % i == 0
begin
set p = i
set n = n / i
end
end
if n > 2
begin
set p = n
end
return integer p
end function
... | # Problem 3
# Largest prime factor
def mpf(n):
p = -1
while(n % 2 == 0):
p = 2
n /= 2
sqN = n ** (1/2) + 1
sqN = int(sqN)
for i in range(3, sqN, 2):
while(n % i == 0):
p = i
n /= i
if n > 2:
p = n
retur... | Python | zaydzuhri_stack_edu_python |
import threading
import socket
class ClientHandler extends Thread
begin
function __init__ self comm_socket likeliestClassValue
begin
call __init__
set comm_socket = comm_socket
set likeliestClassValue = likeliestClassValue
end function
function run self
begin
comment print("started thread")
set data = call send bytes s... | import threading
import socket
class ClientHandler(threading.Thread):
def __init__(self, comm_socket, likeliestClassValue):
super(ClientHandler, self).__init__()
self.comm_socket = comm_socket
self.likeliestClassValue = likeliestClassValue
def run(self):
#print("started thread"... | Python | zaydzuhri_stack_edu_python |
function export self path
begin
import labstep.entities.protocol.repository as protocolRepository
return call exportProtocol self path
end function | def export(self, path):
import labstep.entities.protocol.repository as protocolRepository
return protocolRepository.exportProtocol(self, path) | Python | nomic_cornstack_python_v1 |
function get name bins min_obs
begin
set methods = call get_all
set m = none
for method in methods
begin
comment and method[1].is_valid():
if name == lower method at 0
begin
set m = call bins min_obs
end
end
return m
end function | def get(name, bins, min_obs):
methods = get_all()
m = None
for method in methods:
if name == method[0].lower(): # and method[1].is_valid():
m = method[1](bins, min_obs)
return m | Python | nomic_cornstack_python_v1 |
string Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. Note: Division between two integers should truncate toward zero. The given RPN expression is always valid. That means the expression would always evalua... | """
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid. That means the expression would always evalua... | Python | zaydzuhri_stack_edu_python |
function admin_add_panel_user request
begin
set user_name = get session string user_name
set template = string admin_panel/admin_add_panel_user.html
if method == string GET
begin
try
begin
set panel_data = call get_admin_panel_user_data user_name
set context = dict string panel_data panel_data
return call render reques... | def admin_add_panel_user(request):
user_name = request.session.get('user_name')
template = 'admin_panel/admin_add_panel_user.html'
if request.method == 'GET':
try:
panel_data = util.get_admin_panel_user_data(user_name)
context = {
'panel_data': panel_data,
... | Python | nomic_cornstack_python_v1 |
function setScore self score
begin
debug string score=%d % score
set numMolesWhacked = score
call updateGuiScore
set molesLeft = MolesWhackedTarget - numMolesWhacked
if molesLeft == 0
begin
call gameWon
end
end function | def setScore(self, score):
self.notify.debug('score=%d' % score)
self.numMolesWhacked = score
self.updateGuiScore()
molesLeft = self.MolesWhackedTarget - self.numMolesWhacked
if molesLeft == 0:
self.gameWon() | Python | nomic_cornstack_python_v1 |
function parse conlleval_stdout
begin
for line in split conlleval_stdout string
begin
if string accuracy in line
begin
set p = decimal find all string precision:\s*(\d+\.\d+)% line at 0
set r = decimal find all string recall:\s*(\d+\.\d+)% line at 0
set f = decimal find all string FB1:\s*(\d+\.\d+) line at 0
end
end
re... | def parse(conlleval_stdout):
for line in conlleval_stdout.split('\n'):
if 'accuracy' in line:
p = float(re.findall(r'precision:\s*(\d+\.\d+)%', line)[0])
r = float(re.findall(r'recall:\s*(\d+\.\d+)%', line)[0])
f = float(re.findall(r'FB1:\s*(\d+\.\d+)', line)[0])
retu... | 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.