code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
set train = read csv string kfold/train_clean_english.csv
from sklearn.model_selection import StratifiedKFold
set NFOLDS = 10
set kfold = call StratifiedKFold n_splits=NFOLDS
comment x_train_0 = train[train['threat']==1][['comment_text','threat']]
com... | # -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
train = pd.read_csv('kfold/train_clean_english.csv')
from sklearn.model_selection import StratifiedKFold
NFOLDS = 10
kfold = StratifiedKFold(n_splits=NFOLDS)
#x_train_0 = train[train['threat']==1][['comment_text','threat']]
#x_0 = x_train_0.comment_tex... | Python | zaydzuhri_stack_edu_python |
function download_to_directory self directory url basename=none overwrite=false subdir=none
begin
string Download a file to the workspace. Early Shortcut: If url is a file://-URL and that file is already in the directory, keep it there. If basename is not given but subdir is, assume user knows what she's doing and use ... | def download_to_directory(self, directory, url, basename=None, overwrite=False, subdir=None):
"""
Download a file to the workspace.
Early Shortcut: If url is a file://-URL and that file is already in the directory, keep it there.
If basename is not given but subdir is, assume user know... | Python | jtatman_500k |
function startIfNeeded self
begin
assert call debugStateCall self
comment we need a try to stop the level editor from crashing
try
begin
set curPhase = call getPhaseToRun
if curPhase >= 0
begin
call request string DoAnim
end
end
except any
begin
pass
end
end function | def startIfNeeded(self):
assert self.notify.debugStateCall(self)
# we need a try to stop the level editor from crashing
try:
self.curPhase = self.getPhaseToRun()
if self.curPhase >= 0:
self.request('DoAnim')
except:
pass | Python | nomic_cornstack_python_v1 |
function error self msg *args **kwargs
begin
error msg *args keyword kwargs
end function | def error(self, msg, *args, **kwargs):
self.plugin.error(msg, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
class GrandFather
begin
function func1 self
begin
print string Grand Father class
end function
end class
class Father extends GrandFather
begin
function func2 self
begin
print string Father class
end function
end class
class Child extends Father
begin
function func3 self
begin
print string Child class
end function
end ... | class GrandFather:
def func1(self):
print("Grand Father class")
class Father(GrandFather):
def func2(self):
print("Father class")
class Child(Father):
def func3(self):
print("Child class")
obj=Child()
obj.func1()
obj.func2()
obj.func3() | Python | zaydzuhri_stack_edu_python |
function publication_date self
begin
return start_publication or creation_date
end function | def publication_date(self):
return self.start_publication or self.creation_date | Python | nomic_cornstack_python_v1 |
function app_insights_enabled self
begin
return get pulumi self string app_insights_enabled
end function | def app_insights_enabled(self) -> Optional[bool]:
return pulumi.get(self, "app_insights_enabled") | Python | nomic_cornstack_python_v1 |
function deploy_service service instance marathon_jobid config clients marathon_apps_with_clients bounce_method drain_method_name drain_method_params nerve_ns bounce_health_params soa_dir job_config bounce_margin_factor=1.0
begin
function log_deploy_error errormsg level=string event
begin
return call _log service=servi... | def deploy_service(
service: str,
instance: str,
marathon_jobid: str,
config: marathon_tools.FormattedMarathonAppDict,
clients: marathon_tools.MarathonClients,
marathon_apps_with_clients: Collection[Tuple[MarathonApp, MarathonClient]],
bounce_method: str,
drain_method_name: str,
drai... | Python | nomic_cornstack_python_v1 |
function begin_update_appliance self fabric_name protection_container_name replicated_protected_item_name appliance_update_input **kwargs
begin
comment type: str
comment type: str
comment type: str
comment type: "_models.UpdateApplianceForReplicationProtectedItemInput"
comment type: Any
comment type: (...) -> LROPoller... | def begin_update_appliance(
self,
fabric_name, # type: str
protection_container_name, # type: str
replicated_protected_item_name, # type: str
appliance_update_input, # type: "_models.UpdateApplianceForReplicationProtectedItemInput"
**kwargs # type: Any
):
... | Python | nomic_cornstack_python_v1 |
function save self
begin
set store = call HDFStore hdf5FileName
put string shape call DataFrame shape
set cnt = length boardFeatureTable
put string boardFeatureTable call DataFrame call tolist
put string winRateTable call DataFrame winRateTable
put string moveRateTable call DataFrame moveRateTable
put string modelVersi... | def save(self):
store = pd.HDFStore(self.hdf5FileName)
store.put('shape', pd.DataFrame(self.shape))
cnt = len(self.boardFeatureTable)
store.put('boardFeatureTable', pd.DataFrame(
np.array(self.boardFeatureTable).reshape(cnt, self.rowCount * self.colCount * self.channelCount).... | Python | nomic_cornstack_python_v1 |
string Faça um programa em Python que preencha uma lista com dez números reais informados pelo usuário, calcule e mostre a quantidade de números negativos e a soma dos positivos dessa lista.
set lista = list
set contNegativos = 0
set soma = 0
for i in range 1 11
begin
set num = decimal input string Informe o { i } º n... | """
Faça um programa em Python que preencha uma lista com dez números reais
informados pelo usuário, calcule e mostre a quantidade de números negativos e a
soma dos positivos dessa lista.
"""
lista = []
contNegativos = soma = 0
for i in range(1, 11):
num = float(input(f'Informe o {i}º número real: '))
lista.ap... | Python | zaydzuhri_stack_edu_python |
comment ! /bin/python3
comment # Exercise 1 - Paint Area Colour
comment import math
comment def paint_calc(height, width, cover):
comment tins = math.ceil(height*width/cover)
comment print(f"You will need {tins} tins of paint")
comment test_h = int(input("Height of wall: "))
comment test_w = int(input("Width of wall: "... | #! /bin/python3
# # Exercise 1 - Paint Area Colour
# import math
# def paint_calc(height, width, cover):
# tins = math.ceil(height*width/cover)
# print(f"You will need {tins} tins of paint")
# test_h = int(input("Height of wall: "))
# test_w = int(input("Width of wall: "))
# coverage = 5
# paint_calc(heigh... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import os
import random
import gc
from glob import glob
from keras.preprocessing.image import load_img
from itertools import chain
from sklearn.model_selection import train_test_split
from keras import models
from keras import layers
from keras import optimizers
from keras.preprocessing.... | import matplotlib.pyplot as plt
import os
import random
import gc
from glob import glob
from keras.preprocessing.image import load_img
from itertools import chain
from sklearn.model_selection import train_test_split
from keras import models
from keras import layers
from keras import optimizers
from keras.preprocessing.... | Python | zaydzuhri_stack_edu_python |
class Follower
begin
function __init__ self
begin
set ball_diff = 0
end function
function get self
begin
if ball_diff == 0
begin
return 0
end
else
if ball_diff > 0
begin
return - 1
end
else
if ball_diff < 0
begin
return 1
end
end function
function update self grid
begin
set ball_data = list
function find_ball data row... | class Follower:
def __init__(self):
self.ball_diff = 0
def get(self):
if self.ball_diff == 0:
return 0
elif self.ball_diff > 0:
return -1
elif self.ball_diff < 0:
return 1
def update(self, grid):
ball_data = []
def find_ba... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function numSubarrayProductLessThanK self nums k
begin
if k <= 1
begin
return 0
end
set ans = 0
set left = 0
set product = 1
for right in range length nums
begin
set product = product * nums at right
while product >= k
begin
set product = product // nums at left
set left = left + 1
end
set ans = an... | class Solution:
def numSubarrayProductLessThanK(self, nums, k):
if k <= 1:
return 0
ans = left = 0
product = 1
for right in range(len(nums)):
product *= nums[right]
while product >= k:
product //= nums[left]
left += ... | Python | zaydzuhri_stack_edu_python |
from ae_key_frame import AE_Keyframe
function create_keyframe data base_keyframe_type keyframe_type
begin
string :param data, base_keyframe_type, keyframe_type: :param data:
set keyframe_list = list
for data_item in data
begin
set tuple frame key_data = data_item
append keyframe_list call AE_Keyframe frame base_keyfra... | from ae_key_frame import AE_Keyframe
def create_keyframe(data, base_keyframe_type, keyframe_type):
"""
:param data, base_keyframe_type, keyframe_type:
:param data:
"""
keyframe_list = []
for data_item in data:
(frame, key_data) = data_item
keyframe_list.append(AE_Keyframe(fr... | Python | zaydzuhri_stack_edu_python |
from bisect import bisect_left , bisect_right
from itertools import combinations
if __name__ == string __main__
begin
set tuple N K L R = map lambda x -> integer x split input
set coins = list map lambda x -> integer x split input
set N_half = N // 2
set c1 = list comprehension list map sum call combinations coins at s... | from bisect import bisect_left, bisect_right
from itertools import combinations
if __name__ == "__main__":
N, K, L, R = map(lambda x: int(x), input().split())
coins = list(map(lambda x: int(x), input().split()))
N_half = N // 2
c1 = [list(map(sum, combinations(coins[:N_half], i))) for i in range(0, N... | Python | jtatman_500k |
function renew self cr uid ids context=dict
begin
set rented_obj = get pool string rented.cars
set vehicle_obj = get pool string fleet.vehicle
for record in call browse cr uid ids context=context
begin
for line in car_ids
begin
set rented_record_id = search cr uid list tuple string car_id string = id tuple string state... | def renew(self,cr,uid,ids,context={}):
rented_obj = self.pool.get('rented.cars')
vehicle_obj = self.pool.get('fleet.vehicle')
for record in self.browse(cr,uid,ids,context=context):
for line in record.car_ids:
rented_record_id = rented_obj.search(cr, u... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
import matplotlib.pyplot as plt
from triangles.utils import get_mobius_triangle
from triangles.chains import get_chain
set triangle_type = tuple 2 3 7
set W = string ab
set ini_tri = call get_mobius_triangle *triangle_type
comment %* Se genera la cadena y se guardan los vértices,*)
set tuple v e f... | # coding: utf-8
import matplotlib.pyplot as plt
from triangles.utils import get_mobius_triangle
from triangles.chains import get_chain
triangle_type = (2, 3, 7)
W = 'ab'
ini_tri = get_mobius_triangle(*triangle_type)
v, e, f = get_chain(ini_tri, W) #%* Se genera la cadena y se guardan los vértices,*)
... | Python | zaydzuhri_stack_edu_python |
function gettingJPLUS_123limmags clustername
begin
set sigmas = 5
set root2images = finalroot + string images/%s/ % clustername
set listimages = root2images + string sci.list
set imas = call get_str listimages 0
set nims = length imas
set finalcat = root2images + string %s.photo.mlim123.cat % clustername
if not exists ... | def gettingJPLUS_123limmags(clustername):
sigmas = 5
root2images = finalroot + 'images/%s/'%(clustername)
listimages = root2images+'sci.list'
imas = U.get_str(listimages,0)
nims = len(imas)
finalcat = root2images+'%s.photo.mlim123.cat'%(clustername)
if not os.path.exists(finalcat):
... | Python | nomic_cornstack_python_v1 |
function pie_plot search_list image_dest
begin
comment plt.style.use('fivethirtyeight')
set labels = list keys search_list
set counts = list values search_list
call pie counts labels=labels autopct=string %1.1f%%
axis string equal
save figure image_dest
close plt
return
end function | def pie_plot(search_list, image_dest):
# plt.style.use('fivethirtyeight')
labels = list(search_list.keys())
counts = list(search_list.values())
plt.pie(counts, labels=labels, autopct='%1.1f%%')
plt.axis('equal')
plt.savefig(image_dest)
plt.close()
return | Python | nomic_cornstack_python_v1 |
function test_minio_get_storage_used self mock_class
begin
set return_value = list keys s3_fake_objects
set side_effect = list list keys s3_fake_objects at string bucket1 list keys s3_fake_objects at string bucket2
set side_effect = list values s3_fake_objects at string bucket1 + list values s3_fake_objects at string b... | def test_minio_get_storage_used(self, mock_class):
mock_class().list_buckets.return_value = list(s3_fake_objects.keys())
mock_class().list_objects.side_effect = [list(s3_fake_objects["bucket1"].keys()),
list(s3_fake_objects["bucket2"].keys())]
mock_class().stat_o... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import sys , re
from bisect import bisect_left
comment http://code.google.com/codejam/contest/dashboard?c=351101
comment http://stackoverflow.com/questions/212358/binary-search-in-python/2233940#2233940
comment can't use a to specify default for hi
function binary_search a x lo=0 hi=none
begin
... | #!/usr/bin/python
import sys,re
from bisect import bisect_left
#http://code.google.com/codejam/contest/dashboard?c=351101
#http://stackoverflow.com/questions/212358/binary-search-in-python/2233940#2233940
def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
hi = hi if hi is not None ... | Python | zaydzuhri_stack_edu_python |
function get_branches tree only_term=true
begin
comment remove all special symbols
set filtered_str = sub string [^\w] string tree
comment get rid of numbers
set filtered = set list comprehension x for x in split filtered_str if not is digit x
set filtered = if expression only_term then list comprehension x for x in f... | def get_branches(tree, only_term=True):
# remove all special symbols
filtered_str = re.sub(r'[^\w]', ' ', tree)
# get rid of numbers
filtered = set([x for x in filtered_str.split() if not x.isdigit()])
filtered = [x for x in filtered if "-" not in x and "_" not in x] if only_term else filtered
r... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment coding=utf-8
comment useing python implement Xi'an shiyou unniversity spider
comment Environments: Beautiful selenium and re
comment coded at 2016.9.18 by liuyuzhuo
from bs4 import BeautifulSoup
from urllib import urlopen
from selenium import webdriver
import xlwt
import os
import ... | #!/usr/bin/env python3
# coding=utf-8
#useing python implement Xi'an shiyou unniversity spider
#Environments: Beautiful selenium and re
#coded at 2016.9.18 by liuyuzhuo
from bs4 import BeautifulSoup
from urllib import urlopen
from selenium import webdriver
import xlwt
import os
import threading
import re
import t... | Python | zaydzuhri_stack_edu_python |
string Reels application for download favorite reels
from instascrape import Reel
from app.utils import configure_logging
from app import HeaderEnum
set LOGGER = call configure_logging string ReelsApp:
class ReelsApp
begin
string Main class in the app
decorator staticmethod
function start_application
begin
string Funct... | """
Reels application for download favorite reels
"""
from instascrape import Reel
from app.utils import configure_logging
from app import HeaderEnum
LOGGER = configure_logging('ReelsApp:')
class ReelsApp:
"""Main class in the app"""
@staticmethod
def start_application():
"""Function init applicat... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Sep 30 22:29:27 2018 @author: Arpit
import os , csv
from scipy import sparse
import numpy as np
import matplotlib.pyplot as plt
string Returns the sparse version if it exists otherwise it loads the data, converts it to sparse and saves it... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 30 22:29:27 2018
@author: Arpit
"""
import os, csv
from scipy import sparse
import numpy as np
import matplotlib.pyplot as plt
"""
Returns the sparse version if it exists
otherwise it loads the data, converts it to sparse
and saves it for the futur... | Python | zaydzuhri_stack_edu_python |
function GetIncrements self
begin
Ellipsis
end function | def GetIncrements(self):
... | Python | nomic_cornstack_python_v1 |
function main
begin
set app = call QApplication argv
set window = call MainApp
show
call exec_
end function | def main():
app = QApplication(sys.argv)
window = MainApp()
window.show()
app.exec_() | Python | nomic_cornstack_python_v1 |
function delete_object_store_users self references=none ids=none names=none async_req=false _return_http_data_only=false _preload_content=true _request_timeout=none
begin
comment type: List[models.ReferenceType]
comment type: List[str]
comment type: List[str]
comment type: bool
comment type: bool
comment type: bool
com... | def delete_object_store_users(
self,
references=None, # type: List[models.ReferenceType]
ids=None, # type: List[str]
names=None, # type: List[str]
async_req=False, # type: bool
_return_http_data_only=False, # type: bool
_preload_content=True, # type: bool
... | Python | nomic_cornstack_python_v1 |
function _client_run self **kwargs
begin
call update_pending_deliveries
call listen wait=_socket_timeout keyword kwargs
return true
end function | def _client_run(self, **kwargs):
self._link.update_pending_deliveries()
self._connection.listen(wait=self._socket_timeout, **kwargs)
return True | Python | nomic_cornstack_python_v1 |
function create_loan_request self user payload
begin
assert is instance user User
assert is instance payload dict
set role = call Role role_id
comment Only create a loan request if the user is a borrower
if name == string BORROWER
begin
if not loan_request_ids
begin
comment Create the house
set house = call House paylo... | def create_loan_request(self, user, payload):
assert isinstance(user, User)
assert isinstance(payload, dict)
role = Role(user.role_id)
# Only create a loan request if the user is a borrower
if role.name == 'BORROWER':
if not user.loan_request_ids:
# ... | Python | nomic_cornstack_python_v1 |
comment Uses python3
import sys
function optimal_weight W n w value_dic
begin
if W == 0 or n == 0
begin
return 0
end
if tuple W n in value_dic
begin
return value_dic at tuple W n
end
comment 金条数组
for i in range 1 n + 1
begin
comment 总重量
for j in range 1 W + 1
begin
comment print ("kkk")
set value_dic at tuple j i = cal... | # Uses python3
import sys
def optimal_weight(W,n,w,value_dic):
if (W==0) or (n==0):
return 0
if (W,n) in value_dic:
return value_dic[(W,n)]
for i in range(1,n+1): #金条数组
for j in range(1,W+1): #总重量
#print ("kkk")
value_dic... | Python | zaydzuhri_stack_edu_python |
class Circle
begin
set pi = 3.14
function __init__ self redius
begin
set radius = redius
end function
function calculate_area self
begin
print string Aire du circle : pi * radius * radius
end function
end class
class Rectangle
begin
function __init__ self length width
begin
set length = length
set width = width
end fun... | class Circle:
pi = 3.14
def __init__(self, redius):
self.radius = redius
def calculate_area(self):
print("Aire du circle :", self.pi * self.radius * self.radius)
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def calcu... | Python | zaydzuhri_stack_edu_python |
function test_postcode_invalid self
begin
assert false call postcode_valid string N29 422AM
assert false call postcode_valid string N2# 422AM
assert false call postcode_valid string NART 4QL
assert false call postcode_valid string G13 4XIA
assert false call postcode_valid string PQ9 1J
assert false call postcode_valid ... | def test_postcode_invalid(self):
self.assertFalse(postcode_valid("N29 422AM"))
self.assertFalse(postcode_valid("N2# 422AM"))
self.assertFalse(postcode_valid("NART 4QL"))
self.assertFalse(postcode_valid("G13 4XIA"))
self.assertFalse(postcode_valid("PQ9 1J"))
self.assertFal... | Python | nomic_cornstack_python_v1 |
comment usr/bin/python
comment coding: UTF-8
import MySQLdb
set db = call connect string localhost string root string root string db_shane charset=string utf8
comment cursor游标对象
set cursor = call cursor
set sql = string select * from stu
try
begin
comment 执行sql语句
execute cursor sql
comment 获取数据
set result = call fetcha... | # usr/bin/python
# coding: UTF-8
import MySQLdb
db = MySQLdb.connect("localhost", "root", "root", "db_shane", charset='utf8' )
cursor = db.cursor() # cursor游标对象
sql = "select * from stu "
try:
cursor.execute(sql) # 执行sql语句
result = cursor.fetchall() # 获取数据
for row in result:
print(row)
except:
print("Error")
... | Python | zaydzuhri_stack_edu_python |
comment string,ch=input("enter string name and charcater:-\n").split(',')
comment print(f"\n\nname={string}\nno. of occurences={string.strip().lower().count(ch.strip().lower())}")
comment name=input("enter your name=")
comment i=0
comment while i<len(name):
comment print(f"{name[i]} : {name.count(name[i])}")
comment i+... | # string,ch=input("enter string name and charcater:-\n").split(',')
# print(f"\n\nname={string}\nno. of occurences={string.strip().lower().count(ch.strip().lower())}")
# name=input("enter your name=")
# i=0
# while i<len(name):
# print(f"{name[i]} : {name.count(name[i])}")
# i+=1
# name=input("ente... | Python | zaydzuhri_stack_edu_python |
function is_prime n
begin
if n <= 1
begin
return false
end
for i in range 2 integer n ^ 0.5 + 1
begin
if n % i == 0
begin
return false
end
end
return true
end function
set random_list = list comprehension random integer 0 10000 for _ in range 1000000
set prime_sum = sum generator expression num for num in random_list i... | def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
random_list = [random.randint(0, 10000) for _ in range(1000000)]
prime_sum = sum(num for num in random_list if is_prime(num))
| Python | greatdarklord_python_dataset |
function _execute_action_smb self action
begin
set samba = call application string fileTransfer dict
for _file in action at string files
begin
call smbCopy _file config at string applications at action at string application at string destination config at string applications at action at string application at string us... | def _execute_action_smb(self, action):
samba = self.guest.application("fileTransfer", {})
for _file in action['files']:
samba.smbCopy(_file, self.config['applications'][action['application']]['destination'],
self.config['applications'][action['applicat... | Python | nomic_cornstack_python_v1 |
function value_from_str self s
begin
try
begin
return integer s
end
except ValueError
begin
try
begin
return boolean s
end
except ValueError
begin
return default
end
end
end function | def value_from_str(self, s):
try:
return int(s)
except ValueError:
try:
return bool(s)
except ValueError:
return self.default | Python | nomic_cornstack_python_v1 |
comment I changed the variable in this example from
comment numbers in older versions of the book to nums
comment so the example fits on smaller devices. If you have an older
comment version of the book, you can email me at cory@theselftaughtprogrammer.io
comment and I will send you the newest version. Thank you so muc... | # I changed the variable in this example from
#
numbers in older versions of the book to nums
# so the example fits on smaller devices. If you have an older
# version of the book, you can email me at cory@theselftaughtprogrammer.io
# and I will send you the newest version. Thank you so much for purchasing my book!
... | Python | zaydzuhri_stack_edu_python |
comment MODELOS DE CLASIFICACION - SUBE, BAJA, SE MANTIENE
import pandas as pd
from datos_y_funciones.naragon_ml_model_functions import *
from datos_y_funciones.naragon_stock_prediction_util_functions import get_tickers_to_process , Mongo_stock_metadata
comment modelos ml de sklearn
from sklearn import svm , neighbors
... | #MODELOS DE CLASIFICACION - SUBE, BAJA, SE MANTIENE
import pandas as pd
from datos_y_funciones.naragon_ml_model_functions import *
from datos_y_funciones.naragon_stock_prediction_util_functions import get_tickers_to_process, Mongo_stock_metadata
#modelos ml de sklearn
from sklearn import svm, neighbors
from sklearn.en... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
string @param s: a string @return: an integer
function lengthOfLongestSubstring self s
begin
comment set() 函数创建一个无序不重复元素集
comment set.add() 添加元素
comment set.remove() 删除元素
comment 资料参考: https://liuzhichao.com/p/1645.html
comment Time complexity : O(2n) = O(n). In the worst case each character will
c... | class Solution:
"""
@param s: a string
@return: an integer
"""
def lengthOfLongestSubstring(self, s):
# set() 函数创建一个无序不重复元素集
# set.add() 添加元素
# set.remove() 删除元素
# 资料参考: https://liuzhichao.com/p/1645.html
# Time complexity : O(2n) = O(n). In the worst case ea... | Python | zaydzuhri_stack_edu_python |
comment !/bin/env python3
string finds how many coloured bags can eventually contain my shiny gold bag according to the rules of which coloured bags must be contained in which other coloured bags
import sys
import re
function solution filename
begin
comment read in input data
set input_data = list
with open filename a... | #!/bin/env python3
"""
finds how many coloured bags can eventually
contain my shiny gold bag according to the rules
of which coloured bags must be contained in
which other coloured bags
"""
import sys
import re
def solution(filename):
# read in input data
input_data = []
with open(filename) as f:
for x in f:
... | Python | zaydzuhri_stack_edu_python |
comment 0 1 1 2 3 5 8 13 21 34 55 89
set user_input = integer input string How many values do you want to have?
function fib n
begin
set number_1 = 0
set number_2 = 1
if n <= 0
begin
print string Not a valid number please try again
end
else
if n == 1
begin
print number_1
end
else
begin
print number_1
print number_2
for... | # 0 1 1 2 3 5 8 13 21 34 55 89
user_input = int(input("How many values do you want to have?"))
def fib(n):
number_1 = 0
number_2 = 1
if n <= 0:
print('Not a valid number please try again')
elif n == 1:
print(number_1)
else:
print(number_1)
print(number_2)
f... | Python | zaydzuhri_stack_edu_python |
function reverseWords self s
begin
reverse s
set tuple n i = tuple length s 0
while i < n
begin
set j = i
while j + 1 < n and s at j + 1 != string
begin
set j = j + 1
end
set s at slice i : j + 1 : = s at slice i : j + 1 : at slice : : - 1
set i = j + 2
end
end function | def reverseWords(self, s: List[str]) -> None:
s.reverse()
n, i = len(s), 0
while i < n:
j = i
while j + 1 < n and s[j + 1] != ' ':
j += 1
s[i:j + 1] = s[i:j + 1][::-1]
i = j + 2 | Python | nomic_cornstack_python_v1 |
import numpy as np
function hyperbolicFunction soma
begin
return exp soma - exp - soma / exp soma + exp - soma
end function
print call hyperbolicFunction 2.1
print call hyperbolicFunction - 1 | import numpy as np
def hyperbolicFunction(soma):
return (np.exp(soma) - np.exp(-soma)) / (np.exp(soma) + np.exp(-soma))
print(hyperbolicFunction(2.1))
print(hyperbolicFunction(-1)) | Python | zaydzuhri_stack_edu_python |
function make_request self request_type payload url_extras=list
begin
set s = call Session
update headers dict string Authorization string Bearer %s % access_token ; string Content-Type string application/json
set url = url_base + call get_url_end_string url_extras
comment print(url)
if request_type == POST
begin
set r... | def make_request(self, request_type: RequestTypes, payload: dict, url_extras: [str] = []) -> json:
s = requests.Session()
s.headers.update({
"Authorization": "Bearer %s" % self.access_token,
"Content-Type": "application/json"
})
url = self.url_base + self.get_... | Python | nomic_cornstack_python_v1 |
comment _author:"gang"
comment date: 2017/7/27
comment 简单的装饰函数
comment import time
comment import random
comment #装饰器
comment def timmer(func):
comment def wrapper():
comment start_time = time.time()
comment func()
comment end_time = time.time()
comment print('run time is %s' % (end_time - start_time))
comment return w... | #_author:"gang"
#date: 2017/7/27
#简单的装饰函数
# import time
# import random
#
# #装饰器
# def timmer(func):
# def wrapper():
# start_time = time.time()
# func()
# end_time = time.time()
# print('run time is %s' % (end_time - start_time))
# return wrapper
#
# #被装饰函数
# def index():
#
# ... | Python | zaydzuhri_stack_edu_python |
comment Definition for singly-linked list.
comment class ListNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution extends object
begin
function addTwoNumbers self l1 l2
begin
string :type l1: ListNode :type l2: ListNode :rtype: ListNode
if l1 is none
begin
return l2
... | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1... | Python | zaydzuhri_stack_edu_python |
comment open file
set file = open string hello.txt
comment open and write
set file = open string hello.txt string w
comment open and read
set file = open string hello.txt string r
comment open read, write both
set file = open string hello.txt string r+w
comment close opened file
close file | file = open("hello.txt") #open file
file = open("hello.txt",'w') #open and write
file = open("hello.txt",'r') #open and read
file = open("hello.txt",'r+w') #open read, write both
file.close() #close opened file
| Python | zaydzuhri_stack_edu_python |
function register_cls_list self cls_and_handler
begin
for tuple cls handler in cls_and_handler
begin
call register cls handler
end
call cache_clear
end function | def register_cls_list(self, cls_and_handler):
for cls, handler in cls_and_handler:
self._single_dispatch.register(cls, handler)
self.dispatch.cache_clear() | Python | nomic_cornstack_python_v1 |
function get_model self run_path options generator use_best=true
begin
set model_path = join run_path string model.h5
comment Load the model if it's saved, or create a new one.
if is file model_path
begin
set model = call load_model run_path options generator use_best
print string Continuing training from saved model.
... | def get_model(self, run_path, options, generator, use_best=True):
model_path = join(run_path, 'model.h5')
# Load the model if it's saved, or create a new one.
if isfile(model_path):
model = self.load_model(run_path, options, generator, use_best)
print('Continuing trainin... | Python | nomic_cornstack_python_v1 |
from bomb import Bomb
class Simulation
begin
function __init__ self num_modules minutes=0 seconds=0
begin
set bomb = call Bomb num_modules minutes seconds
end function
function pass_time self
begin
if call is_solved
begin
return false
end
if call has_strikes 3
begin
return false
end
return call pass_time
end function
f... | from bomb import Bomb
class Simulation:
def __init__(self,num_modules:int,minutes:int=0,seconds:int=0):
self.bomb = Bomb(num_modules,minutes,seconds)
def pass_time(self) -> bool:
if self.bomb.is_solved():
return False
if self.bomb.has_strikes(3):
return False
... | Python | zaydzuhri_stack_edu_python |
string This challenge is based on the game Minesweeper. Create a function that takes a grid of `#` and `-`, where each hash (#) represents a mine and each dash (-) represents a mine-free spot. Return a list where each dash is replaced by a digit indicating the number of mines immediately adjacent to the spot (horizonta... | """
This challenge is based on the game Minesweeper.
Create a function that takes a grid of `#` and `-`, where each hash (#)
represents a mine and each dash (-) represents a mine-free spot. Return a list
where each dash is replaced by a digit indicating the number of mines
immediately adjacent to the spot (horizonta... | Python | zaydzuhri_stack_edu_python |
function quest_info self user
begin
set key = get user at string party at string quest string key none
if string _id not in user at string party or key is none
begin
return none
end
for refresh in tuple false true
begin
set content = call Content api refresh
set quest = get content at string quests key none
if quest
be... | def quest_info(self, user):
key = user['party']['quest'].get('key', None)
if '_id' not in user['party'] or key is None:
return None
for refresh in False, True:
content = Content(self.api, refresh)
quest = content['quests'].get(key, None)
if quest:
... | Python | nomic_cornstack_python_v1 |
function pentagonal num
begin
return 5 * num ^ 2 - 5 * num + 2 / 2
end function | def pentagonal(num):
return (5*(num**2)-(5*num)+2)/2
| Python | zaydzuhri_stack_edu_python |
function start_browser
begin
info string Prepare virtual display...
set display = call Display visible=0 size=tuple 800 600
start display
info string Fire up headless browser...
set browser = call Browser
end function | def start_browser():
logger.info("Prepare virtual display...")
world.display = Display(visible=0, size=(800, 600))
world.display.start()
logger.info("Fire up headless browser...")
world.browser = Browser() | Python | nomic_cornstack_python_v1 |
function stop_area_players_logging
begin
comment Set logging trigger attribute to False
set _logging_thread = false
end function | def stop_area_players_logging():
# Set logging trigger attribute to False
MapVision._logging_thread = False | Python | nomic_cornstack_python_v1 |
function cancel_job self id=none
begin
set uri = format string /2012-09-25/jobs/{0} id
return call make_request string DELETE uri expected_status=202
end function | def cancel_job(self, id=None):
uri = '/2012-09-25/jobs/{0}'.format(id)
return self.make_request('DELETE', uri, expected_status=202) | Python | nomic_cornstack_python_v1 |
import sys
import heapq
set INF = 1000000000.0
set tuple V E = map int split read line stdin
set G = list comprehension list for _ in range V + 1
set K = integer read line stdin
for _ in range E
begin
set tuple start end distance = map int split read line stdin
append G at start list distance end
end
set result = list... | import sys
import heapq
INF = 1e9
V, E = map(int,sys.stdin.readline().split())
G = [[] for _ in range(V + 1)]
K = int(sys.stdin.readline())
for _ in range(E):
start, end, distance=map(int,sys.stdin.readline().split())
G[start].append([distance, end])
result = [INF for _ in range(V + 1)]
result[K] = 0
q = [... | Python | zaydzuhri_stack_edu_python |
function std_mean self
begin
set std = std
if ddof != 0
begin
comment ddof correction, (need copy of std)
set std = std * square root sum_weights - ddof / sum_weights
end
return std / square root sum_weights - 1
end function | def std_mean(self):
std = self.std
if self.ddof != 0:
# ddof correction, (need copy of std)
std = std * np.sqrt(
(self.sum_weights - self.ddof) / self.sum_weights
)
return std / np.sqrt(self.sum_weights - 1) | Python | nomic_cornstack_python_v1 |
function get_dev_asset_details_all auth url
begin
string Takes no input to fetch device assett details from HP IMC RESTFUL API :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dict... | def get_dev_asset_details_all(auth, url):
"""Takes no input to fetch device assett details from HP IMC RESTFUL API
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list ... | Python | jtatman_500k |
from collections import namedtuple
set Mood_filter = named tuple string Mood_filter list string lower_bound string upper_bound
function available_moods
begin
return keys _moods
end function
function _hype_filter
begin
return call Mood_filter lower_bound=string 2/3 upper_bound=string 1
end function
function _chill_filte... | from collections import namedtuple
Mood_filter = namedtuple('Mood_filter',
['lower_bound',
'upper_bound'])
def available_moods():
return _moods.keys()
def _hype_filter():
return Mood_filter(lower_bound='2/3', upper_bound='1')
def _chill_filter():
ret... | Python | zaydzuhri_stack_edu_python |
function __init__ self *args **kwds
begin
if args or kwds
begin
call __init__ *args keyword kwds
comment message fields cannot be None, assign default values for those that are
if position is none
begin
set position = call Point
end
if approach is none
begin
set approach = call Vector3
end
if binormal is none
begin
set... | def __init__(self, *args, **kwds):
if args or kwds:
super(GraspConfig, self).__init__(*args, **kwds)
# message fields cannot be None, assign default values for those that are
if self.position is None:
self.position = geometry_msgs.msg.Point()
if self.approach is None:
self.ap... | Python | nomic_cornstack_python_v1 |
import requests
from util import util
function getUsers token
begin
set r = post string https://slack.com/api/users.list data=dict string token token
set response = call getJSON r string Error in getting user list
comment Iterate through each user
set usernames = dict
for member in response at string members
begin
set... | import requests
from util import util
def getUsers(token):
r = requests.post('https://slack.com/api/users.list', data = {'token': token});
response = util.getJSON(r, "Error in getting user list")
# Iterate through each user
usernames = {};
for member in response["members"]:
member_id = member["id"];
member_... | Python | zaydzuhri_stack_edu_python |
string * Copyright 2020, Departamento de sistemas y Computación * Universidad de Los Andes * * * Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the ... | """
* Copyright 2020, Departamento de sistemas y Computación
* Universidad de Los Andes
*
*
* Desarrolado para el curso ISIS1225 - Estructuras de Datos y Algoritmos
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
... | Python | zaydzuhri_stack_edu_python |
import gym
set env = call make string MountainCarContinuous-v0
call reset
set action = random sample
print action
set tuple state reward done _ = step env action
print state reward done _
print action_space observation_space
string action float (hitotu) state リストで状態変数(2つ) reward 報酬(float) done _ info(必要なさそう、dict) env.a... | import gym
env = gym.make('MountainCarContinuous-v0')
env.reset()
action = env.action_space.sample()
print(action)
state, reward, done, _ = env.step(action)
print(state, reward, done, _)
print(env.action_space, env.observation_space)
"""
action float (hitotu)
state リストで状態変数(2つ)
reward 報酬(float)
done
_ info(必要なさそう、d... | Python | zaydzuhri_stack_edu_python |
function _popupMenuRequest self pos
begin
set sender = call sender
call setFocus
call emit call _context sender pos
end function | def _popupMenuRequest(self, pos):
sender = self.sender()
sender.setFocus()
self.popupMenuRequest.emit(self._context(sender), pos) | Python | nomic_cornstack_python_v1 |
function printerC dic coding off
begin
if is instance dic dict
begin
print
end
end function | def printerC(dic, coding, off):
if isinstance(dic, dict):
print | Python | zaydzuhri_stack_edu_python |
function sound_id self sound_id
begin
if sound_id is none
begin
raise call ValidationError string Sound ID must not be none
end
else
if not is instance sound_id int
begin
raise call ValidationError string Sound ID must be an integer.
end
call set_input string sound_id sound_id
end function | def sound_id(self, sound_id):
if sound_id is None:
raise ValidationError("Sound ID must not be none")
elif not isinstance(sound_id, int):
raise ValidationError("Sound ID must be an integer.")
self.set_input("sound_id", sound_id) | Python | nomic_cornstack_python_v1 |
function key_from_ireq ireq
begin
if req is none and link is not none
begin
return string link
end
else
begin
return call key_from_req req
end
end function | def key_from_ireq(ireq):
if ireq.req is None and ireq.link is not None:
return str(ireq.link)
else:
return key_from_req(ireq.req) | Python | nomic_cornstack_python_v1 |
function getCreatedTime self
begin
return string parse time tweet at string created_at string %a %b %d %H:%M:%S +0000 %Y
end function | def getCreatedTime(self):
return datetime.strptime(self.tweet["created_at"], '%a %b %d %H:%M:%S +0000 %Y') | Python | nomic_cornstack_python_v1 |
from typing import List
from pprint import pprint
class Solution
begin
function generateMatrix self n
begin
set tuple l r t b = tuple 0 n - 1 0 n - 1
set num = 1
set res = list comprehension list 0 * n for __ in range n
while num <= n * n
begin
for i in range l r + 1
begin
set res at t at i = num
set num = num + 1
end
... | from typing import List
from pprint import pprint
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
l, r, t, b = 0, n-1, 0, n-1
num = 1
res = [[0]*n for __ in range(n)]
while num <= n*n:
for i in range(l, r+1):
res[t][i] = num
... | Python | zaydzuhri_stack_edu_python |
function lyric_collector track_lst artist_lst
begin
set lyric_lst = list
comment Iterate through tracks and store lyrics
for tuple t a in call tqdm zip track_lst artist_lst
begin
set song = call search_song title=t artist=a get_full_info=false
if song is not none
begin
append lyric_lst lyrics
end
else
begin
append lyr... | def lyric_collector(track_lst,artist_lst):
lyric_lst = []
# Iterate through tracks and store lyrics
for t, a in tqdm(zip(track_lst, artist_lst)):
song = genius.search_song(title = t,
artist = a,
get_full_info = False)
if song is not None:
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Given a non-empty array of integers, return the k most frequent elements. For example, Given [1,1,1,2,2,3] and k = 2, return [1,2]. Note: You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Your algorithm's time complexity must be better than O(n log n), where n is ... | # -*- coding: utf-8 -*-
"""
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the a... | Python | zaydzuhri_stack_edu_python |
string Experiment using Linear GPR on freesurfer volume data. Results: MAE: Mean(SD) = 6.132(0.096)
from pathlib import Path
import joblib
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import KFold , GridSearchCV... | """
Experiment using Linear GPR on freesurfer volume data.
Results:
MAE: Mean(SD) = 6.132(0.096)
"""
from pathlib import Path
import joblib
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import KFold, GridSearch... | Python | zaydzuhri_stack_edu_python |
function text_to_code self text
begin
set code = list
for character in text
begin
append code key_to_value at character
end
print text code
return code
end function | def text_to_code(self, text):
code = []
for character in text:
code.append(self.key_to_value[character])
print(text, code)
return code | Python | nomic_cornstack_python_v1 |
async function set_app_pin self pin
begin
await call set_app_pin name pin
end function | async def set_app_pin(self, pin: bool) -> None:
await self.AD.threading.set_app_pin(self.name, pin) | Python | nomic_cornstack_python_v1 |
function testSomeColumnsMissing self subprocessMock
begin
set return_value = string JOBID ST
set error = string ^Required columns \(NODELIST\(REASON\), TIME\) not found in 'squeue -u %s' output$ % call getlogin
call assertRaisesRegex self SQueueError error SQueue
end function | def testSomeColumnsMissing(self, subprocessMock):
subprocessMock.return_value = 'JOBID ST\n'
error = (
'^Required columns \(NODELIST\(REASON\), TIME\) not found in '
"'squeue -u %s' output$" % getlogin())
assertRaisesRegex(self, SQueueError, error, SQueue) | Python | nomic_cornstack_python_v1 |
function state self
begin
return get pulumi self string state
end function | def state(self) -> pulumi.Output[str]:
return pulumi.get(self, "state") | Python | nomic_cornstack_python_v1 |
function disruption_reason self
begin
return _disruption_reason
end function | def disruption_reason(self):
return self._disruption_reason | Python | nomic_cornstack_python_v1 |
class ABCD
begin
set MAX_MEMBER = 10
function __init__ self name
begin
set name = name
set member = list string 한성일 string 김수진
end function
function join self name
begin
if call __len__ < MAX_MEMBER
begin
append member name
print string 반갑습니다. + name
end
else
begin
print name + string 님 죄송합니다.! 정원이 만땅입니다.
end
end funct... | class ABCD:
MAX_MEMBER = 10
def __init__(self, name):
self.name = name
self.member = ["한성일", "김수진"]
def join(self, name):
if self.member.__len__() < ABCD.MAX_MEMBER:
self.member.append(name)
print("반갑습니다." + name)
else:
print(name + "님 죄... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string Lockboxes Method
function canUnlockAll boxes
begin
string Determines if all the boxes can be opened
set keys = list 0
for key in keys
begin
comment loop through the keys
set box = boxes at key
for nkey in box
begin
comment get the new key in each box
if nkey not in keys and nkey < lengt... | #!/usr/bin/python3
""" Lockboxes Method """
def canUnlockAll(boxes):
""" Determines if all the boxes can be opened """
keys = [0]
for key in keys:
# loop through the keys
box = boxes[key]
for nkey in box:
# get the new key in each box
if nkey not in keys an... | Python | zaydzuhri_stack_edu_python |
from twitter_scraper import get_tweets
import markovify
import twitter
from twitter import *
import random
import time
comment Twitter API settings
comment These are in our Discord server!
comment DO NOT COMMIT TO GIT WITH THE API KEYS
set api = call Api consumer_key=string fZpJFlF9Fe8z1adti8V0j0Zlt consumer_secret=str... | from twitter_scraper import get_tweets
import markovify
import twitter
from twitter import *
import random
import time
# Twitter API settings
# These are in our Discord server!
# DO NOT COMMIT TO GIT WITH THE API KEYS
api = twitter.Api(consumer_key='fZpJFlF9Fe8z1adti8V0j0Zlt',
consumer_secret='L2kqz... | Python | zaydzuhri_stack_edu_python |
function test_create_bios_policy self
begin
pass
end function | def test_create_bios_policy(self):
pass | Python | nomic_cornstack_python_v1 |
function copy_as_curl self
begin
set curl_headers = string
for tuple header value in headers
begin
set curl_headers = curl_headers + format string -H '{}: {}' header value
end
set curl_data = string
if operation in tuple string POST string PUT
begin
set curl_data = format string --data '{}' data
end
set curl_cmd = fo... | def copy_as_curl(self):
curl_headers = ''
for header, value in self.headers:
curl_headers += "-H '{}: {}' ".format(header, value)
curl_data = ''
if self.operation in ('POST', 'PUT'):
curl_data = "--data '{}' ".format(self.data)
curl_cmd = "curl '{}' {} {}-... | Python | nomic_cornstack_python_v1 |
function close self
begin
raise call NotImplementedError string Use a specific writer or the `get_writer` method.
end function | def close(self):
raise NotImplementedError("Use a specific writer or the `get_writer` method.") | Python | nomic_cornstack_python_v1 |
from fractions import Fraction
set A = list
comment n=int(input("2x2 or 3x3 : "))
set n = 3
set a = 0
for i in range n
begin
set B = list
for j in range n
begin
set a = a + i + j
comment print(i+1,j+1,end=" ")
comment a=int(input("Enter Number : "))
append B a
end
append A B
end
print A
set B = list
append B A
set C... | from fractions import Fraction
A=[]
# n=int(input("2x2 or 3x3 : "))
n=3
a=0
for i in range(n):
B=[]
for j in range(n):
a+=i+j
# print(i+1,j+1,end=" ")
# a=int(input("Enter Number : "))
B.append(a)
A.append(B)
print(A)
B=[]
B.append(A)
C=[]
if n == 2 :
... | Python | zaydzuhri_stack_edu_python |
import unittest
from creds3 import paddedInt
class TestPadLeft extends TestCase
begin
function test_zero self
begin
set i = 0
assert equal call paddedInt i string 0 * 19
end function
function test_ten self
begin
set i = 10
assert equal call paddedInt i call zfill 19
end function
function test_arbitrary_number self
begi... | import unittest
from creds3 import paddedInt
class TestPadLeft(unittest.TestCase):
def test_zero(self):
i = 0
self.assertEqual(paddedInt(i), "0" * 19)
def test_ten(self):
i = 10
self.assertEqual(paddedInt(i), str(i).zfill(19))
def test_arbitrary_number(self):
i = ... | Python | jtatman_500k |
function enable_disable_tpg self num_iterations num_tpgids num_tags tx_port rx_port
begin
set tags = call get_tpg_tags qinq=false max_tag=num_tags + 1
comment one packet just to warmup the memory
set warmup_streams = call get_streams 1 1 qinq=false vlans=num_tags pkt_size=100
call reset ports=list tx_port rx_port
for _... | def enable_disable_tpg(self, num_iterations, num_tpgids, num_tags, tx_port, rx_port):
tags = self.get_tpg_tags(qinq=False, max_tag=num_tags+1)
warmup_streams = self.get_streams(1, 1, qinq=False, vlans=num_tags, pkt_size=100) # one packet just to warmup the memory
self.c.reset(ports=[tx_port, r... | Python | nomic_cornstack_python_v1 |
function replace_domain email old_domain new_domain
begin
if string @ + old_domain in email
begin
set index = index email string @ + old_domain
set new_email = email at slice : index : + string @ + new_domain
return new_email
end
return email
end function
set thea = call replace_domain string tdcforonda@mymail.mapua.... | def replace_domain(email, old_domain, new_domain):
if "@" + old_domain in email:
index = email.index("@" + old_domain)
new_email = email[:index] + "@" + new_domain
return new_email
return email
thea = replace_domain("tdcforonda@mymail.mapua.edu.ph", "mymail.mapua.edu.ph", "mapua.edu.ph"... | Python | zaydzuhri_stack_edu_python |
function restore self
begin
string Restore a soft-deleted model instance.
if call _fire_model_event string restoring is false
begin
return false
end
set attribute self call get_deleted_at_column none
call set_exists true
set result = save
call _fire_model_event string restored
return result
end function | def restore(self):
"""
Restore a soft-deleted model instance.
"""
if self._fire_model_event("restoring") is False:
return False
setattr(self, self.get_deleted_at_column(), None)
self.set_exists(True)
result = self.save()
self._fire_model_ev... | Python | jtatman_500k |
from Snake import *
import pickle
import random
class QL
begin
function __init__ self size
begin
set size = size
set snake = call SnakeGame size
call reset
set q = dict
end function
comment def reward(self, action):
comment cpy = self.s.copy()
function load self file
begin
set temp = load pickle file
set snake = snake... | from Snake import *
import pickle
import random
class QL:
def __init__(self, size):
self.size = size
self.snake = SnakeGame(size)
self.snake.reset()
self.q = {}
# def reward(self, action):
# cpy = self.s.copy()
def load(self, file):
temp = ... | Python | zaydzuhri_stack_edu_python |
function fillna self value=none method=none limit=none
begin
from pandas.api.types import is_array_like
from pandas.util._validators import validate_fillna_kwargs
from pandas.core.missing import pad_1d , backfill_1d
set tuple value method = call validate_fillna_kwargs value method
set mask = call isna
if call is_array_... | def fillna(self, value=None, method=None, limit=None):
from pandas.api.types import is_array_like
from pandas.util._validators import validate_fillna_kwargs
from pandas.core.missing import pad_1d, backfill_1d
value, method = validate_fillna_kwargs(value, method)
mask = self.isn... | Python | nomic_cornstack_python_v1 |
function getValueAt *args
begin
return call OutSineFunction_getValueAt *args
end function | def getValueAt(*args):
return _osgAnimation.OutSineFunction_getValueAt(*args) | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
comment -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import unittest
from ltltrans.ltlparser.ltl_parser import LtlDictBuilder
call basicConfig level=INFO format=string %(message)s
class ParseLtlTest extends TestCase
begin
function setUp self
begin
set dict_b... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import unittest
from ltltrans.ltlparser.ltl_parser import LtlDictBuilder
logging.basicConfig(level=logging.INFO, format="%(message)s")
class ParseLtlTest(unittest.TestCase):
def setUp(self):
self.dic... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import csv
function load_distance coloum_name
begin
set distance_dict = dictionary
with open string ./data_distance/distance_ + coloum_name + string .csv newline=string as csvfile
begin
set reader = reader csvfile
for row in reader
begin
update distance_dict dict round decimal row at 2 5 row at 1
en... | import pandas as pd
import csv
def load_distance(coloum_name):
distance_dict = dict()
with open('./data_distance/distance_' + coloum_name + ".csv", newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
distance_dict.update({round(float(row[2]),5): row[1]})
re... | Python | zaydzuhri_stack_edu_python |
from random import *
from tkinter import *
from tkinter import messagebox
set W = list
set Z = list
set var_chk = 0
set tabela = list
set escolha = list
comment funcao que gera o traco mealy
function geramealy entrada saida sequencia
begin
set cont = 0
for x in range 0 25
begin
set p = length sequencia - 1
if x <= ... | from random import *
from tkinter import *
from tkinter import messagebox
W = []
Z = []
var_chk = 0
tabela = []
escolha = []
#funcao que gera o traco mealy
def geramealy(entrada,saida,sequencia):
cont = 0
for x in range(0, 25):
p = (len(sequencia)-1)
if (x <= len(sequencia)-2):
saida.append(0... | Python | zaydzuhri_stack_edu_python |
comment ---------------------------------------------------------------------#
comment This script is a more generalized TAMSAT-ALERT risk assessment tool.
comment Dagmawi Teklu Asfaw
comment November, 2017
comment ---------------------------------------------------------------------#
import numpy as np
import datetime... | #---------------------------------------------------------------------#
# This script is a more generalized TAMSAT-ALERT risk assessment tool.
# Dagmawi Teklu Asfaw
# November, 2017
#---------------------------------------------------------------------#
import numpy as np
import datetime as dt
import os
import matplotl... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.