code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function _checkoutProject shortName syncSpecs environment=string testing
begin
set environmentSuffix = call _getEnvironmentSuffix environment
set serverBaseUrl = string https://svn + environmentSuffix + string .inkling.com/svn/
set serverUrl = serverBaseUrl + shortName + string /trunk
set destinationPath = call _getRep... | def _checkoutProject(shortName, syncSpecs, environment='testing'):
environmentSuffix = _getEnvironmentSuffix(environment)
serverBaseUrl = 'https://svn' + environmentSuffix + '.inkling.com/svn/'
serverUrl = serverBaseUrl + shortName + '/trunk'
destinationPath = _getRepoPath(shortName, environment)
l... | Python | nomic_cornstack_python_v1 |
from p5 import *
import numpy as np
set asteroids = list
set location = 0
set asteroid_velocity = 5
set fires = list
function setup
begin
global asteroids
size 800 800
for _ in range 20
begin
set x = random integer - 400 400
set y = random integer - 800 - 400
append asteroids call asteroid x y
end
end function
functi... | from p5 import *
import numpy as np
asteroids=[]
location=0
asteroid_velocity=5
fires=[]
def setup():
global asteroids
size(800,800)
for _ in range(20):
x=np.random.randint(-400,400)
y=np.random.randint(-800,-400)
asteroids.append(asteroid(x,y))
def draw():
global fire_velocity,... | Python | zaydzuhri_stack_edu_python |
import turtle
import time
import sys
from vector import Vector
from math import pi , cos , sin
set tuple I J K = tuple call Vector 1 0 0 call Vector 0 1 0 call Vector 0 0 1
class Shape extends object
begin
function __init__ self start_point *args
begin
call make_vertices start_point *args
end function
function make_ver... | import turtle
import time
import sys
from vector import Vector
from math import pi, cos, sin
I, J, K = Vector(1, 0, 0), Vector(0, 1, 0), Vector(0, 0, 1)
class Shape(object):
def __init__(self, start_point, *args):
self.make_vertices(start_point, *args)
def make_vertices(self, start_point, *args):
self.vertices... | Python | zaydzuhri_stack_edu_python |
function test_double_command_registration self
begin
comment TODO: move these common lists to setup_class
set alias = list string potato string cannon string Fodder string fireball
comment lets define them initially.
for name in alias
begin
decorator call command name
async function foo
begin
pass
end function
with cal... | def test_double_command_registration(self):
alias = ['potato', 'cannon', 'Fodder', 'fireball'] # TODO: move these common lists to setup_class
# lets define them initially.
for name in alias:
@Commands.command(name)
async def foo():
pass
with ... | Python | nomic_cornstack_python_v1 |
function incircle self
begin
set centre = call incenter
from Drawables.Line import Line
set distance = call distanceFrom point=centre
from Drawables.Circle import Circle
return call fromMetrics centre distance
end function | def incircle(self):
centre = self.incenter()
from Drawables.Line import Line
distance = Line.fromPoints(
self.vertices[0], self.vertices[1]
).distanceFrom(point=centre)
from Drawables.Circle import Circle
return Circle.fromMetrics(centre, distance) | Python | nomic_cornstack_python_v1 |
function get_full_name self
begin
set full_name = string %s %s % tuple first_name last_name
return strip full_name
end function | def get_full_name(self):
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip() | Python | nomic_cornstack_python_v1 |
function add_storage self i
begin
set name = string iscsi_%d % i
call _add_storage add_iscsi_data_domain host name datacenter luns at i lun_addresses at i lun_targets at i
return name
end function | def add_storage(self, i):
name = "iscsi_%d" % i
self._add_storage(
add_iscsi_data_domain, self.host, name, self.datacenter,
self.luns[i], self.lun_addresses[i], self.lun_targets[i])
return name | Python | nomic_cornstack_python_v1 |
function _scale_enum anchor scales
begin
set tuple w h x_ctr y_ctr = call _whctrs anchor
set ws = w * scales
set hs = h * scales
set anchors = call _mkanchors ws hs x_ctr y_ctr
return anchors
end function | def _scale_enum(anchor, scales):
w, h, x_ctr, y_ctr = _whctrs(anchor)
ws = w * scales
hs = h * scales
anchors = _mkanchors(ws, hs, x_ctr, y_ctr)
return anchors | Python | nomic_cornstack_python_v1 |
function new_self_initiated_dialogue_reference cls
begin
return tuple call _generate_dialogue_nonce UNASSIGNED_DIALOGUE_REFERENCE
end function | def new_self_initiated_dialogue_reference(cls) -> Tuple[str, str]:
return cls._generate_dialogue_nonce(), Dialogue.UNASSIGNED_DIALOGUE_REFERENCE | Python | nomic_cornstack_python_v1 |
function test_bills_for_provider_uuid self
begin
set bills = call bills_for_provider_uuid azure_provider_uuid start_date=this_month_start
with call schema_context schema
begin
assert equal length bills 1
end
end function | def test_bills_for_provider_uuid(self):
bills = self.accessor.bills_for_provider_uuid(self.azure_provider_uuid, start_date=self.dh.this_month_start)
with schema_context(self.schema):
self.assertEqual(len(bills), 1) | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
function shape tensor
begin
return call as_list
end function
function conv2d inputs num_outputs kernel_size=tuple 3 3 stride=1 padding=string same activation=relu initializer=call xavier_initializer name=none
begin
set output = conv 2d inputs num_outputs kernel_size stride padding=padding activa... | import tensorflow as tf
def shape(tensor):
return tensor.get_shape().as_list()
def conv2d(inputs, num_outputs,
kernel_size=(3,3),
stride=1,
padding='same',
activation=tf.nn.relu,
initializer=tf.contrib.layers.xavier_initializer(),
name=None):
... | Python | zaydzuhri_stack_edu_python |
from statistics import mean
from scipy import stats
set list = list 20 33 44 66 89 10 40 50 28 49 55 41 21 11 13 14 15 16 78 79 70
sort list
string trim=int(0.1*len(list)) print(list) print(trim) list=list[trim:] list=list[:len(list)-trim] print(list) print(mean(list))
set m = call trim_mean list 0.1
print m | from statistics import mean
from scipy import stats
list=[20,33,44,66,89,10,40,50,28,49,55,41,21,11,13,14,15,16,78,79,70]
list.sort()
"""
trim=int(0.1*len(list))
print(list)
print(trim)
list=list[trim:]
list=list[:len(list)-trim]
print(list)
print(mean(list))
"""
m=stats.trim_mean(list,0.1)
print(m) | Python | zaydzuhri_stack_edu_python |
comment Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
comment For example, given a 3-ary tree:
comment We should return its level order traversal:
comment [
comment [1],
comment [3,2,4],
comment [5,6]
comment ]
comment Note:
comment The depth of th... | # Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
#
# For example, given a 3-ary tree:
#
#
#
#
#
#
#
# We should return its level order traversal:
#
#
# [
# [1],
# [3,2,4],
# [5,6]
# ]
#
#
#
#
# Note:
#
#
# The depth... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
import time
import traceback
function openWeb
begin
set path = string ./chromedriver.exe
set driver = call Chrome path
comment url需要为手机上查看的
set url = string https://www.wjx.cn/xz/32823920.aspx
get driver url
comment 获取所有的input输入框
set textinput = call find_elements_by_tag_name string input... | from selenium import webdriver
import time
import traceback
def openWeb():
path = './chromedriver.exe'
driver = webdriver.Chrome(path)
url = 'https://www.wjx.cn/xz/32823920.aspx' # url需要为手机上查看的
driver.get(url)
# 获取所有的input输入框
textinput = driver.find_element_by_class_name('fieldset').find_elemen... | Python | zaydzuhri_stack_edu_python |
from os.path import exists
function write_nurikabe ind
begin
string User friendly way for saving nurikabe. The description of the nurikabe is saved to 'nurikabe<ind>.txt'. :param ind: index of the nurikabe. :return: width, heigh, island stems, where island stems is a list of form [(stem_x, stem_y, island size), ...].
s... | from os.path import exists
def write_nurikabe(ind):
"""
User friendly way for saving nurikabe. The description of the nurikabe is saved to 'nurikabe<ind>.txt'.
:param ind: index of the nurikabe.
:return: width, heigh, island stems, where island stems is a list of form [(stem_x, stem_y, island s... | Python | zaydzuhri_stack_edu_python |
function place_pitch_effect chan_row effect replace warn_on_stop=false msg=none
begin
set pitch_effect_idx = none
for current_effect_idx in range length chan_row at string effects
begin
set current_effect = chan_row at string effects at current_effect_idx
if current_effect at 0 in pitch_effects
begin
set pitch_effect_i... | def place_pitch_effect(chan_row, effect, replace, warn_on_stop=False, msg=None):
pitch_effect_idx = None
for current_effect_idx in range(len(chan_row['effects'])):
current_effect = chan_row['effects'][current_effect_idx]
if current_effect[0] in pitch_effects:
pitch_effect_idx = current_effect_idx
pitch_effect... | Python | nomic_cornstack_python_v1 |
function rotate_clockwise matrix
begin
comment rows in the original matrix. This becomes cols in new matrix
set m_numrows = length matrix
comment cols in original matrix & num rows in new matrix
set m_numcols = length matrix at 0
comment This one doesn't work. Any changes made to one row are made to ALL rows in
comment... | def rotate_clockwise(matrix):
m_numrows = len(matrix) # rows in the original matrix. This becomes cols in new matrix
m_numcols = len(matrix[0]) # cols in original matrix & num rows in new matrix
# This one doesn't work. Any changes made to one row are made to ALL rows in
# the resulting matrix
#... | Python | nomic_cornstack_python_v1 |
function save_stream_map self widget data
begin
set stream_df_map = call DataFrame columns=list string SID string Stream_Size string ID string Start_index string End_Index string Full_Signature
set idx = 0
for ctr in range current_index
begin
set SID = stream_df at string SID at ctr
set Size_stream = stream_df at strin... | def save_stream_map(self, widget, data):
stream_df_map = pd.DataFrame(columns = ['SID', 'Stream_Size', 'ID', 'Start_index', 'End_Index', 'Full_Signature'])
idx=0
for ctr in range(self.current_index):
SID = self.stream_df['SID'][ctr]
Size_stream = self.stream_df['Size... | Python | nomic_cornstack_python_v1 |
while true
begin
try
begin
set temp = input
if length temp == 0
begin
break
end
append instList temp
end
except EOFError
begin
break
end
end
function binToDec num
begin
string [summary] Args: num ([string]): [binary number] Returns: [integer]: [description]
return integer num 2
end function
class Memory
begin
function ... | while True:
try:
temp = input()
if len(temp) == 0:
break
instList.append(temp)
except EOFError:
break
def binToDec(num):
"""[summary]
Args:
num ([string]): [binary number]
Returns:
[integer]: [description]
"""
return int(num,... | Python | zaydzuhri_stack_edu_python |
import cyaron , os
call system string g++ -o std -O2 ./std.cpp
for i in range 10
begin
set io = call IO file_prefix=string sdfs data_id=i + 1
if i < 6
begin
set n = random integer 5000 10000
end
else
begin
set n = random integer 50000 100000
end
set m = random integer n // 2 n * 2
set graph = call graph n m self_loop=f... | import cyaron, os
os.system('g++ -o std -O2 ./std.cpp')
for i in range(10):
io = cyaron.IO(file_prefix = 'sdfs', data_id = i + 1)
if i < 6:
n = cyaron.randint(5000, 10000)
else:
n = cyaron.randint(50000, 100000)
m = cyaron.randint(n // 2, n * 2)
graph = cyaron.Graph.graph(n, m, ... | Python | zaydzuhri_stack_edu_python |
import mysql.connector
class StockManagement
begin
function __init__ self
begin
set my_db = call connect host=string localhost user=string root database=string param_super_mart
set my_cursor = call cursor
end function
function adding_new_type self item_type
begin
set command = format string insert into stock_type(stock... | import mysql.connector
class StockManagement:
def __init__(self):
self.my_db = mysql.connector.connect(
host="localhost",
user="root",
database="param_super_mart"
)
self.my_cursor = self.my_db.cursor()
def adding_new_type(self, item_type):
c... | Python | zaydzuhri_stack_edu_python |
function history self
begin
return call G3RUH_descramble_sptr_history self
end function | def history(self):
return _spacegrant_swig.G3RUH_descramble_sptr_history(self) | Python | nomic_cornstack_python_v1 |
import socket
comment The server's hostname or IP address
set HOST = string 127.0.0.1
comment The port used by the server
set PORT = 65432
with call socket AF_INET SOCK_STREAM as s
begin
call connect tuple HOST PORT
while true
begin
comment The string to be sent should be in the format: label + white space + x + white ... | import socket
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 65432 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True:
# The string to be sent should be in the format: label + white space + x + white space ... | Python | zaydzuhri_stack_edu_python |
import cv2
import matplotlib.pyplot as plt
import numpy as np
comment Loading in the multi-face test image again
set image = call imread string images/test_image_1.jpg
comment Converting the image copy to RGB colorspace
set image = call cvtColor image COLOR_BGR2RGB
comment Makeing an array copy of this image
set image_... | import cv2
import matplotlib.pyplot as plt
import numpy as np
# Loading in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')
# Converting the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# Makeing an array copy of this image
image_with_noise = np.asarray(im... | Python | zaydzuhri_stack_edu_python |
function _ParseFlights self json_data
begin
set flights = list
for trip_option in json_data at string trips at string tripOption
begin
set flight = call Flight trip_option
append flights flight
end
return flights
end function | def _ParseFlights(self, json_data):
flights = []
for trip_option in json_data["trips"]["tripOption"]:
flight = Flight(trip_option)
flights.append(flight)
return flights | Python | nomic_cornstack_python_v1 |
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer | import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
| Python | flytech_python_25k |
function get_config_section self title_startswith return_all=true
begin
for section in _config_sections
begin
if starts with section at 0 title_startswith
begin
if return_all
begin
yield section
end
else
begin
return section
end
end
end
end function | def get_config_section(self, title_startswith, return_all=True):
for section in self._config_sections:
if section[0].startswith(title_startswith):
if return_all:
yield section
else:
return section | Python | nomic_cornstack_python_v1 |
import unittest
from CarRental import Car , ElectricCar , PetrolCar , DieselCar , HybridCar , CarFleet
comment test the car functionality
class TestCar extends TestCase
begin
function test_car_fleet self
begin
set car_fleet = call CarFleet
assert equal 40 call getNumAvailable
call rentCar 5
assert equal 35 call getNumA... | import unittest
from CarRental import Car, ElectricCar, PetrolCar, DieselCar, HybridCar, CarFleet
# test the car functionality
class TestCar(unittest.TestCase):
def test_car_fleet(self):
car_fleet = CarFleet()
self.assertEqual(40, car_fleet.getNumAvailable())
car_fleet.rentCar(5)... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Jun 30 12:17:16 2020 @author: Alexis Garcia
function a x y
begin
return x + y
end function
set b = lambda x y -> x + y | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 30 12:17:16 2020
@author: Alexis Garcia
"""
def a(x,y):
return x+y
b=lambda x,y: x+y
| Python | zaydzuhri_stack_edu_python |
function _handler_autosample_stop_autosample self *args **kwargs
begin
set next_state = none
set result = none
comment send soft break
call send SOFT_BREAK_FIRST_HALF
sleep 0.1
call _do_cmd_resp SOFT_BREAK_SECOND_HALF *args expected_prompt=CONFIRMATION keyword kwargs
comment Issue the confirmation command.
call _do_cmd... | def _handler_autosample_stop_autosample(self, *args, **kwargs):
next_state = None
result = None
# send soft break
self._connection.send(InstrumentCmds.SOFT_BREAK_FIRST_HALF)
time.sleep(.1)
self._do_cmd_resp(InstrumentCmds.SOFT_BREAK_SECOND_HALF,
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import os
import random
import struct
import hashlib
import zlib
import base64
from Crypto.Cipher import AES , DES
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import config
class AllCipher
begin
string Encryption and decryption are done in chunksize to prevent run... | # -*- coding: utf-8 -*-
import os
import random
import struct
import hashlib
import zlib
import base64
from Crypto.Cipher import AES, DES
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import config
class AllCipher():
""" Encryption and decryption are done in chunksize to prevent running ... | Python | zaydzuhri_stack_edu_python |
function delete self root key
begin
return call recursive_delete root key string key
end function | def delete(self,root,key):
return self.recursive_delete(root,key,"key") | Python | nomic_cornstack_python_v1 |
from functools import reduce
function manual_exponent num exp
begin
set computed_list = list num * exp
return reduce lambda total element -> total * element computed_list
end function
print call manual_exponent 2 3
print call manual_exponent 10 2 | from functools import reduce
def manual_exponent(num, exp):
computed_list = [num] * exp
return (reduce(lambda total, element: total * element, computed_list))
print(manual_exponent(2, 3))
print(manual_exponent(10, 2)) | Python | zaydzuhri_stack_edu_python |
from paho.mqtt import client as mqtt
from time import sleep
set TOPIK = string Bandung_Weather_News
set received_messages = list
function on_message client user_data msg
begin
comment simpan message dan convert dalam variable int
append received_messages integer decode payload string utf-8
comment tampilkan suhu rata-... | from paho.mqtt import client as mqtt
from time import sleep
TOPIK = 'Bandung_Weather_News'
received_messages= []
def on_message(client, user_data, msg):
#simpan message dan convert dalam variable int
received_messages.append(int(msg.payload.decode('utf-8')))
#tampilkan suhu rata-rata yang didapat
pri... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function getSum self a b
begin
print string a binary a
print string b binary b
set mask = 2047
set c = 0
set binary_a = binary mask ? a
set binary_b = binary mask ? b
print string a binary_a
print string b binary_b
set binary_a = binary_a at slice 2 : :
set binary_b = binary_b at slice 2 : :
if... | class Solution:
def getSum(self, a: int, b: int) -> int:
print('a',bin(a))
print('b',bin(b))
mask = 0x7FF
c = 0
binary_a = bin(mask & a)
binary_b = bin(mask & b)
print('a',binary_a)
print('b',binary_b)
binary_a = binary_a[2:]
binar... | Python | zaydzuhri_stack_edu_python |
function get self url **kwargs
begin
set response = get session url timeout=timeout keyword kwargs
return call _handle_response response
end function | def get(self, url, **kwargs):
response = self.session.get(url, timeout=self.timeout, **kwargs)
return self._handle_response(response) | Python | nomic_cornstack_python_v1 |
for i in range 1000 10000
begin
set concatenated = string i + string i * 2
if length concatenated == 9 and length set list concatenated == 9 and string 0 not in concatenated
begin
print string i + string * (1, 2) = + concatenated
end
end
for i in range 100 1000
begin
set concatenated = string i + string i * 2 + string ... | for i in range(1000, 10000):
concatenated = str(i) + str(i * 2)
if len(concatenated) == 9 and len(set(list(concatenated))) == 9 and '0' not in concatenated:
print(str(i) + ' * (1, 2) = ' + concatenated)
for i in range(100, 1000):
concatenated = str(i) + str(i * 2) + str(i * 3)
if len(con... | Python | zaydzuhri_stack_edu_python |
function remove_edge_from_graph self currency_1 currency_2
begin
set index = - 1
set first_index = - 1
set second_index = - 1
for tuple vertecies current_log_weight in graph
begin
if first_index != - 1 and second_index != - 1
begin
break
end
set index = index + 1
if vertecies == tuple get digit_currencies currency_2 ge... | def remove_edge_from_graph(self, currency_1, currency_2):
index = -1
first_index = -1
second_index = -1
for vertecies, current_log_weight in self.graph:
if first_index != -1 and second_index != -1:
break
index += 1
if vertecies == (se... | Python | nomic_cornstack_python_v1 |
function __Bs__ self Dimuon daughters conf
begin
set _b2xmumu = call CombineParticles
set DecayDescriptors = conf at string DECAYS
set CombinationCut = BdCombCut
set MotherCut = BdCut
set _sel_Daughters = call MergedSelection string Selection_ + name + string _daughters RequiredSelections=daughters
set sel = call Selec... | def __Bs__(self, Dimuon, daughters, conf):
_b2xmumu = CombineParticles()
_b2xmumu.DecayDescriptors = conf['DECAYS']
_b2xmumu.CombinationCut = self.BdCombCut
_b2xmumu.MotherCut = self.BdCut
_sel_Daughters = MergedSelection("Selection_"+self.name+"_daught... | Python | nomic_cornstack_python_v1 |
function get_cmd action=string compare
begin
if string CONE_PATH in environ
begin
set CONE_CMD = join path environ at string CONE_PATH CONE_SCRIPT
if not exists path CONE_CMD
begin
raise call RuntimeError string '%s' does not exist! % CONE_CMD
end
return string "%s" %s % tuple CONE_CMD action
end
else
begin
set SOURCE_... | def get_cmd(action='compare'):
if 'CONE_PATH' in os.environ:
CONE_CMD = os.path.join(os.environ['CONE_PATH'], CONE_SCRIPT)
if not os.path.exists(CONE_CMD):
raise RuntimeError("'%s' does not exist!" % CONE_CMD)
return '"%s" %s' % (CONE_CMD, action)
else:
SOURCE_... | Python | nomic_cornstack_python_v1 |
import time
import board
import analogio
from adafruit_circuitplayground import cp
set angle_sensor = call AnalogIn A1
while true
begin
set angle_normalized = round value / 65536 3
print angle_normalized
if angle_normalized > 0.5
begin
set pixels at 0 = tuple 0 0 255
end
else
begin
set pixels at 0 = tuple 0 0 0
end
sle... | import time
import board
import analogio
from adafruit_circuitplayground import cp
angle_sensor = analogio.AnalogIn(board.A1)
while True:
angle_normalized = round( angle_sensor.value/ 65536, 3)
print( angle_normalized )
if angle_normalized > 0.5:
cp.pixels[0] = (0,0,255)
else:
cp.pixel... | Python | zaydzuhri_stack_edu_python |
import numpy
import pymysql
import pandas
import matplotlib.pylab
from sklearn.decomposition import PCA
comment 属性规约 数值规约
comment 主成分分析
set conn = call connect host=string 127.0.0.1 user=string root port=33061 passwd=string xiangzong30917 db=string houseinfo
set sql = string select housesize, price from house
set data8... | import numpy
import pymysql
import pandas
import matplotlib.pylab
from sklearn.decomposition import PCA
#属性规约 数值规约
#主成分分析
conn = pymysql.connect(host='127.0.0.1', user="root", port=33061, passwd="xiangzong30917", db="houseinfo")
sql = "select housesize, price from house"
data8 = pandas.read_sql(sql, conn)
# print(dat... | Python | zaydzuhri_stack_edu_python |
comment Python program to remove initial extra zeros in regular expressions
import re
function match_wrd string
begin
set match = sub string \.[0]* string . string
return match
end function | # Python program to remove initial extra zeros in regular expressions
import re
def match_wrd(string):
match = re.sub(r'\.[0]*','.', string)
return match
| Python | zaydzuhri_stack_edu_python |
function __init__ __self__ condition=none error_message=none time=none
begin
if condition is not none
begin
set __self__ string condition condition
end
if error_message is not none
begin
set __self__ string error_message error_message
end
if time is not none
begin
set __self__ string time time
end
end function | def __init__(__self__, *,
condition: Optional[str] = None,
error_message: Optional[str] = None,
time: Optional[str] = None):
if condition is not None:
pulumi.set(__self__, "condition", condition)
if error_message is not None:
pul... | Python | nomic_cornstack_python_v1 |
comment This script labels the sentiment of each tweet as either positive/negative or neutral using textblob package
from textblob import TextBlob
import os
import csv
set directory = list directory string /home/gauravbg/SBU-fall-17/Big_Data/Project/Classified_Data/final
change directory string /home/gauravbg/SBU-fall-... | #This script labels the sentiment of each tweet as either positive/negative or neutral using textblob package
from textblob import TextBlob
import os
import csv
directory = os.listdir('/home/gauravbg/SBU-fall-17/Big_Data/Project/Classified_Data/final')
os.chdir('/home/gauravbg/SBU-fall-17/Big_Data/Project/Classified_... | Python | zaydzuhri_stack_edu_python |
function check_collision self
begin
comment verifie la collision avec l'ecran
call collide_screen
comment verifie la collision avec les bricks
set indices = call collide_list_of_bricks
for tuple i idx in enumerate indices
begin
comment supprime les bricks qu'on a touchees
del bricks at idx - i
end
comment si plus de br... | def check_collision(self):
self.collide_screen() # verifie la collision avec l'ecran
indices = self.collide_list_of_bricks() # verifie la collision avec les bricks
for i, idx in enumerate(indices):
del(self.bricks[idx-i]) # supprime les bricks qu'on a touchees
... | Python | nomic_cornstack_python_v1 |
function test_delete_tag self
begin
with call test_client as client
begin
set resp = post string /tags/ { id } /delete follow_redirects=true
set html = call get_data as_text=true
assert equal status_code 200
assert not in string Marvel html
end
end function | def test_delete_tag(self):
with app.test_client() as client:
resp = client.post(f"/tags/{self.tag.id}/delete", follow_redirects=True)
html = resp.get_data(as_text=True)
self.assertEqual(resp.status_code, 200)
self.assertNotIn("Marvel", html) | Python | nomic_cornstack_python_v1 |
from Shell.Abstract.Command import Command
class Remove_Layer extends Command
begin
function execute self layer_list dimension_list params
begin
set tuple layer value = params
set value = integer value
set ocurrencies = 0
for i in range length layer_list
begin
if layer_list at i == layer
begin
set ocurrencies = ocurren... | from Shell.Abstract.Command import Command
class Remove_Layer(Command):
def execute(self, layer_list, dimension_list, params):
(layer, value) = params
value = int(value)
ocurrencies = 0
for i in range(len(layer_list)):
if layer_list[i] == layer:
ocurren... | Python | zaydzuhri_stack_edu_python |
function setup cls rule_details details_map
begin
set out_file = rule_details at NAME_KEY + string .zip
call init_rule_common rule_details out_file list
set rule_details at POSSIBLE_PREFIXES_KEY = call prefix_transform list
call _setup_deps rule_details details_map
call _setup_tests rule_details details_map
call _setup... | def setup(cls, rule_details, details_map):
out_file = rule_details[su.NAME_KEY] + '.zip'
su.init_rule_common(rule_details, out_file, [])
rule_details[su.POSSIBLE_PREFIXES_KEY] = su.prefix_transform([])
cls._setup_deps(rule_details, details_map)
cls._setup_tests(rule_details, details_map)
cls._se... | Python | nomic_cornstack_python_v1 |
function is_alive url
begin
comment Create a request object to connect with
comment s = socket.socket()
comment Now try connecting, passing in a tuple with address & port
try
begin
try
begin
set r = get requests url allow_redirects=false timeout=1
end
comment para logear error print (r.raise_for_status())
except any
be... | def is_alive(url):
# Create a request object to connect with
#s = socket.socket()
# Now try connecting, passing in a tuple with address & port
try:
try:
r= requests.get (url, allow_redirects = False, timeout = 1)
# para logear error print (r.raise_for_status()... | Python | nomic_cornstack_python_v1 |
function shutdown loop
begin
try
begin
if version_info at slice : 2 : >= tuple 3 7
begin
set all_tasks = all_tasks
end
else
begin
set all_tasks = all_tasks
end
comment This part is borrowed from asyncio/runners.py in Python 3.7b2.
set to_cancel = list comprehension task for task in call all_tasks loop if not call don... | def shutdown(loop: asyncio.AbstractEventLoop) -> None:
try:
if sys.version_info[:2] >= (3, 7):
all_tasks = asyncio.all_tasks
else:
all_tasks = asyncio.Task.all_tasks
# This part is borrowed from asyncio/runners.py in Python 3.7b2.
to_cancel = [task for task in... | Python | nomic_cornstack_python_v1 |
function hostify_url url
begin
if url at 0 == string /
begin
return HOST + url
end
else
begin
return url
end
end function | def hostify_url(url):
if url[0] == '/':
return HOST + url
else:
return url | Python | nomic_cornstack_python_v1 |
function split_sentences self text
begin
if ch
begin
set re_compile = re_ch_sent_split
end
else
begin
set re_compile = re_en_sent_split
end
set sentence_delimiters = compile re_compile U
set sentences = split sentence_delimiters text
return sentences
end function | def split_sentences(self,text):
if self.ch:
re_compile = re_ch_sent_split
else:
re_compile = re_en_sent_split
sentence_delimiters = re.compile(re_compile, re.U)
sentences = sentence_delimiters.split(text)
return sentences | Python | nomic_cornstack_python_v1 |
from HandCombo import HandCombo
from FieldCombo import FieldCombo
class TotalCombo
begin
function __init__ self fieldCombos=list cardsInDeck=40
begin
set fieldCombos = fieldCombos
set brickPerc = call calcPercBrick
set cardsInDeck = cardsInDeck
end function
function calcPercBrick self
begin
set percBrick = 1
for combo... | from HandCombo import HandCombo
from FieldCombo import FieldCombo
class TotalCombo():
def __init__(self, fieldCombos = [], cardsInDeck = 40):
self.fieldCombos = fieldCombos
self.brickPerc = self.calcPercBrick()
self.cardsInDeck = cardsInDeck
def calcPercBrick(self):
percBrick = ... | Python | zaydzuhri_stack_edu_python |
function nic_speed self speed
begin
set xlate = dict string 40000000000 string 40 Gbps ; string 20000000000 string 20 Gbps ; string 10000000000 string 10 Gbps ; string 1000000000 string 1 Gbps ; string 2000000000 string 2 Gbps ; string 100000000 string 100 Mbps ; string 10000000 string 10 Mbps ; string 0 string undefin... | def nic_speed(self, speed):
xlate = {
'40000000000': u'40 Gbps',
'20000000000': u'20 Gbps',
'10000000000': u'10 Gbps',
'1000000000': u'1 Gbps',
'2000000000': u'2 Gbps',
'100000000': u'100 Mbps',
'10000000': u'10 Mbps',
... | Python | nomic_cornstack_python_v1 |
function test_rectangle_get_perimeter self
begin
set rhombus = call Rhombus 0 5 60
assert equal call get_perimeter 20
end function | def test_rectangle_get_perimeter(self):
rhombus = Rhombus(0, 5, 60)
self.assertEqual(rhombus.get_perimeter(), 20) | Python | nomic_cornstack_python_v1 |
while true
begin
set current = read line raw
if current == string
begin
break
end
print current
if string ## in current or string %% in current
begin
write clean current
end
end
close raw
close clean | while True:
current = raw.readline()
if current == '':
break;
print(current)
if '##' in current or '%%' in current:
clean.write(current)
raw.close()
clean.close() | Python | zaydzuhri_stack_edu_python |
function port port_number return_format=none
begin
set response = call _get format string port/{number} number=port_number return_format
if string bad port number in string response
begin
raise error format string Bad port number, {number} number=port_number
end
else
begin
return response
end
end function | def port(port_number, return_format=None):
response = _get('port/{number}'.format(number=port_number), return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | Python | nomic_cornstack_python_v1 |
function northwestCommand self northwestCommand
begin
pass
end function | def northwestCommand(self, northwestCommand):
pass | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
function young_time str_arg
begin
call point str_arg
print string tell_number
end function
function point str_arg
begin
print str_arg
end function
if __name__ == string __main__
begin
call young_time string feel_same_company_after_year
end | #! /usr/bin/env python
def young_time(str_arg):
point(str_arg)
print('tell_number')
def point(str_arg):
print(str_arg)
if __name__ == '__main__':
young_time('feel_same_company_after_year')
| Python | zaydzuhri_stack_edu_python |
function loadTouchs
begin
from scripts.general import chkVersion
call chkVersion
import pandas as pd
import os
import numpy as np
from IPython.display import display
call makeSettings basic=true levels=false
comment Primero se carga la info de la estructura json (los touchs y sounds vienen dentro de los trials)
if is f... | def loadTouchs ():
from scripts.general import chkVersion
chkVersion()
import pandas as pd
import os
import numpy as np
from IPython.display import display
makeSettings(basic=True,levels=False)
# Primero se carga la info de la estructura json (los touchs y sounds vienen dentro de los... | Python | nomic_cornstack_python_v1 |
import threading
import time
function thread_job
begin
print string t1 start,this is a adding thread, number is %s % call current_thread
for i in range 30
begin
sleep 0.1
end
print string t1 finish
end function
function t2_job
begin
print string t2 start
print string t2 end
end function
function main
begin
set added_tr... | import threading
import time
def thread_job():
print("t1 start,this is a adding thread, number is %s" % threading.current_thread())
for i in range(30):
time.sleep(0.1)
print('t1 finish')
def t2_job():
print('t2 start')
print('t2 end')
def main():
added_tread = threading.Thread(tar... | Python | zaydzuhri_stack_edu_python |
import re
from google.appengine.api import users
import logging
import os
function path file_path=string /
begin
return join path directory name path __file__ string templates/ + file_path
end function
function authdetails page=string /
begin
set user = call get_current_user
set authenticated = if expression user then ... | import re
from google.appengine.api import users
import logging
import os
def path(file_path='/'):
return os.path.join(os.path.dirname(__file__), "templates/"+file_path )
def authdetails(page = "/"):
user = users.get_current_user()
authenticated = True if user else False
label = "sign out" if authe... | Python | zaydzuhri_stack_edu_python |
function replace_selections bb ref_name path_to_replacement
begin
function _replace inner_bb
begin
comment Start with an empty selection
set path = list
set selection = inner_bb
while is instance selection Selection
begin
append path call as_index
set selection = source
end
comment In ASTs like x[0][1], we'll see the ... | def replace_selections(
bb: building_blocks.ComputationBuildingBlock,
ref_name: str,
path_to_replacement: dict[
tuple[int, ...], building_blocks.ComputationBuildingBlock
],
) -> building_blocks.ComputationBuildingBlock:
def _replace(inner_bb):
# Start with an empty selection
path = []... | Python | nomic_cornstack_python_v1 |
function make_freq_dict text
begin
set freq_dict = dict
for byte in text
begin
set default freq_dict byte 0
set freq_dict at byte = freq_dict at byte + 1
end
return freq_dict
end function | def make_freq_dict(text):
freq_dict = {}
for byte in text:
freq_dict.setdefault(byte, 0)
freq_dict[byte] += 1
return freq_dict | Python | nomic_cornstack_python_v1 |
function snmp_v3_privacy_protocol self value=string No Privacy Protocol
begin
set attributes at string Lanforge Resource.SNMP V3 Privacy Protocol = value
end function | def snmp_v3_privacy_protocol(self, value='No Privacy Protocol'):
self.attributes['Lanforge Resource.SNMP V3 Privacy Protocol'] = value | Python | nomic_cornstack_python_v1 |
from common import BoundaryCondition
import models.incompressibleNS.variableDensity
from numpy import tanh , sqrt
class Uniform2D
begin
set boundaryCondition = tuple PERIODIC PERIODIC
set finalTime = 1.0
set exactSolution = none
function __init__ self ambient_state
begin
set ambient_state = ambient_state
end function
f... | from common import BoundaryCondition
import models.incompressibleNS.variableDensity
from numpy import tanh, sqrt
class Uniform2D():
boundaryCondition = (BoundaryCondition.PERIODIC, BoundaryCondition.PERIODIC)
finalTime = 1.0
exactSolution = None
def __init__(self, ambient_state):
self.ambi... | Python | zaydzuhri_stack_edu_python |
function screen_width self screen_width
begin
comment type: (int) -> None
if screen_width is not none
begin
if not is instance screen_width int
begin
raise call TypeError string Invalid type for `screen_width`, type has to be `int`
end
end
set _screen_width = screen_width
end function | def screen_width(self, screen_width):
# type: (int) -> None
if screen_width is not None:
if not isinstance(screen_width, int):
raise TypeError("Invalid type for `screen_width`, type has to be `int`")
self._screen_width = screen_width | Python | nomic_cornstack_python_v1 |
function set_x_d self treatment_var
begin
if not is instance treatment_var str
begin
raise call TypeError string treatment_var must be of str type. { string treatment_var } of type { string type treatment_var } was passed.
end
if treatment_var not in d_cols
begin
raise call ValueError string Invalid treatment_var. { tr... | def set_x_d(self, treatment_var):
if not isinstance(treatment_var, str):
raise TypeError('treatment_var must be of str type. '
f'{str(treatment_var)} of type {str(type(treatment_var))} was passed.')
if treatment_var not in self.d_cols:
raise ValueError... | Python | nomic_cornstack_python_v1 |
function update_activation self
begin
if forced
begin
return
end
call update_activation
end function | def update_activation(self) -> None:
if self.forced:
return
self.units.update_activation() | Python | nomic_cornstack_python_v1 |
while i < 10
begin
if i % 2 == 0
begin
print string * end=string
end
else
begin
print string $ end=string
end
set i = i + 1
end | while i<10:
if i%2==0:
print("*", end= " ")
else:
print("$", end=" ")
i+=1
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Apr 13 17:08:03 2021 @author: TORREX
set lista = list
for x in range 5
begin
set valor = integer input string ingrese valor
append lista valor
end
set menor = lista at 0
set posicion = 0
for x in range 1 5
begin
if lista at x < menor
begin
set menor = lista at x
set ... | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 13 17:08:03 2021
@author: TORREX
"""
lista=[]
for x in range(5):
valor=int(input("ingrese valor"))
lista.append(valor)
menor=lista[0]
posicion=0
for x in range(1,5):
if lista[x]<menor:
menor=lista[x]
posicion=x
print("lista completa",lista)
pr... | Python | zaydzuhri_stack_edu_python |
import urllib2
set response = url open string http://python.org
set html = read response
with open string pytong.txt string w as f
begin
write f html
close f
end | import urllib2
response = urllib2.urlopen("http://python.org")
html = response.read()
with open("pytong.txt", "w") as f:
f.write(html)
f.close()
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Mon Apr 6 11:12:43 2020 @author: ShihaoYang
from py2neo import Graph , Node , Relationship
set g = call Graph host=string 127.0.0.1 http_port=7687 user=string neo4j password=string wdygcs
comment neo4j 搭载服务器的ip地址,ifconfig可获取到
comment neo4j 服务... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 6 11:12:43 2020
@author: ShihaoYang
"""
from py2neo import Graph,Node,Relationship
g = Graph(
host="127.0.0.1", # neo4j 搭载服务器的ip地址,ifconfig可获取到
http_port=7687, # neo4j 服务器监听的端口号
user="neo4j", # 数据库user name,如... | Python | zaydzuhri_stack_edu_python |
function annotations self
begin
return get pulumi self string annotations
end function | def annotations(self) -> Optional[Sequence[Any]]:
return pulumi.get(self, "annotations") | Python | nomic_cornstack_python_v1 |
function silly_fibonacci_example self n
begin
if n < 1
begin
raise call ValueError string n must be >= 1, got %s % n
end
if n in tuple 1 2
begin
return 1
end
else
begin
return call silly_fibonacci_example n - 1 + call silly_fibonacci_example n - 2
end
end function | def silly_fibonacci_example(self, n):
if n < 1:
raise ValueError('n must be >= 1, got %s' % n)
if n in (1, 2):
return 1
else:
return (self.silly_fibonacci_example(n - 1) +
self.silly_fibonacci_example(n - 2)) | Python | nomic_cornstack_python_v1 |
function cancel self
begin
call cancel
call cancel
end function | def cancel(self):
self.cbA.cancel()
self.cbB.cancel() | Python | nomic_cornstack_python_v1 |
function round_to_two_decimals number
begin
return round number 2
end function | def round_to_two_decimals(number):
return round(number, 2) | Python | iamtarun_python_18k_alpaca |
function __pow__ self power
begin
return call Spectral ID=format string {}**{} ID power value=value ^ power wl=wl wn=wn desc=format string {}**{} desc power
end function | def __pow__(self, power):
return Spectral(ID='{}**{}'.format(self.ID,power), value=self.value ** power,
wl=self.wl, wn=self.wn,desc='{}**{}'.format(self.desc,power)) | Python | nomic_cornstack_python_v1 |
function region self
begin
return get pulumi self string region
end function | def region(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "region") | Python | nomic_cornstack_python_v1 |
set a = 5
set b = 2
set sub = a - b
print sub | a=5
b=2
sub=a-b
print(sub) | Python | zaydzuhri_stack_edu_python |
function merge self lst _app=none
begin
comment pragma: nocover
if not lst
begin
raise call RuntimeError string no items provided to merge
end
set labels = dict
for item in lst
begin
comment pragma: nocover
if not __name__ == string label
begin
warning string item is not the correct type, skipping...
continue
end
upda... | def merge(self, lst, _app=None):
if not lst: # pragma: nocover
raise RuntimeError('no items provided to merge')
labels = {}
for item in lst:
if not item.__class__.__name__ == 'label': # pragma: nocover
logging.warning('item is not the correct type, skipp... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Mon Sep 28 14:18:05 2020 @author: Barmando
from PyQt5 import QtCore , QtGui , QtWidgets
from PyQt5.QtCore import pyqtSignal
import psutil
from time import sleep
class RaspiInformation extends QThread
begin
set raspi_signal = call pyqtSignal dict
function __init__ self thr... | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 14:18:05 2020
@author: Barmando
"""
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import pyqtSignal
import psutil
from time import sleep
class RaspiInformation(QtCore.QThread):
raspi_signal = pyqtSignal(dict)
def __init__(self, threadID, na... | Python | zaydzuhri_stack_edu_python |
comment auther:shixingjian time:2020/06/28
import MySQLdb
set db = call connect host=string 127.0.0.1 port=3306 user=string root passwd=string 123456 db=string plesson charset=string utf8
set cu = call cursor
comment cu.execute("insert into sq_course value(4,'java','java数据',4);")
comment 一次性插入多条数据
comment sql = '''
com... | # auther:shixingjian time:2020/06/28
import MySQLdb
db = MySQLdb.connect(host = '127.0.0.1',port = 3306,user = 'root',passwd = '123456',db = 'plesson',charset = 'utf8')
cu = db.cursor()
# cu.execute("insert into sq_course value(4,'java','java数据',4);")
# 一次性插入多条数据
# sql = '''
# insert into sq_course(name,`desc`,display... | Python | zaydzuhri_stack_edu_python |
comment # Computation on NumPy Arrays: Universal Functions
comment %%
import numpy as np
seed 0
function compute_reciprocals values
begin
set output = call empty length values
for i in range length values
begin
set output at i = 1.0 / values at i
end
return output
end function
set values = random integer 1 10 size=5
pr... | # # Computation on NumPy Arrays: Universal Functions
#%%
import numpy as np
np.random.seed(0)
def compute_reciprocals(values):
output = np.empty(len(values))
for i in range(len(values)):
output[i] = 1.0 / values[i]
return output
values = np.random.randint(1, 10, size=5)
print(compute_recip... | Python | zaydzuhri_stack_edu_python |
from telegram.ext import CommandHandler
function get_commands
begin
set commands = string Timer commands: /timer <seconds> /stoptimer
return commands
end function
function add_handlers dispatcher
begin
set timer_handler = call CommandHandler string timer timer pass_args=true pass_job_queue=true pass_user_data=true
call... | from telegram.ext import CommandHandler
def get_commands():
commands = "Timer commands:\n/timer <seconds>\n/stoptimer\n"
return commands
def add_handlers(dispatcher):
timer_handler = CommandHandler("timer", timer, pass_args=True, pass_job_queue=True, pass_user_data=True)
dispatcher.add_handler(timer... | Python | zaydzuhri_stack_edu_python |
import socket
import sys
from input_timeout import readInput
set username = argv at 1
function prompt nl
begin
if nl
begin
print string
end
print string < + username + string >
end function
set server_address = tuple string localhost 10000
set client = call socket AF_INET SOCK_STREAM
call connect server_address
call se... | import socket
import sys
from input_timeout import readInput
username = sys.argv[1]
def prompt(nl):
if nl:
print("")
print("<" + username + ">")
server_address = ("localhost", 10000)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(server_address)
client.sendall(username.... | Python | zaydzuhri_stack_edu_python |
function enumerate_files self table
begin
for i in range call nrofrecords
begin
set data = call readrec i + 1
if data and data at 0 == tableid
begin
yield tuple i + 1 data at slice 1 : :
end
end
end function | def enumerate_files(self, table):
for i in range(self.nrofrecords()):
data = self.bank.readrec(i + 1)
if data and data[0] == table.tableid:
yield i + 1, data[1:] | Python | nomic_cornstack_python_v1 |
from pymongo import MongoClient
from globals import connStr
from bson import ObjectId
comment Pass URL of mdb cluster
set client = call MongoClient connStr
set db = call get_database string UsersTestDB
set coll = Users
string print(coll.count_documents({})) new_user = { 'name': 'Alejandro', 'lastName': 'Vasquez', 'age'... | from pymongo import MongoClient
from globals import connStr
from bson import ObjectId
client = MongoClient(connStr) #Pass URL of mdb cluster
db = client.get_database('UsersTestDB')
coll = db.Users
'''print(coll.count_documents({}))
new_user = {
'name': 'Alejandro',
'lastName': 'Vasquez',
'age': 22
}
coll... | Python | zaydzuhri_stack_edu_python |
function make_complete_graph num_nodes
begin
set graph = dict
if num_nodes <= 0
begin
set graph = dict
return graph
end
else
if num_nodes == 1
begin
set graph = dict 0 set list
return graph
end
else
begin
for node in range 0 num_nodes
begin
set graph at node = set list comprehension x for x in range 0 num_nodes if x ... | def make_complete_graph(num_nodes):
graph={}
if num_nodes<=0:
graph={}
return graph
elif num_nodes==1:
graph={0:set([])}
return graph
else:
for node in range(0,num_nodes):
graph[node]=set([x for x in range(0,num_nodes) if x!=node])
return graph
def compute_in_degrees(digraph):
in_degrees={}
for no... | Python | zaydzuhri_stack_edu_python |
function loads s
begin
set data = loads s
return list comprehension call from_dict d for d in data
end function | def loads(s):
data = json.loads(s)
return [from_dict(d) for d in data] | Python | nomic_cornstack_python_v1 |
function calculateUser df normalizeRows=false
begin
set customerIds = unique
set result = list
for customerId in customerIds
begin
set mask = customerId == customerId
set customerDf = df at mask
set customerDf = customerDf at all_cols
set customerDf at string transactionAmount = call normalize reshape values - 1 1 axi... | def calculateUser(df,normalizeRows=False):
customerIds = df.customerId.unique()
result = []
for customerId in customerIds:
mask = df.customerId == customerId
customerDf = df[mask]
customerDf = customerDf[all_cols]
customerDf['transactionAmount'] = normalize(customerDf['transa... | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import urllib2
from unidecode import unidecode
import uuid
set BASE = string https://en.wikipedia.org
set starter = string /wiki/Mahatma_Gandhi
comment CRAWLER
set paths = list
function crawler URL
begin
set solved = false
set hops = 0
set page = read url open URL
set html = call Beautifu... | from bs4 import BeautifulSoup
import urllib2
from unidecode import unidecode
import uuid
BASE = "https://en.wikipedia.org"
starter = "/wiki/Mahatma_Gandhi"
# CRAWLER
paths = []
def crawler(URL):
solved = False
hops = 0
page = urllib2.urlopen(URL).read()
html = BeautifulSoup(page, "html.parser")
ID = uuid.uuid... | Python | zaydzuhri_stack_edu_python |
function get_output cmd err=false returncode=0
begin
if is instance cmd str
begin
set cmd = split shlex cmd
end
set stderr = if expression err then STDOUT else stderr
try
begin
set output = decode check output cmd stderr=stderr string utf8 string replace
end
except CalledProcessError as e
begin
if returncode != returnc... | def get_output(cmd, err=False, returncode=0):
if isinstance(cmd, str):
cmd = shlex.split(cmd)
stderr = STDOUT if err else sys.stderr
try:
output = check_output(cmd, stderr=stderr).decode('utf8', 'replace')
except CalledProcessError as e:
if e.returncode != returncode:
... | Python | nomic_cornstack_python_v1 |
function noisify x snr unit=none
begin
if unit == string dB
begin
set snr = 10 ^ snr / 20
end
if call iscomplexobj x
begin
set n = call standard_normal shape + 1j * call standard_normal shape
end
else
begin
set n = call standard_normal shape
end
set n = n * 1 / square root snr * norm x / norm n
return x + n
end functio... | def noisify(x, snr, unit=None):
if unit == "dB":
snr = 10 ** (snr / 20)
if np.iscomplexobj(x):
n = np.random.standard_normal(x.shape) + 1j * np.random.standard_normal(x.shape)
else:
n = np.random.standard_normal(x.shape)
n *= 1 / np.sqrt(snr) * np.linalg.norm(x) / np.linalg.nor... | Python | nomic_cornstack_python_v1 |
function build app path
begin
with catch warnings
begin
comment Ignore warnings emitted by docutils internals.
filter warnings string ignore string 'U' mode is deprecated DeprecationWarning
call build
with open join path outdir path encoding=string utf-8 as rendered
begin
return read rendered
end
end
end function | def build(app, path):
with warnings.catch_warnings():
# Ignore warnings emitted by docutils internals.
warnings.filterwarnings(
"ignore",
"'U' mode is deprecated",
DeprecationWarning)
app.build()
with open(os.path.join(app.outdir, path),
... | Python | nomic_cornstack_python_v1 |
from django.shortcuts import render
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import matplotlib
from clustering import clusters
from clustering import lines
from clustering import contents
from clustering import Total_Annotations , Inconsistent_Annotations
from clustering import single , ... | from django.shortcuts import render
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import matplotlib
from clustering import clusters
from clustering import lines
from clustering import contents
from clustering import Total_Annotations, Inconsistent_Annotations
from clustering import single,MWE... | Python | zaydzuhri_stack_edu_python |
function build_loss_fun
begin
return call call get_loss_fun
end function | def build_loss_fun():
return get_loss_fun()() | Python | nomic_cornstack_python_v1 |
function write_data_index self
begin
set content = string
remove self join path config at string data_subdir string *
if data_index
begin
print string - writing data index
set content = content + string # [ { config at string github_repo_name } ]( { config at string github_pages_url } )
set content = content + string ... | def write_data_index(self):
content = ""
self.remove(os.path.join(config["data_subdir"], "*"))
if self.data_index:
print("- writing data index")
content += f"# [{config['github_repo_name']}]({config['github_pages_url']})\n"
content += "\n## Index of Data files... | Python | nomic_cornstack_python_v1 |
import os
import matplotlib
import numpy as np
import pandas as pd
import tushare as ts
set pro = call pro_api string 28cacf3fd08f2da30fadedec0e2e550c2a7ed2d907d3b79547d0e293
change directory string C:/Users/i038196
call set_printoptions threshold=inf
call set_option string display.width 200
call set_option string disp... | import os
import matplotlib
import numpy as np
import pandas as pd
import tushare as ts
pro = ts.pro_api("28cacf3fd08f2da30fadedec0e2e550c2a7ed2d907d3b79547d0e293");
os.chdir("C:/Users/i038196")
np.set_printoptions(threshold=np.inf)
pd.set_option('display.width', 200)
pd.set_option('display.max_columns', Non... | 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.