code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function test_CombatInfo_post_cant_post_invalid_death_save_failure self
begin
set client = call APIClient
set score_data = dict string armor_class 15 ; string initiative 2 ; string speed 30 ; string total_hit_points 20 ; string current_hit_points 17 ; string temporary_hit_points 0 ; string hit_dice_total 1 ; string hit... | def test_CombatInfo_post_cant_post_invalid_death_save_failure(self):
client = APIClient()
score_data = {
"armor_class": 15,
"initiative": 2,
"speed": 30,
"total_hit_points": 20,
"current_hit_points": 17,
"temporary_hit_points": 0,
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
import pygeons
from mpl_toolkits.basemap import Basemap
import h5py
from matplotlib.colors import ListedColormap
from matplotlib.patches import Ellipse
from matplotlib.cm import viridis
from myplot.colorbar import pseudo_transparent_cmap , transparent_colorbar
from sym... | import numpy as np
import matplotlib.pyplot as plt
import pygeons
from mpl_toolkits.basemap import Basemap
import h5py
from matplotlib.colors import ListedColormap
from matplotlib.patches import Ellipse
from matplotlib.cm import viridis
from myplot.colorbar import pseudo_transparent_cmap,transparent_colorbar
from sympy... | Python | zaydzuhri_stack_edu_python |
function _check self
begin
set c2 = call _loggedErrors
assert equal length c2 2
call trap ZeroDivisionError
call flushLoggedErrors ZeroDivisionError
end function | def _check(self):
c2 = self._loggedErrors()
self.assertEqual(len(c2), 2)
c2[1]["failure"].trap(ZeroDivisionError)
self.flushLoggedErrors(ZeroDivisionError) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Fri Apr 17 08:10:08 2020 @author: lzx3x3
import pandas as pd
import numpy as np
import statistics
set df = read csv string reviews_of_100_restaurants
comment df.photos = df.photos.replace('', 0)
set friends = extract str string (\d+)
set number_reviews = extract str strin... | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 08:10:08 2020
@author: lzx3x3
"""
import pandas as pd
import numpy as np
import statistics
df = pd.read_csv('reviews_of_100_restaurants')
# df.photos = df.photos.replace('', 0)
df.friends = df.friends.str.extract('(\d+)')
df.number_reviews = df.number... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
comment Cria a Series notas sem especificar index
set notas = call Series list 7.5 8.0 9.5 6.0
print string Notas >>>
print notas
print string -----------
comment Cria a Series alunos especificando index
set lst_matriculas = list string M01 string M02 string M03 string M04
set lst_nomes = list strin... | import pandas as pd
#Cria a Series notas sem especificar index
notas = pd.Series([7.5, 8.0, 9.5, 6.0])
print("Notas >>>");
print(notas);
print("-----------");
#Cria a Series alunos especificando index
lst_matriculas = ['M01','M02','M03','M04']
lst_nomes = ['Seinfeld','George','Kramer','Elaine']
alunos = pd.Series(lst... | Python | zaydzuhri_stack_edu_python |
function autocorr x lag=1
begin
set S = call autocov x lag
return S at tuple 0 1 / square root call prod call diag S
end function | def autocorr(x, lag=1):
S = autocov(x, lag)
return S[0, 1]/np.sqrt(np.prod(np.diag(S))) | Python | nomic_cornstack_python_v1 |
string https://adventofcode.com/2017/day/1
function reverse_captcha halfway=false
begin
with open string input.txt string r as input
begin
set captcha = replace read input string string
set result = 0
set shift = if expression halfway then length captcha / 2 else 1
for tuple index n in enumerate captcha
begin
set next... | '''
https://adventofcode.com/2017/day/1
'''
def reverse_captcha(halfway=False):
with open("input.txt", 'r') as input:
captcha = input.read().replace('\n', "")
result = 0
shift = len(captcha) / 2 if halfway else 1
for index, n in enumerate(captcha):
next = int((index + s... | Python | zaydzuhri_stack_edu_python |
comment load in packages
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from linepart import partition_img , convo_edge_det
from img_to_gray import to_gray
from clustering import turnCartoon
comment read in image
set img = call imread string ../Reef.jpg
comment print out shape of im... | # load in packages
import numpy as np
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from linepart import partition_img, convo_edge_det
from img_to_gray import to_gray
from clustering import turnCartoon
# read in image
img = mpimg.imread("../Reef.jpg")
# print out shape of image
imshape = np.shape(i... | Python | zaydzuhri_stack_edu_python |
function header_value self
begin
return get pulumi self string header_value
end function | def header_value(self) -> pulumi.Input[str]:
return pulumi.get(self, "header_value") | Python | nomic_cornstack_python_v1 |
function submit self dispatcher tracker domain
begin
set tea = call get_slot string tea
set temperature = call get_slot string temperature
set sugar = call get_slot string sugar
set userMess = latest_message
print string 用户输入: { userMess }
call utter_message format string {}{}的{} 马上为您送上 temperature sugar tea
return lis... | def submit(
self,
dispatcher: CollectingDispatcher,
tracker: Tracker,
domain: Dict[Text, Any],
) -> List[Dict]:
tea = tracker.get_slot('tea')
temperature = tracker.get_slot('temperature')
sugar = tracker.get_slot('sugar')
userMess = tracker.latest_mess... | Python | nomic_cornstack_python_v1 |
function SetTranslatedCommentText self comment language
begin
set callResult = call _Call string SetTranslatedCommentText comment language
end function | def SetTranslatedCommentText(self, comment, language):
callResult = self._Call("SetTranslatedCommentText", comment, language) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
comment orm delete command test for assignment 3
comment Assume student's db constructor, connect, and close are working.
comment Assume student's orm basic functionality (orm basic test) is working.
import asst3
import socket
import tester
import importlib
set asst3_schema = call load_module ... | #!/usr/bin/python3
#
# orm delete command test for assignment 3
# Assume student's db constructor, connect, and close are working.
# Assume student's orm basic functionality (orm basic test) is working.
#
import asst3
import socket
import tester
import importlib
asst3_schema = asst3.load_module('asst3_schema')
TOTAL... | Python | zaydzuhri_stack_edu_python |
import pyautogui
import cv2
import os
import time
import ftplib
class RDPUtil
begin
function __init__ self
begin
pass
end function
function get_ftp self server username passwd
begin
set ftp = call FTP server
call login username passwd
return ftp
end function
function upload_ftp self ftp filename
begin
comment ftp = sel... | import pyautogui
import cv2
import os
import time
import ftplib
class RDPUtil:
def __init__(self):
pass
def get_ftp(self, server, username, passwd):
ftp = ftplib.FTP(server)
ftp.login(username, passwd)
return ftp
def upload_ftp(self, ftp, filename):
... | Python | zaydzuhri_stack_edu_python |
string Program Title: utilities.py Author: Mike Brice Last Modified: Thu Sep 27, 2018 Description: All the utility functions for SDSS_Stellar_Spectra package are found here
comment =============================================================================
comment Imports
comment =====================================... | '''
Program Title:
utilities.py
Author:
Mike Brice
Last Modified:
Thu Sep 27, 2018
Description:
All the utility functions for SDSS_Stellar_Spectra package are found here
'''
# =============================================================================
# Imports
# ===================... | Python | zaydzuhri_stack_edu_python |
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
from docx.shared import Inches
from docx.shared import Length
from docx.text.run import Font
from docx.table import Table
from tkinter import *
from tkinter.filedialog import *
from imr import ingresoMinimo
from numeraliz... | from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
from docx.shared import Inches
from docx.shared import Length
from docx.text.run import Font
from docx.table import Table
from tkinter import *
from tkinter.filedialog import *
from imr import ingresoMinimo
from numeraliz... | Python | zaydzuhri_stack_edu_python |
comment BASIC FUNCTIONS
import cv2
import numpy as np
set kernel = ones tuple 5 5 uint8
comment GET IMAGE IN GRAY IMAGE:
set img = call imread string model.jpg
set imgGray = call cvtColor img COLOR_BGR2GRAY
image show string Gray Image imgGray
comment GET IMAGE IN BLUR IMAGE:
set imgBlur = call GaussianBlur imgGray tup... | #BASIC FUNCTIONS
import cv2
import numpy as np
kernel=np.ones((5,5),np.uint8)
#GET IMAGE IN GRAY IMAGE:
img= cv2.imread("model.jpg")
imgGray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray Image",imgGray)
#GET IMAGE IN BLUR IMAGE:
imgBlur=cv2.GaussianBlur(imgGray,(7,7),0)
cv2.imshow("Blur Image",imgBlur... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python3
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
from numpy.random import choice
from random import choices
import numpy as np
import itertools
import operator
import random
import copy
class Select
begin
function __init__ self
begin
set itaretion = 0
set parent = 0
... | #! /usr/bin/env python3
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
from numpy.random import choice
from random import choices
import numpy as np
import itertools
import operator
import random
import copy
class Select():
def __init__(self):
self.itaretion=0
... | Python | zaydzuhri_stack_edu_python |
function search self word
begin
set node = root
for char in word
begin
if char not in node
begin
return false
end
set node = node at char
end
return string end in node
end function | def search(self, word):
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return 'end' in node | Python | nomic_cornstack_python_v1 |
function auth_url self perms frob
begin
set encoded = call encode_and_sign dict string api_key api_key ; string frob frob ; string perms perms
return string http://%s%s?%s % tuple flickr_host flickr_auth_form encoded
end function | def auth_url(self, perms, frob):
encoded = self.encode_and_sign({
"api_key": self.api_key,
"frob": frob,
"perms": perms})
return "http://%s%s?%s" % (FlickrAPI.flickr_host, \
FlickrAPI.flickr_auth_form, encoded) | Python | nomic_cornstack_python_v1 |
if a == b == c
begin
print 3 * a + b + c
end
else
begin
print a + b + c
end | if a==b==c:
print(3*(a+b+c))
else:
print(a+b+c)
| Python | zaydzuhri_stack_edu_python |
string File: noise.py Author: Calvin Huang/Lupita Sahu Github: https://github.com/dovermore Description: This is part of the assignment one for Advanced machine learning it integrates sklearn like interface and constructs basic noise adding module.
import numpy as np
from sklearn.base import TransformerMixin
class Salt... | """
File: noise.py
Author: Calvin Huang/Lupita Sahu
Github: https://github.com/dovermore
Description: This is part of the assignment one for Advanced machine learning
it integrates sklearn like interface and constructs basic noise adding module.
"""
import numpy as np
from sklearn.base import TransformerMi... | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
class QNetwork extends Module
begin
function __init__ self input_dim output_dim hidden_dim
begin
string DQN Network Args: input_dim (int): `state` dimension. `state` is 2-D tensor of shape (n, input_dim) output_dim (int): Number of actions. Q_value is 2-D tensor of shape (n, output_di... | import torch
import torch.nn as nn
class QNetwork(nn.Module):
def __init__(self, input_dim, output_dim, hidden_dim) -> None:
"""DQN Network
Args:
input_dim (int): `state` dimension.
`state` is 2-D tensor of shape (n, input_dim)
output_dim (int): Number of ac... | Python | zaydzuhri_stack_edu_python |
comment name.strip() #soluciona el problema de los espacios, eliminando los espacios a la derecha y a izquierda
comment si solo quiero eliminar los espacios de la izquierda es lstrip()
comment si solo quiero eliminar los espacios de la derecha es rstrip()
print string esta es la longitud del nombre: length name
comment... | #name.strip() #soluciona el problema de los espacios, eliminando los espacios a la derecha y a izquierda
#si solo quiero eliminar los espacios de la izquierda es lstrip()
#si solo quiero eliminar los espacios de la derecha es rstrip()
print("esta es la longitud del nombre: ",len(name))
print(f"tiene {character} {nam... | Python | zaydzuhri_stack_edu_python |
import unittest
from datetime import datetime
import html_scanner
class TestScannerOlivian extends TestCase
begin
function setUp self
begin
set test_markup = open string data/olivian.html
set scanner = call ScannerOlivian
end function
function test_get_units self
begin
set result = call get_units test_markup
assert equ... | import unittest
from datetime import datetime
import html_scanner
class TestScannerOlivian(unittest.TestCase):
def setUp(self):
self.test_markup = open('data/olivian.html')
self.scanner = html_scanner.ScannerOlivian()
def test_get_units(self):
result = self.scanner.get_units(self.te... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment После завершения работы с файлом, его нужно закрыть. В некоторых случаях Python может самостоятельно закрыть файл.
comment Но лучше на это не рассчитывать и закрывать файл явно.
comment close() - закрытие файла
set f = open string r1.txt string r
print read f
comment У объекта file... | # -*- coding: utf-8 -*-
#После завершения работы с файлом, его нужно закрыть. В некоторых случаях Python может самостоятельно закрыть файл.
# Но лучше на это не рассчитывать и закрывать файл явно.
#close() - закрытие файла
f = open('r1.txt', 'r')
print(f.read())
#У объекта file есть специальный атрибут closed, которы... | Python | zaydzuhri_stack_edu_python |
function __init__ self cat_name
begin
call __init__ cat_name
end function | def __init__(self, cat_name):
super(Cat, self).__init__(cat_name) | Python | nomic_cornstack_python_v1 |
function hour_pixel hour
begin
set val = if expression hour < 12 then hour else hour - 12
return val * 5
end function | def hour_pixel(hour):
val = hour if hour<12 else hour -12
return val * 5 | Python | nomic_cornstack_python_v1 |
function urlparse self url
begin
set _url = deep copy url
if url at slice 0 : 5 : == string https
begin
set _url = call https_to_s3 url
end
if _url at slice 0 : 5 : != string s3://
begin
raise exception string Invalid S3 url %s % _url
end
set url_obj = split replace _url string s3:// string string /
comment remove em... | def urlparse(self, url):
_url = deepcopy(url)
if url[0:5] == 'https':
_url = self.https_to_s3(url)
if _url[0:5] != 's3://':
raise Exception('Invalid S3 url %s' % _url)
url_obj = _url.replace('s3://', '').split('/')
# remove empty items
url_obj = ... | Python | nomic_cornstack_python_v1 |
function get_custom_datatype_triples
begin
set custom_datatypes = call get_custom_datatypes
from osp.core.namespaces import _namespace_registry
set result = call Graph
for d in custom_datatypes
begin
add result tuple d type Datatype
set pattern = tuple none range d
for tuple s p o in call triples pattern
begin
add resu... | def get_custom_datatype_triples():
custom_datatypes = get_custom_datatypes()
from osp.core.namespaces import _namespace_registry
result = rdflib.Graph()
for d in custom_datatypes:
result.add((d, rdflib.RDF.type, rdflib.RDFS.Datatype))
pattern = (None, rdflib.RDFS.range, d)
for s,... | Python | nomic_cornstack_python_v1 |
function run _
begin
set fscad = call ModuleType string fscad.fscad
set __path__ = list directory name path real path path __file__
set modules at string fscad.fscad = fscad
for key in __all__
begin
call __setattr__ key globals at key
end
end function | def run(_):
fscad = types.ModuleType("fscad.fscad")
fscad.__path__ = [os.path.dirname(os.path.realpath(__file__))]
sys.modules['fscad.fscad'] = fscad
for key in __all__:
fscad.__setattr__(key, globals()[key]) | Python | nomic_cornstack_python_v1 |
function __getitem__ self index
begin
set indexes = indexes at slice index * batch_size : index + 1 * batch_size :
set batch_baskets = user_baskets at indexes
set batch_metadata = user_metadata at indexes
comment Counts of elements in each of the baskets in batch
set batch_counts = user_baskets_count at indexes
set ba... | def __getitem__(self, index):
indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]
batch_baskets = self.user_baskets[indexes]
batch_metadata = self.user_metadata[indexes]
# Counts of elements in each of the baskets in batch
batch_counts = self.user_bask... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
from threading import Thread
from time import sleep
import tkinter
import tkinter.messagebox
function main
begin
class DownloadTask extends Thread
begin
function run self
begin
sleep 10
call showinfo string 提示 string 下载完成
end function
end class
function download... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from threading import Thread
from time import sleep
import tkinter
import tkinter.messagebox
def main():
class DownloadTask(Thread):
def run(self):
sleep(10)
tkinter.messagebox.showinfo('提示', '下载完成')
def download():
# 禁用按... | Python | zaydzuhri_stack_edu_python |
async function test_listener_close endpoint_error_handling
begin
if call get_ucx_version < tuple 1 10 0 and endpoint_error_handling is true
begin
skip string Endpoint error handling is only supported for UCX >= 1.10
end
async function client_node listener
begin
set ep = await call create_endpoint call get_address port ... | async def test_listener_close(endpoint_error_handling):
if ucp.get_ucx_version() < (1, 10, 0) and endpoint_error_handling is True:
pytest.skip("Endpoint error handling is only supported for UCX >= 1.10")
async def client_node(listener):
ep = await ucp.create_endpoint(
ucp.get_addres... | Python | nomic_cornstack_python_v1 |
function setAllLayersVisible self visible
begin
set layers = call ls type=string displayLayer
for layer in layers
begin
if ends with layer LAYER_SUFFIX
begin
set attribute string %s.visibility % layer visible
end
end
end function | def setAllLayersVisible(self, visible):
layers = cmds.ls( type='displayLayer')
for layer in layers:
if layer.endswith(self.LAYER_SUFFIX):
cmds.setAttr('%s.visibility' % layer, visible) | Python | nomic_cornstack_python_v1 |
function pack_to_dict self
begin
if root is none
begin
return none
end
else
begin
set node_queue = list
set dict_queue = list
append node_queue root
set dict_pack = call dict_form
append dict_queue dict_pack
while length node_queue
begin
set q_node = pop node_queue 0
set dict_get = pop dict_queue 0
if left is not none
... | def pack_to_dict(self):
if self.root is None:
return None
else:
node_queue = list()
dict_queue = list()
node_queue.append(self.root)
dict_pack = self.root.dict_form()
dict_queue.append(dict_pack)
while len(node_queue):
... | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
set return_str = string
comment iterate through products the user is allowed use
for tuple key value in items products
begin
if currency_type == string eur
begin
set return_str = return_str + format string {} €{} key value
end
else
if currency_type == string usd
begin
set return_str = retur... | def __str__(self):
return_str = ''
for key, value in self.products.items(): # iterate through products the user is allowed use
if self.currency_type == 'eur':
return_str += "{} €{}\n".format(key, value)
elif self.currency_type == 'usd':
return_... | Python | nomic_cornstack_python_v1 |
function checkPermutationByCounting self string1 string2
begin
set freq = dict
if length string1 != length string2
begin
return false
end
comment incrementing Freq count
for i in string1
begin
if i in freq
begin
set freq at i = freq at i + 1
end
else
begin
set freq at i = 1
end
end
comment decrementing Freq count
for ... | def checkPermutationByCounting(self, string1, string2):
freq = {}
if len(string1) != len(string2):
return False
# incrementing Freq count
for i in string1:
if i in freq:
freq[i] += 1
else:
freq[i] = 1
# decrem... | Python | nomic_cornstack_python_v1 |
import sys
import time
import copy
import turtle
print string 1 to get the blank board
print string Which method do you want to use?
print string 2-minimax 3-alpha beta
print string press 4 to get all the statistics(R1-R12)
set c = integer strip call raw_input
if c == 1
begin
class Pen extends Turtle
begin
function __i... | import sys
import time
import copy
import turtle
print("1 to get the blank board")
print("Which method do you want to use?")
print("2-minimax 3-alpha beta")
print ("press 4 to get all the statistics(R1-R12)")
c = int(raw_input().strip())
if c == 1:
class Pen(turtle.Turtle):
def __init... | Python | zaydzuhri_stack_edu_python |
import RPi.GPIO as GPIO
import time
call setmode BOARD
set pir = 12
setup GPIO pir IN | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
pir = 12
GPIO.setup(pir, GPIO.IN) | Python | zaydzuhri_stack_edu_python |
comment Desarrollar un programa que indique lo que genera un esquema piramidal como Amway o Herbalife
function maxLvl replicacion totalHab
begin
set nivelMax = 0
while replicacion ^ nivelMax < totalHab
begin
set nivelMax = nivelMax + 1
end
return print format string Se repite {} veces nivelMax
end function
call maxLvl ... | # Desarrollar un programa que indique lo que genera un esquema piramidal como Amway o Herbalife
def maxLvl(replicacion, totalHab):
nivelMax = 0
while replicacion**nivelMax < totalHab:
nivelMax += 1
return print('Se repite {} veces'.format(nivelMax))
maxLvl(2, 2890000) | Python | zaydzuhri_stack_edu_python |
class Solution
begin
string Cleaner solution, but *MARGINALLY* slower Time: 87%-93% (120ms)
function countNegatives self grid
begin
set length = length grid at 0
set count = 0
for row in grid
begin
for i in range 0 length
begin
if row at i < 0
begin
set count = count + length - i
break
end
end
end
return count
end func... | class Solution:
"""
Cleaner solution, but *MARGINALLY* slower
Time: 87%-93% (120ms)
"""
def countNegatives(self, grid: List[List[int]]) -> int:
length = len(grid[0])
count = 0
for row in grid:
for i in range(0,length):
if row[i] < 0:
... | Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ self data
begin
set data = data
set prev = none
set next = none
end function
end class
class DoublyLinkedList
begin
function __init__ self
begin
set head = none
set tail = none
end function
function addNodeAtBeginning self data
begin
set newNode = call Node data
if head is none
begin
... | class Node:
def __init__(self, data):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def addNodeAtBeginning(self, data):
newNode = Node(data)
if self.head is None:
... | Python | jtatman_500k |
function get_issues_data org query_limit
begin
set variables = dict string search_query string org: { org } ; string size query_limit
set query = call get_data_query string graphql/issues_data.gql
return call get_data query variables
end function | def get_issues_data(org, query_limit):
variables = {
"search_query": f"org:{org}",
"size": query_limit,
}
query = get_data_query('graphql/issues_data.gql')
return get_data(query, variables) | Python | nomic_cornstack_python_v1 |
class Result extends object
begin
function __init__ self result=none error=none
begin
set is_success = error is none
set result = result
set error = error
end function
function unwrap self
begin
if is_success
begin
return result
end
return none
end function
decorator classmethod
function ok cls result
begin
return call... | class Result(object):
def __init__(self, result=None, error=None):
self.is_success = error is None
self.result = result
self.error = error
def unwrap(self):
if self.is_success:
return self.result
return None
@classmethod
def ok(cls, result):
... | Python | zaydzuhri_stack_edu_python |
function get self
begin
set limit = get args string limit
set radio_name = get args string radio_name
set tuple start end = call validate_date_range
return call get_tracks_per_date_reviewed_per_radio start_date=start end_date=end radio_name=radio_name end_id=limit
end function | def get(self):
limit = request.args.get('limit')
radio_name = request.args.get('radio_name')
start, end = validate_date_range()
return track.Track.get_tracks_per_date_reviewed_per_radio(start_date=start, end_date=end,
radi... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
function jobDirPath fileName jobName=none
begin
return join path call getJobDir jobName fileName
end function | def jobDirPath(fileName, jobName=None):
return os.path.join(getJobDir(jobName), fileName) | Python | nomic_cornstack_python_v1 |
function get_orphan_images_without_use self
begin
set images_in_use = call get_imageset_othertenants string orphan_image
set orphan_images = set generator expression id for image in values call get_images if string orphan_image in properties
return orphan_images - images_in_use
end function | def get_orphan_images_without_use(self):
images_in_use = self.get_imageset_othertenants('orphan_image')
orphan_images = set(image.id for image in self.get_images().values()
if 'orphan_image' in image.properties)
return orphan_images - images_in_use | Python | nomic_cornstack_python_v1 |
function random_search X y loss score_func search_config n_epochs=1000 n_iter=10
begin
set best_score = - decimal string inf
for _ in range n_iter
begin
set configs = call generate_configs search_config
set model = call build_model configs
set kfold = call StratifiedKFold n_splits=4 shuffle=true
set scores = list
for ... | def random_search(X, y, loss, score_func, search_config,
n_epochs=1000, n_iter=10):
best_score = -float('inf')
for _ in range(n_iter):
configs = generate_configs(search_config)
model = build_model(configs)
kfold = StratifiedKFold(n_splits=4, shuffle=True)
scor... | Python | nomic_cornstack_python_v1 |
function _get_component_code self data
begin
return _component_code
end function | def _get_component_code(self, data) -> ComponentCodes:
return self._component_code | Python | nomic_cornstack_python_v1 |
import random
import string
import os
set dire = string C:/Users/solda/Downloads/correo.txt
function randomString stringLength=10
begin
set letters = ascii_lowercase
return join string generator expression random choice letters for i in range stringLength
end function
set file = open dire string w
for i in range 100
b... | import random
import string
import os
dire = "C:/Users/solda/Downloads/correo.txt"
def randomString(stringLength = 10):
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(stringLength))
file = open(dire, "w")
for i in range(100):
file.write("\nCorreo: " + randomString(... | Python | zaydzuhri_stack_edu_python |
function test_sessionProperties self
begin
set session = call session
set value = list string 123 dict string 12 123
call setProperty string key value
call setProperty string key2 string hello
assert equal tuple call getProperty string key call getProperty string key2 call hasProperty string key call hasProperty string... | def test_sessionProperties(self):
session = self.mdk.session()
value = ["123", {"12": 123}]
session.setProperty("key", value)
session.setProperty("key2", "hello")
self.assertEqual((session.getProperty("key"), session.getProperty("key2"),
session.hasPrope... | Python | nomic_cornstack_python_v1 |
function bezier_unit_tangent seg t
begin
string Returns the unit tangent of the segment at t. Notes ----- If you receive a RuntimeWarning, try the following: >>> import numpy >>> old_numpy_error_settings = numpy.seterr(invalid='raise') This can be undone with: >>> numpy.seterr(**old_numpy_error_settings)
assert 0 <= t ... | def bezier_unit_tangent(seg, t):
"""Returns the unit tangent of the segment at t.
Notes
-----
If you receive a RuntimeWarning, try the following:
>>> import numpy
>>> old_numpy_error_settings = numpy.seterr(invalid='raise')
This can be undone with:
>>> numpy.seterr(**old_numpy_error_set... | Python | jtatman_500k |
function load_image filename
begin
try
begin
set image = load image filename
end
except message
begin
raise message
end
set image = call convert
return image
end function | def load_image(filename):
try:
image = pygame.image.load(filename)
except pygame.error.message:
raise SystemExit.message
image = image.convert()
return image | Python | nomic_cornstack_python_v1 |
while grow
begin
set inc = false
set grow = false
for i in range n
begin
if h at i == 0
begin
set inc = false
end
else
begin
set h at i = h at i - 1
if not inc
begin
set inc = true
set grow = true
set cnt = cnt + 1
end
end
end
end
print cnt | while grow:
inc = False
grow = False
for i in range(n):
if h[i] == 0:
inc = False
else:
h[i] -= 1
if not inc:
inc = True
grow = True
cnt += 1
print(cnt)
| Python | zaydzuhri_stack_edu_python |
comment Original realization in Damnae's Storybrew
comment https://github.com/Damnae/storybrew/blob/master/common/Animations/EasingFunctions.cs
import math
set Reverse = lambda func value -> 1 - call func 1 - value
set ToInOut = lambda func value -> 0.5 * if expression value < 0.5 then call func 2 * value else 2 - call... | # Original realization in Damnae's Storybrew
# https://github.com/Damnae/storybrew/blob/master/common/Animations/EasingFunctions.cs
import math
Reverse = lambda func, value: 1 - func(1 - value)
ToInOut = lambda func, value: 0.5 * (func(2 * value) if value < 0.5 else 2 - func(2 - 2 * value))
Linear = lambda x: x
QuadIn... | Python | zaydzuhri_stack_edu_python |
function getItemTypeCode self
begin
return call ListOfParameters_getItemTypeCode self
end function | def getItemTypeCode(self):
return _libsbml.ListOfParameters_getItemTypeCode(self) | Python | nomic_cornstack_python_v1 |
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.decomposition import PCA
comment You can add the parameter data_home to wherever to where you want to download your data
set dataset = read csv string Iris.csv
set x = iloc at tuple slice : : list 1 2 3 4
set y = iloc at tuple slic... | from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.decomposition import PCA
# You can add the parameter data_home to wherever to where you want to download your data
dataset = pd.read_csv('Iris.csv')
x = dataset.iloc[:,[1,2,3,4]]
y = dataset.iloc[:,-1]
from sklearn.preproce... | Python | zaydzuhri_stack_edu_python |
function create_invoice self request obj
begin
if obj
begin
set result = call create_invoice
if result
begin
call message_user request format string Rechnung {} erfolgreich erstellt. result
set state = string 3
save
set r = format string admin:{}_{}_change app_label model_name
return call redirect reverse r args=tuple ... | def create_invoice(self, request, obj):
if obj:
result = obj.create_invoice()
if result:
self.message_user(request, u"Rechnung {} erfolgreich erstellt.".format(result))
obj.state = '3'
obj.save()
r = 'admin:{}_{}_change'.for... | Python | nomic_cornstack_python_v1 |
from app.config.main import config
from io import BytesIO
import emails
class Mailer
begin
set __config = none
set __html = none
set __text = none
set __subject = none
set __from_email = none
set __from_name = none
set __to = none
set __cc = none
set __bcc = none
set __files_attachments = list
set __strings_attachment... | from app.config.main import config
from io import BytesIO
import emails
class Mailer:
__config = None
__html = None
__text = None
__subject = None
__from_email = None
__from_name = None
__to = None
__cc = None
__bcc = None
__files_attachments = []
__strings_attachments = [... | Python | zaydzuhri_stack_edu_python |
string 2 dimensional array of colors given . Find the largest group of colors touching. [[R,B,B,B,G], [ R,B,G,G,R], ==> Answer is B , as 5 B's are touching each othre [ R,B,R,R,G]]
set a = list list string R string B string B string B string G list string R string B string B string B string R list string R string B str... | '''
2 dimensional array of colors given . Find the largest group of colors touching.
[[R,B,B,B,G],
[ R,B,G,G,R], ==> Answer is B , as 5 B's are touching each othre
[ R,B,R,R,G]]
'''
a = [['R', 'B', 'B', 'B', 'G'],
['R', 'B', 'B', 'B', 'R'],
['R', 'B', 'R', 'R', 'G']]
'''
t = [['R', 'B', 'B', 'B', 'R'],
... | Python | zaydzuhri_stack_edu_python |
function test_out_farewell self
begin
comment Prepare test
set player_name = name
comment Run test
call out_farewell
comment Evaluate test
set calls = list call OUT_MSG_THANKS call format OUT_MSG_GOODBYE name
call has_call calls
end function | def test_out_farewell(self):
# Prepare test
self.console.player_name = self.name
# Run test
self.console.out_farewell()
# Evaluate test
calls = [
call(i18n.OUT_MSG_THANKS),
call(i18n.OUT_MSG_GOODBYE.format(self.name))
]
self.conso... | Python | nomic_cornstack_python_v1 |
function after_run self run_context run_values
begin
add pbar 1
end function | def after_run(self, run_context, run_values):
self.pbar.add(1) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment Author: Dale Housler
comment OS: UNIX & WINDOWS
comment ConformationFolders.py
comment This program creates the folders for conformation files
comment The user runs this program by selecting misc menu from the proCLic Menu
import os
import re
import shutil
set confDirs = list
funct... | #!/usr/bin/env python
#Author: Dale Housler
#OS: UNIX & WINDOWS
# ConformationFolders.py
#This program creates the folders for conformation files
#The user runs this program by selecting misc menu from the proCLic Menu
import os
import re
import shutil
confDirs = []
def moveFINALConf_files(confDirs):
start_dir... | Python | zaydzuhri_stack_edu_python |
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
set text = string I am wondering what is the best way to learn English.
set text = lower text
set tokens = call word_tokenize text
set stop_words = set call words string english
set filtered_token... | import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.probability import FreqDist
text = "I am wondering what is the best way to learn English."
text = text.lower()
tokens = word_tokenize(text)
stop_words = set(stopwords.words('english'))
filtered_tokens = [word for word ... | Python | jtatman_500k |
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import pandas as pd
from tqdm import tqdm
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import ElementClickInterceptedExceptio... | import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import pandas as pd
from tqdm import tqdm
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import ElementClickInterceptedExcepti... | Python | zaydzuhri_stack_edu_python |
function unlines line
begin
return call translate call maketrans string string
end function | def unlines(line):
return line.translate(str.maketrans('\n', ' ')) | Python | nomic_cornstack_python_v1 |
function get_xy_reset coef1 coef2 xold yold
begin
comment Funnel line with coef1
comment TODO: Understand why it breaks with xold < l_helipad and xold > r_heli
if xold < 0
begin
set b1 = coef1 * l_heli
set m1 = - coef1
comment Coef of the perpendicular line
set m2 = 1 / coef2
end
else
if xold > 0
begin
set b1 = - coef1... | def get_xy_reset(coef1, coef2, xold, yold):
# Funnel line with coef1
# TODO: Understand why it breaks with xold < l_helipad and xold > r_heli
if xold < 0:
b1 = coef1 * utils.l_heli
m1 = - coef1
m2 = 1 / coef2 # Coef of the perpendicular line
elif xold > 0:
b1 = -coef1 *... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment !/usr/bin/python
comment 构建 GitHub的兴趣图
string 度中心性(Degree Centrality) 中介中心性/中间中心性(Between Centrality) 接近中心性(Closeness Centrality)
from operator import itemgetter
from github import Github
import networkx as nx
import sys
set ACCESS_TOKEN = string 23777b727db037245ee9c9815775b3fe4c7... | # -*- coding: utf-8 -*-
# !/usr/bin/python
#构建 GitHub的兴趣图
'''
度中心性(Degree Centrality)
中介中心性/中间中心性(Between Centrality)
接近中心性(Closeness Centrality)
'''
from operator import itemgetter;
from github import Github;
import networkx as nx;
import sys;
ACCESS_TOKEN = '23777b727db037245ee9c9815775b3fe4c7e390c';
#USER = 'xian... | Python | zaydzuhri_stack_edu_python |
import numpy
import random
import math
set data = list
set weidhts = list
set volumes = list
set values = list
set file = open string 15.txt
for line in file
begin
append data split line
end
set maxVolume = decimal data at 0 at 1
set maxWeight = decimal data at 0 at 0
del data at 0
for item in data
begin
append wei... | import numpy
import random
import math
data=[]
weidhts=[]
volumes=[]
values=[]
file = open('15.txt')
for line in file:
data.append(line.split())
maxVolume = float(data[0][1])
maxWeight = float(data[0][0])
del data[0]
for item in data:
weidhts.append(float(item[0]))
volumes.append(float(item... | Python | zaydzuhri_stack_edu_python |
function eval_rank_bytimediff test_ds tss forecasts prediction_length
begin
set carlist = list
comment carno-lap# -> elapsed_time[] array
set forecasts_et = dictionary
set ds_iter = iterate test_ds
for idx in range length test_ds
begin
set test_rec = next ds_iter
comment global carid
set carno = decode_carids at test_... | def eval_rank_bytimediff(test_ds,tss,forecasts,prediction_length):
carlist = []
# carno-lap# -> elapsed_time[] array
forecasts_et = dict()
ds_iter = iter(test_ds)
for idx in range(len(test_ds)):
test_rec = next(ds_iter)
#global carid
carno = decode_carids[test_rec['feat_s... | Python | nomic_cornstack_python_v1 |
import time
import numpy as np
import tensorflow as tf
from model.model import Model
from utils.general_utils import get_minibatches
import tensorflow.contrib.layers as layers
function fire_module x inp sp e11p e33p
begin
with call variable_scope string fire
begin
with call variable_scope string squeeze
begin
set W = c... | import time
import numpy as np
import tensorflow as tf
from model.model import Model
from utils.general_utils import get_minibatches
import tensorflow.contrib.layers as layers
def fire_module(x,inp,sp,e11p,e33p):
with tf.variable_scope("fire"):
with tf.variable_scope("squeeze"):
W = tf.get_v... | Python | zaydzuhri_stack_edu_python |
function license self license
begin
set _license = license
end function | def license(self, license):
self._license = license | Python | nomic_cornstack_python_v1 |
function cheapestJump coins maxJump
begin
set n = length coins
set dp = list decimal string inf * n
set parent = list - 1 * n
set dp at 0 = coins at 0
for i in range n
begin
if coins at i == - 1
begin
continue
end
for j in range 1 maxJump + 1
begin
if i + j >= n
begin
break
end
set next = i + j
set cost = coins at next... | def cheapestJump(coins, maxJump):
n = len(coins)
dp = [float('inf')] * n
parent = [-1] * n
dp[0] = coins[0]
for i in range(n):
if coins[i] == -1:
continue
for j in range(1, maxJump + 1):
if i + j >= n:
break
next = i + j
... | Python | jtatman_500k |
comment ! /usr/bin/env python
import math
from movingres import CheckToMove , TotalRes
class Technologies
begin
set Techs = dict string Energy 0 ; string Laser 0 ; string Ion 0 ; string Hyperspace 0 ; string Plasma 0 ; string CombustionDrive 0 ; string ImpulseDrive 0 ; string HyperDrive 0 ; string Espionage 0 ; string ... | #! /usr/bin/env python
import math
from movingres import CheckToMove, TotalRes
class Technologies():
Techs = {'Energy':0,'Laser':0,'Ion':0,'Hyperspace':0,'Plasma':0,'CombustionDrive':0
,'ImpulseDrive':0,'HyperDrive':0,'Espionage':0,'Computer':0,'Astrophysics':0
,'IGRN':0,'Grav':0,'Weapons':... | Python | zaydzuhri_stack_edu_python |
from sys import stdin , stdout
comment Rating: ~ 3.4 / 10
comment Link: https://open.kattis.com/problems/houselawn
function main
begin
set lines = read lines stdin
set tuple l m = map int split lines at 0
set valid = dict
for i in range 1 m + 1
begin
set line = split strip lines at i string ,
set n = line at 0
set tup... | from sys import stdin, stdout
# Rating: ~ 3.4 / 10
# Link: https://open.kattis.com/problems/houselawn
def main():
lines = stdin.readlines()
l, m = map(int, lines[0].split())
valid = {}
for i in range(1, m + 1):
line = lines[i].strip().split(',')
n = line[0]
p, c, t, r = map(int, line[1:])
to... | Python | zaydzuhri_stack_edu_python |
function get_register_value raw_value log2m
begin
set substream_value = call unsigned_right_shift_long raw_value log2m
if substream_value == 0
begin
comment The paper does not cover p(0x0), so the special value 0 is used.
comment 0 is the original initialization value of the registers, so by
comment doing this the HLL ... | def get_register_value(raw_value, log2m):
substream_value = BitUtil.unsigned_right_shift_long(raw_value, log2m)
if substream_value == 0:
# The paper does not cover p(0x0), so the special value 0 is used.
# 0 is the original initialization value of the registers, so by
# doing this the HL... | Python | nomic_cornstack_python_v1 |
if score1 < score2
begin
print string player1 wins
set player1Wins = player1Wins + 1
set player2Losses = player2Losses + 1
end
else
if score1 > score2
begin
print string player2 wins
set player2Wins = player2Wins + 1
set player1Losses = player1Losses + 1
end
else
begin
print string tie
set tieCount = tieCount + 1
end | if score1 < score2:
print('player1 wins');
player1Wins +=1;
player2Losses +=1;
elif score1 > score2:
print('player2 wins');
player2Wins +=1;
player1Losses +=1;
else:
print('tie');
tieCount += 1;
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
comment USAGE EXAMPLE:
comment to get top submissions:
comment python crawler.py -t -v
comment or to get hot submissions:
comment python crawler.py -l -v
comment or to get a single submissions:
comment python crawler.py -s id -v
import argparse
import praw
import c... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# USAGE EXAMPLE:
# to get top submissions:
# python crawler.py -t -v
# or to get hot submissions:
# python crawler.py -l -v
# or to get a single submissions:
# python crawler.py -s id -v
import argparse
import praw
import csv
import codecs
import time
from functions import *... | Python | zaydzuhri_stack_edu_python |
function __init__ self response_input=none schema_registry_url=none
begin
set _request = none
set _response_internal = none
set _schema_registry_url = schema_registry_url
set _tstamp2frameannsidx = dict
if is instance response_input Request
begin
set _request = response_input
call _init_from_request
end
else
if is ins... | def __init__(self, response_input=None, schema_registry_url=None):
self._request = None
self._response_internal = None
self._schema_registry_url = schema_registry_url
self._tstamp2frameannsidx = {}
if isinstance(response_input, Request):
self._request = response_inpu... | Python | nomic_cornstack_python_v1 |
function judge self trial measurements
begin
call _verify_trial trial
return call judge transform transformed_space trial measurements
end function | def judge(self, trial: Trial, measurements: Any) -> dict | None:
self._verify_trial(trial)
return self.algorithm.judge(
self.transformed_space.transform(trial), measurements
) | Python | nomic_cornstack_python_v1 |
function max_level self
begin
return max array list I dtype=int8
end function | def max_level(self):
return np.max(np.array(list(self.I), dtype=np.int8)) | Python | nomic_cornstack_python_v1 |
function add x
begin
return x + 2
end function
set newlist = list 10 20 30 40 50
set result = list map add newlist
print result | def add (x):
return x + 2
newlist = [10,20,30,40,50]
result = list(map(add,newlist))
print(result) | Python | zaydzuhri_stack_edu_python |
comment type: (Union[int, float]) -> Union[int, float]
function easeInOutQuint n
begin
call _checkRange n
set n = n * 2
if n < 1
begin
return 0.5 * n ^ 5
end
else
begin
set n = n - 2
return 0.5 * n ^ 5 + 2
end
end function | def easeInOutQuint(n): # type: (Union[int, float]) -> Union[int, float]
_checkRange(n)
n *= 2
if n < 1:
return 0.5 * n**5
else:
n -= 2
return 0.5 * (n**5 + 2) | Python | nomic_cornstack_python_v1 |
set nombre = input string Ingrese su Nombre:
print nombre
print type nombre | nombre = input("Ingrese su Nombre: ")
print (nombre)
print (type(nombre)) | Python | zaydzuhri_stack_edu_python |
function test_hashverify_ok_glob self
begin
call dbgfunc
try
begin
set glop = string /home/tpb/hic_test/hash*
set h = call HSI verbose=string verbose in call testargs
comment make sure the hashables all have a checksum stored
set x = call hashlist plist
for path in plist
begin
if string \(?none\)? %s % path in x
begin
... | def test_hashverify_ok_glob(self):
self.dbgfunc()
try:
glop = "/home/tpb/hic_test/hash*"
h = hpss.HSI(verbose=("verbose" in testhelp.testargs()))
# make sure the hashables all have a checksum stored
x = h.hashlist(self.plist)
for path in self.... | Python | nomic_cornstack_python_v1 |
import sys
import argparse
import math
set parser = call ArgumentParser description=string Loan calculator
call add_argument string --type type=str help=string Type of Payment
call add_argument string --principal type=float help=string The Principal amount
call add_argument string --periods type=float help=string No. o... | import sys
import argparse
import math
parser = argparse.ArgumentParser(description='Loan calculator')
parser.add_argument('--type', type=str, help='Type of Payment')
parser.add_argument('--principal', type=float, help='The Principal amount')
parser.add_argument('--periods', type=float, help='No. of months needed to re... | Python | zaydzuhri_stack_edu_python |
function process filename
begin
with open filename string r encoding=string UTF-8 as f
begin
comment 키 : 알파벳, 값 : 빈도수
set dict = dict
set data = read f
for i in data
begin
if i in dict
begin
set dict at i = dict at i + 1
end
else
begin
set dict at i = 1
end
end
end
return dict
end function
set dict = process string in... | def process(filename):
with open(filename, "r", encoding='UTF-8') as f:
# 키 : 알파벳, 값 : 빈도수
dict = {}
data = f.read()
for i in data:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
return dict
dict = process("input.txt")
# 빈도수를 ... | Python | zaydzuhri_stack_edu_python |
from json import JSONEncoder , JSONDecodeError , loads , dump
import product
comment define the Encoder class used in serialization
class Encoder extends JSONEncoder
begin
string from a Python object we need to obtain a json representation
comment also encode the type of the object
function default self o
begin
set res... | from json import JSONEncoder, JSONDecodeError, loads, dump
import product
# define the Encoder class used in serialization
class Encoder(JSONEncoder):
""" from a Python object we need to obtain a json representation"""
# also encode the type of the object
def default(self, o):
result = o.__dict_... | Python | zaydzuhri_stack_edu_python |
function test_xyzp_qm_7a
begin
set subject = subject7
with raises MoleculeFormatError
begin
set tuple final intermed = call from_string subject return_processed=true dtype=string psi4
end
end function | def test_xyzp_qm_7a():
subject = subject7
with pytest.raises(qcdb.MoleculeFormatError):
final, intermed = qcdb.molparse.from_string(subject, return_processed=True, dtype='psi4') | Python | nomic_cornstack_python_v1 |
function min_val node
begin
set cur = node
while left is not none
begin
set cur = left
end
return cur
end function | def min_val(node):
cur = node
while cur.left is not None:
cur = cur.left
return cur | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string Solution for the Advent of Code challenge 2016, day 16.
set __author__ = string Serge Beaumont
set __date__ = string December 2016
set INPUT = string 11110010111001001
set FILL_LENGTH = 272
set FILL_LENGTH_PART_2 = 35651584
function dragonize s
begin
set reverse = join string list c... | #!/usr/bin/env python
"""Solution for the Advent of Code challenge 2016, day 16."""
__author__ = "Serge Beaumont"
__date__ = "December 2016"
INPUT = "11110010111001001"
FILL_LENGTH = 272
FILL_LENGTH_PART_2 = 35651584
def dragonize(s):
reverse = ''.join(['1' if x == '0' else '0' for x in s[::-1]])
return "{0... | Python | zaydzuhri_stack_edu_python |
function save_as_json self json_path
begin
set data = dict
for company in self
begin
set df = copy data
set index = map str
set data at ticker = loads to json df
end
with open json_path string w as file
begin
dump data file indent=4 sort_keys=true
end
end function | def save_as_json(self,json_path):
data = {}
for company in self:
df = company.data.copy()
df.index = df.index.map(str)
data[company.ticker] = json.loads(df.to_json())
with open(json_path, 'w') as file:
json.dump(data, file,indent = 4,sort_keys = ... | Python | nomic_cornstack_python_v1 |
function test_set_power self
begin
set motor = motor_set at string front_left
set power = 0
assert power == 0
set power = 50
assert power == 50
end function | def test_set_power(self):
motor = self.motor_set['front_left']
motor.power = 0
assert motor.power == 0
motor.power = 50
assert motor.power == 50 | Python | nomic_cornstack_python_v1 |
function convertToColors self guess
begin
set guessInColorsList = list
for item in guess
begin
if item == string 0
begin
append guessInColorsList string grey
end
else
if item == string 1
begin
append guessInColorsList string white
end
else
if item == string 2
begin
append guessInColorsList string black
end
else
if ite... | def convertToColors(self, guess):
guessInColorsList = []
for item in guess:
if item == '0':
guessInColorsList.append('grey')
elif item == '1':
guessInColorsList.append('white')
elif item == '2':
guessInColorsList.append(... | Python | nomic_cornstack_python_v1 |
function __init__ self folder
begin
set charLocPath = join path folder string cascade/char/char_single.xml
set modelRecognitionPath = list join path folder string dnn/SegmenationFree-Inception.prototxt join path folder string dnn/SegmenationFree-Inception.caffemodel
set modelFineMappingPath = list join path folder stri... | def __init__(self, folder):
charLocPath = os.path.join(folder, "cascade/char/char_single.xml")
modelRecognitionPath = [os.path.join(folder, "dnn/SegmenationFree-Inception.prototxt"), os.path.join(folder, "dnn/SegmenationFree-Inception.caffemodel")]
modelFineMappingPath = [os.path.join(folder, "... | Python | nomic_cornstack_python_v1 |
function acquire self
begin
if not call trylock
begin
call SMlog string Failed to lock %s on first attempt, % lockpath + string blocked by PID %d % call test
lock
end
if VERBOSE
begin
call SMlog string lock: acquired %s % lockpath
end
end function | def acquire(self):
if not self.lock.trylock():
util.SMlog("Failed to lock %s on first attempt, " % self.lockpath
+ "blocked by PID %d" % self.lock.test())
self.lock.lock()
if VERBOSE:
util.SMlog("lock: acquired %s" % self.lockpath) | Python | nomic_cornstack_python_v1 |
function parse file
begin
try
begin
return call parseFile file parseAll=true
end
except ParseException as e
begin
print line
print string * column - 1 + string ^
print e
raise e
end
end function | def parse(file):
try:
return parser(file).parseFile(file, parseAll=True)
except pyparsing.ParseException as e:
print(e.line)
print(" " * (e.column - 1) + "^")
print(e)
raise e | Python | nomic_cornstack_python_v1 |
comment This file represents the Schema for our Database. We have two MongoDB documents - Webpages and QueryWords.
comment Webpages
comment The webpages document is created for each webpage in the corpus. It stores the docID, url, title and a dictionary of tokens with their frequency
comment The webpage document also c... | #This file represents the Schema for our Database. We have two MongoDB documents - Webpages and QueryWords.
##Webpages
#The webpages document is created for each webpage in the corpus. It stores the docID, url, title and a dictionary of tokens with their frequency
#The webpage document also caches the total number of ... | Python | zaydzuhri_stack_edu_python |
function complete_xml_element self xmlnode doc
begin
string Complete the XML node with `self` content. :Parameters: - `xmlnode`: XML node with the element being built. It has already right name and namespace, but no attributes or content. - `doc`: document to which the element belongs. :Types: - `xmlnode`: `libxml2.xml... | def complete_xml_element(self, xmlnode, doc):
"""Complete the XML node with `self` content.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but no attributes or content.
- `doc`: document to which the elemen... | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.