code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function manually_parse_dimensions self dim_string
begin
set parsed = none
set template = string {{{{Size|cm|{}|{}}}}}
if string x in dim_string
begin
set split = split dim_string string x
set first = strip split at 0
set second = split strip split at 1 string at 0
set parsed = format template first second
end
return p... | def manually_parse_dimensions(self, dim_string):
parsed = None
template = "{{{{Size|cm|{}|{}}}}}"
if "x" in dim_string:
split = dim_string.split("x")
first = split[0].strip()
second = split[1].strip().split(" ")[0]
parsed = template.format(first, s... | Python | nomic_cornstack_python_v1 |
function schedule_action self scheduler_name action_name
begin
with lock
begin
call check_scheduler_name scheduler_name
call check_action_name action_name
set scheduler = call get_scheduler scheduler_name
if is instance scheduler TimedScheduler
begin
call set_timed _timed
end
else
if is instance scheduler Immediately
b... | def schedule_action(self, scheduler_name: str, action_name: str):
with Lok.lock:
self.check_scheduler_name(scheduler_name)
self.check_action_name(action_name)
scheduler = self.get_scheduler(scheduler_name)
if isinstance(scheduler, TimedScheduler):
... | Python | nomic_cornstack_python_v1 |
function bigquery_explain_forecast_model_job model destination_table gcp_resources location=string us-central1 horizon=3 confidence_level=0.95 query_parameters=list job_configuration_query=dict labels=dict encryption_spec_key_name=string project=PROJECT_ID_PLACEHOLDER
begin
comment fmt: off
comment fmt: on
return c... | def bigquery_explain_forecast_model_job(
model: Input[BQMLModel],
destination_table: Output[BQTable],
gcp_resources: OutputPath(str),
location: str = 'us-central1',
horizon: int = 3,
confidence_level: float = 0.95,
query_parameters: List[str] = [],
job_configuration_query: Dict[str, str]... | Python | nomic_cornstack_python_v1 |
function setup
begin
set is_installed = call wp_cli string core is-installed
if is_installed
begin
call wp_cli string core download
set install_params = dict
set install_params at string url = call prompt string URL:
set install_params at string title = call prompt string Title:
set install_params at string admin_user... | def setup():
is_installed = wp_cli('core is-installed')
if is_installed:
wp_cli('core download')
install_params = {}
install_params['url'] = prompt('URL: ')
install_params['title'] = prompt('Title: ')
install_params['admin_user'] = prompt('Admin User: ')
instal... | Python | nomic_cornstack_python_v1 |
function test_harness_request_get_list_and_dict_params self
begin
set tuple _ rule view_class annotations = annotations at 3
set annotation = annotations at 0
set result = call request rule view_class annotation
set result at string response = loads result at string response
assert result == dict string method string G... | def test_harness_request_get_list_and_dict_params(self):
_, rule, view_class, annotations = self.annotations[3]
annotation = annotations[0]
result = self.harness.request(rule, view_class, annotation)
result['response'] = json.loads(result['response'])
assert result == {
... | Python | nomic_cornstack_python_v1 |
comment Definition for a binary tree node.
comment class TreeNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Solution extends object
begin
function pathSum self root sum
begin
string :type root: TreeNode :type sum: int :rtype: List[List[int]]
se... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[i... | Python | zaydzuhri_stack_edu_python |
function normalize_scores scores
begin
comment print(scores)
set keys = keys scores
set sum = 0.0
for k in keys
begin
comment print("%06f\t" % scores.get(k)),
set sum = sum + get scores k
end
if sum == 1.0
begin
return scores
end
set new_scores = dict
for k in keys
begin
set new_scores at k = get scores k / decimal su... | def normalize_scores(scores):
#print(scores)
keys = scores.keys()
sum = 0.0
for k in keys:
#print("%06f\t" % scores.get(k)),
sum += scores.get(k)
if sum == 1.0:
return scores
new_scores = {}
for k in keys:
new_scores[k] = scores.get(k)/float(sum)
retur... | Python | nomic_cornstack_python_v1 |
comment Here, the state is a bit more complicated
comment We hold a connection graph which modifies
comment as moves are made to analyze the win-
comment state efficiently
import random
set n = 9
class State
begin
set EMPTY = 0
set X = 1
set O = 2
comment a set for each hex of connected indices
comment this could be mo... | # Here, the state is a bit more complicated
# We hold a connection graph which modifies
# as moves are made to analyze the win-
# state efficiently
import random
n = 9
class State:
EMPTY = 0
X = 1
O = 2
# a set for each hex of connected indices
# this could be more clear but i... | Python | zaydzuhri_stack_edu_python |
function is_point_inside_frustum camera point
begin
set tuple cs ce = tuple clip_start clip_end
set co_ndc = call world_to_camera_view scene camera point
comment check wether point is inside frustum
if 0.0 < x < 1.0 and 0.0 < y < 1.0 and cs < z < ce
begin
return true
end
else
begin
return false
end
end function | def is_point_inside_frustum(camera, point):
cs, ce = camera.data.clip_start, camera.data.clip_end
co_ndc = world_to_camera_view(bpy.context.scene, camera, point)
# check wether point is inside frustum
if (0.0 < co_ndc.x < 1.0 and
0.0 < co_ndc.y < 1.0 and
cs < co_ndc.z < ce):
... | Python | nomic_cornstack_python_v1 |
function return_results fp output_folder gzip=true
begin
comment Compress the output
if gzip
begin
call run_cmds list string gzip fp
set fp = fp + string .gz
end
if starts with output_folder string s3://
begin
comment Copy to S3
call run_cmds list string aws string s3 string cp string --quiet string --sse string AES256... | def return_results(fp, output_folder, gzip=True):
# Compress the output
if gzip:
run_cmds(['gzip', fp])
fp = fp + '.gz'
if output_folder.startswith('s3://'):
# Copy to S3
run_cmds([
'aws',
's3',
'cp',
'--quiet',
'-... | Python | nomic_cornstack_python_v1 |
import sqlite3
from sqlite3 import Error
function create_connection
begin
set conn = call connect string D:\Computer Stuff\Documents\pyscripts\app1\movielist.db
set cur = call cursor
execute cur string SELECT *
set rows = call fetchall
for row in rows
begin
print row
end
end function
call create_connection | import sqlite3
from sqlite3 import Error
def create_connection():
conn = sqlite3.connect("D:\\Computer Stuff\\Documents\\pyscripts\\app1\\movielist.db")
cur = conn.cursor()
cur.execute("SELECT *")
rows = cur.fetchall()
for row in rows:
print(row)
create_connection()
| Python | zaydzuhri_stack_edu_python |
from dataclasses import dataclass
function player_to_resources player
begin
return call Resources player at 1 player at 2 player at 4 player at 3 player at 8 player at 10
end function
decorator dataclass
comment Food cap and food used seems to be inverted
class Resources
begin
set mineral : int
set vespene : int
set fo... | from dataclasses import dataclass
def player_to_resources(player):
return Resources(
player[1],
player[2],
player[4], # Food cap and food used seems to be inverted
player[3],
player[8],
player[10],
)
@dataclass
class Resources:
mineral: int
vespene: in... | Python | zaydzuhri_stack_edu_python |
function say self message **options
begin
set steps = _steps
set say_obj = call Say message keyword options
set piece = obj
comment steps.append({'say' : piece})
append steps piece
set _steps = steps
return json
end function | def say(self, message, **options):
steps = self._steps
say_obj = Say(message, **options)
piece = say_obj.obj
# steps.append({'say' : piece})
steps.append(piece)
self._steps = steps
return say_obj.json | Python | nomic_cornstack_python_v1 |
comment This program is used for students to know what classes they have on different
comment days of the school week. It is based off of a 7 block waterfall schedule where
comment the student has 6 classes a day.
comment The program takes in either a preset name/schedule or the different classes in
comment the schedul... | # This program is used for students to know what classes they have on different
# days of the school week. It is based off of a 7 block waterfall schedule where
# the student has 6 classes a day.
# The program takes in either a preset name/schedule or the different classes in
# the schedule, and returns what 'day' of ... | Python | zaydzuhri_stack_edu_python |
function resumekeepalive self expected_state=none timeout=none
begin
call call_operation string resumeKeepAlive expected_state timeout
end function | def resumekeepalive(self, expected_state=None, timeout=None):
super(IxnLdpTargetedRouterV6Emulation, self).call_operation('resumeKeepAlive', expected_state, timeout) | Python | nomic_cornstack_python_v1 |
import coinbasepro as cbp
from coinbasepro.exceptions import CoinbaseAPIError
from coinbase_pro_feed.api_keys import API_KEY , API_SECRET , API_PASS
set BTC = string BTC
set EUR = string EUR
set DAI = string DAI
class CoinbaseConnection
begin
function __init__ self
begin
set public_connection = call PublicClient
set pe... | import coinbasepro as cbp
from coinbasepro.exceptions import CoinbaseAPIError
from coinbase_pro_feed.api_keys import API_KEY, API_SECRET, API_PASS
BTC = 'BTC'
EUR = 'EUR'
DAI = 'DAI'
class CoinbaseConnection:
def __init__(self):
self.public_connection = cbp.PublicClient()
self.perso... | Python | zaydzuhri_stack_edu_python |
comment need to test
function pearlmutter_forward_pass self inputs unflattened_labels feature_sequence_lens direction batch_size hiddens=none outputs=none model=none check_gradient=false stop_at=string output
begin
if model == none
begin
set model = model
end
if hiddens == none or outputs == none
begin
set tuple output... | def pearlmutter_forward_pass(self, inputs, unflattened_labels, feature_sequence_lens, direction, batch_size, hiddens=None, outputs=None, model=None, check_gradient=False, stop_at='output'): #need to test
if model == None:
model = self.model
if hiddens == None or outputs == None:
... | Python | nomic_cornstack_python_v1 |
function output_errors self
begin
set output = list
for error in sorted errors
begin
if length error == 2
begin
set line = string { error at 0 } - Could not find { error at 1 } in map names!
end
else
begin
set line = string { error at 0 } - { error at 1 } : Could not find { error at 2 } in map names!
end
error line
app... | def output_errors(self) -> List[str]:
output = list()
for error in sorted(self.errors):
if len(error) == 2:
line = f"{error[0]} - Could not find {error[1]} in map names!"
else:
line = f"{error[0]} - {error[1]}: Could not find {error[2]} in map name... | Python | nomic_cornstack_python_v1 |
function get_norm_hitcounts self documents
begin
set newList = list
comment if semantic
if string relevant_paras in documents at 0
begin
set hitCount = list comprehension length x at string relevant_paras for x in documents
set minHit = min hitCount
set maxHit = max hitCount
for doc in documents
begin
comment normaliz... | def get_norm_hitcounts(self, documents: list):
newList = []
# if semantic
if "relevant_paras" in documents[0]:
hitCount = [len(x["relevant_paras"]) for x in documents]
minHit = min(hitCount)
maxHit = max(hitCount)
for doc in documents:
... | Python | nomic_cornstack_python_v1 |
comment Import the Twython class
from twython import Twython
import json
comment Load credentials from json file
with open string twitter_credentials.json string r as file
begin
set creds = load json file
end
comment Instantiate an object
set twitter = call Twython creds at string CONSUMER_KEY creds at string CONSUMER_... | # Import the Twython class
from twython import Twython
import json
# Load credentials from json file
with open("twitter_credentials.json", "r") as file:
creds = json.load(file)
# Instantiate an object
twitter = Twython(creds['CONSUMER_KEY'], creds['CONSUMER_SECRET'])
try:
result = twitter.show_us... | Python | zaydzuhri_stack_edu_python |
import timeit
import pandas as pd
import numpy as np
function mssubclass train test cols=list string MSSubClass
begin
for i in tuple train test
begin
for z in cols
begin
set i at z = apply i at z lambda x -> string x
end
end
return tuple train test
end function
function lotfrontage train test
begin
for i in tuple train... | import timeit
import pandas as pd
import numpy as np
def mssubclass(train, test, cols=['MSSubClass']):
for i in (train, test):
for z in cols:
i[z] = i[z].apply(lambda x: str(x))
return train, test
def lotfrontage(train, test):
for i in (train, test):
i['LotFrontage'] = i['LotFr... | Python | zaydzuhri_stack_edu_python |
function load_scheme_files files
begin
for datafile in files
begin
set command = string (load-scm-from-file " + OPENCOG_SOURCE_FOLDER + datafile + string ")
call scheme command
end
end function | def load_scheme_files(files):
for datafile in files:
command = "(load-scm-from-file \"" + \
OPENCOG_SOURCE_FOLDER + datafile + "\")"
scheme(command) | Python | nomic_cornstack_python_v1 |
import re
set list = list string The price of rice is $20 string The price of meat is $50 per kilo string The price of apples is $10 per kilo string The price of oranges is $10 per kilo
set pattern = string ^The price of [a-zA-Z]+ is \$([1-9][0-9]*)
set prices = list
for report in list
begin
set match = match pattern ... | import re
list = [
"The price of rice is $20",
"The price of meat is $50 per kilo",
"The price of apples is $10 per kilo",
"The price of oranges is $10 per kilo"
]
pattern = "^The price of [a-zA-Z]+ is \$([1-9][0-9]*)"
prices = []
for report in list:
match = re.match(pattern, report)
if ... | Python | zaydzuhri_stack_edu_python |
function get_console_output self instance
begin
set vm_ref = call _get_vm_ref_from_the_name name
if vm_ref is none
begin
raise call InstanceNotFound instance_id=id
end
set param_list = dict string id string vm_ref
set base_url = string %s://%s/screen?%s % tuple _scheme _host_ip url encode param_list
set request = call ... | def get_console_output(self, instance):
vm_ref = self._get_vm_ref_from_the_name(instance.name)
if vm_ref is None:
raise exception.InstanceNotFound(instance_id=instance.id)
param_list = {"id": str(vm_ref)}
base_url = "%s://%s/screen?%s" % (self._session._scheme,
... | Python | nomic_cornstack_python_v1 |
function blocks_size self
begin
return CHUNK_WIDTH * CHUNK_HEIGHT * CHUNK_DEPTH * size
end function | def blocks_size(self):
return (self.CHUNK_WIDTH * self.CHUNK_HEIGHT * self.CHUNK_DEPTH *
self._block_struct.size) | Python | nomic_cornstack_python_v1 |
string Modelo Autor
class Author
begin
set name = none
set last_name = none
function create_author self name last_name
begin
set name = name
set last_name = last_name
end function
function __str__ self
begin
return string { name } { last_name }
end function
end class | """
Modelo Autor
"""
class Author:
name = None
last_name = None
def create_author(self,name, last_name):
self.name = name
self.last_name = last_name
def __str__(self):
return f"{self.name} {self.last_name}" | Python | zaydzuhri_stack_edu_python |
function submit self fn value
begin
set tuple job_fn cid = value
set actor = pop _idle_actors
if call _check_and_remove_actor_from_pool actor
begin
set future = call fn actor job_fn
set future_key = if expression is instance future List then tuple future else future
set _future_to_actor at future_key = tuple _next_task... | def submit(self, fn: Any, value: Tuple[Callable[[], ClientRes], str]) -> None:
job_fn, cid = value
actor = self._idle_actors.pop()
if self._check_and_remove_actor_from_pool(actor):
future = fn(actor, job_fn)
future_key = tuple(future) if isinstance(future, List) else futu... | Python | nomic_cornstack_python_v1 |
string // Time Complexity : O(n), where n is the number of elements in the linked list // Space Complexity : O(1) // Did this code successfully run on Leetcode : yes // Any problem you faced while coding this : No
comment Node class
class Node
begin
comment Function to initialise the node object
function __init__ self ... | """
// Time Complexity : O(n), where n is the number of elements in the linked list
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : No
"""
# Node class
class Node:
# Function to initialise the node object
def __init__(self, d... | Python | zaydzuhri_stack_edu_python |
function send_cmd ser command debug=0
begin
call reset_input_buffer
call reset_output_buffer
for b in call iterbytes command
begin
set n = write ser b
if debug
begin
debug format string {} byte ({}) written to port n b
end
sleep 0.1
end
set out = string
set rx = 1
while rx
begin
set rx = read ser in_waiting or 1
if rx... | def send_cmd(ser, command, debug=0):
ser.reset_input_buffer()
ser.reset_output_buffer()
for b in serial.iterbytes(command):
n = ser.write(b)
if debug:
LOGGER.debug("{} byte ({}) written to port".format(n, b))
time.sleep(0.1)
out = ""
rx = 1
while rx:
... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function findMinArrowShots self points
begin
string :type points: List[List[int]] :rtype: int
if length points < 2
begin
return length points
end
sort points key=lambda x -> x at 0
set res = 1
set end = points at 0 at 1
for i in range 1 length points
begin
if points at i at 0 > end
b... | class Solution(object):
def findMinArrowShots(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
if len(points) < 2:
return len(points)
points.sort(key=lambda x: x[0])
res = 1
end = points[0][1]
for i in range(1, len(p... | Python | zaydzuhri_stack_edu_python |
from sklearn.preprocessing import normalize
import KNN
import common
import numpy as np
import scipy.sparse as sps
import PSD
import sys
from MatrixStringKeys import MSK
function kernel_knn_graph K k
begin
set tuple N D = shape
set D = call to_square_dist K
set idx = call find_knn D k want_self=false
set G = call creat... | from sklearn.preprocessing import normalize
import KNN
import common
import numpy as np
import scipy.sparse as sps
import PSD
import sys
from MatrixStringKeys import MSK
def kernel_knn_graph(K, k):
(N, D) = K.shape
D = PSD.to_square_dist(K)
idx = KNN.find_knn(D, k, want_self=False)
G = create_knn_grap... | Python | zaydzuhri_stack_edu_python |
comment temp=10
comment blank=""
comment for i in range(1,11):
comment for j in range(0,temp):
comment print(blank, j, end=" ")
comment for k in range(0,j):
comment blank+=" "
comment print("\n")
comment temp=10-i
set temp = 10
set blanksteg = string
for x in range 1 11
begin
print blanksteg end=string
set blanksteg =... | #temp=10
#blank=""
#for i in range(1,11):
# for j in range(0,temp):
# print(blank, j, end=" ")
# for k in range(0,j):
# blank+=" "
# print("\n")
# temp=10-i
temp=10
blanksteg=" "
for x in range(1,11):
print(blanksteg, end="")
blanksteg+=" "
for j in... | Python | zaydzuhri_stack_edu_python |
function parse_code_new self
begin
string handle posts
for tuple title body_dict in items body_mapping
begin
comment create the query
set current_query = call CodeWrapper title body_dict at 0
comment add post code to query
call set_code body_dict at 1
comment add post tags to query
call set_tags body_dict at 2
comment ... | def parse_code_new(self):
"""handle posts"""
for title, body_dict in self.body_mapping.items():
current_query = CodeWrapper.CodeWrapper(title, body_dict[0]) # create the query
current_query.set_code(body_dict[1]) # add post code to query
current_query.set_tags(body... | Python | nomic_cornstack_python_v1 |
function create_gen_region self
begin
call create_var var_name=string gen_region obj_type=string String q_txt=string Target AWS region t_tip=string Target AWS region def_val=aws_region h_txt=string Target AWS region order_val=1000 m_toggle=string false
end function | def create_gen_region(self):
self.create_var(var_name='gen_region',
obj_type="String",
q_txt="Target AWS region",
t_tip="Target AWS region",
def_val=self.aws_region,
h_txt="Target AWS region",... | Python | nomic_cornstack_python_v1 |
import fnmatch
import os , re
set pattern = call translate string *.jpg | import fnmatch
import os, re
pattern = fnmatch.translate("*.jpg") | Python | zaydzuhri_stack_edu_python |
import collections
set N = integer input
set count = counter string N
for b in range 31
begin
if count == counter string 1 ? b
begin
print string True
exit
end
else
begin
continue
end
end
print string False | import collections
N = int(input())
count = collections.Counter(str(N))
for b in range(31):
if count == collections.Counter(str(1 << b)):
print("True")
exit()
else:
continue
print("False")
| Python | zaydzuhri_stack_edu_python |
import pygame
import random
class Asteroid extends Sprite
begin
string An asteroid that is aware of pygame. A round piece of space debris that comes in 3 sizes. Coordinates are the center of the asteroid.
function __init__ self screen_size size=3
begin
string Create an asteroid. Args: screen_size: a 2-int tuple, the wi... | import pygame
import random
class Asteroid(pygame.sprite.Sprite):
"""An asteroid that is aware of pygame.
A round piece of space debris that comes in 3 sizes.
Coordinates are the center of the asteroid.
"""
def __init__(self, screen_size, size=3):
"""Create an asteroid.
Args:
... | Python | zaydzuhri_stack_edu_python |
comment Sorting Algorithms
comment Neil Denning
string Tim, So, the selection sort is at the bottom. These here are my attempts at "bubble sort". FYI- I ended up sorting from the last index to the first index. I kept getting out of range errors going forward. I used two "for loops", one nested inside the other to sort.... | # Sorting Algorithms
# Neil Denning
'''
Tim,
So, the selection sort is at the bottom. These here are my attempts at "bubble sort".
FYI- I ended up sorting from the last index to the first index. I kept getting out of range errors going forward.
I used two "for loops", one nested inside the other to sort.
The first "... | Python | zaydzuhri_stack_edu_python |
async function read_workers work_pool_name=call Path Ellipsis description=string The work pool name workers=none limit=call LimitBody offset=call Body 0 ge=0 worker_lookups=call Depends WorkerLookups db=call Depends provide_database_interface
begin
async_with call session_context as session
begin
set work_pool_id = awa... | async def read_workers(
work_pool_name: str = Path(..., description="The work pool name"),
workers: schemas.filters.WorkerFilter = None,
limit: int = dependencies.LimitBody(),
offset: int = Body(0, ge=0),
worker_lookups: WorkerLookups = Depends(WorkerLookups),
db: OrionDBInterface = Depends(prov... | Python | nomic_cornstack_python_v1 |
function contains_str cadena1 cadena2
begin
set cad1 = lower cadena1
set cad2 = lower cadena2
set puntuacion = 0
set puntuacion_max = 0
set idx = 0
for val in cad2
begin
if cad1 at idx is val
begin
set idx = idx + 1
if idx is length cad1 - 1
begin
return true
end
end
else
begin
set idx = 0
end
end
return false
end func... | def contains_str(cadena1, cadena2):
cad1 = cadena1.lower()
cad2 = cadena2.lower()
puntuacion = 0
puntuacion_max = 0
idx = 0
for val in cad2:
if cad1[idx] is val:
idx += 1
if idx is len(cad1)-1:
return True
else:
idx = 0
... | Python | nomic_cornstack_python_v1 |
function impute_years cars
begin
return Ellipsis
end function | def impute_years(cars):
return ... | Python | nomic_cornstack_python_v1 |
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import re
import os
import smtplib
from email.message import EmailMessage
import sqlite3
comment creating current atmosphere
class Date
begin
set time = now
set day = string format time time string %A
set tuple date month ... | import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import webbrowser
import re
import os
import smtplib
from email.message import EmailMessage
import sqlite3
# creating current atmosphere
class Date():
time = datetime.datetime.now()
day = time.strftime("%A")
date... | Python | zaydzuhri_stack_edu_python |
function get_all_cur_site_insts
begin
return all
end function | def get_all_cur_site_insts():
return models.Curation_SiteInstance.objects.all() | Python | nomic_cornstack_python_v1 |
function _is_increasing y w
begin
set increasing = call isotonic_regression y w increasing=true
set decreasing = call isotonic_regression y w increasing=false
set increasing_norm = call average increasing - y ^ 2 weights=w
set decreasing_norm = call average decreasing - y ^ 2 weights=w
return increasing_norm <= decreas... | def _is_increasing(y: Sequence[float], w: Sequence[float]) -> bool:
increasing = isotonic.isotonic_regression(y, w, increasing=True)
decreasing = isotonic.isotonic_regression(y, w, increasing=False)
increasing_norm = np.average((increasing - y)**2, weights=w)
decreasing_norm = np.average((decreasing - y)**2, w... | Python | nomic_cornstack_python_v1 |
comment Return true if line segments AB and CD intersect
function intersect a b c d
begin
set v1 = d at 0 - c at 0 * a at 1 - c at 1 - d at 1 - c at 1 * a at 0 - c at 0
set v2 = d at 0 - c at 0 * b at 1 - c at 1 - d at 1 - c at 1 * b at 0 - c at 0
set v3 = b at 0 - a at 0 * c at 1 - a at 1 - b at 1 - a at 1 * c at 0 - ... | # Return true if line segments AB and CD intersect
def intersect(a, b, c, d):
v1 = (d[0] - c[0]) * (a[1] - c[1]) - (d[1] - c[1]) * (a[0] - c[0])
v2 = (d[0] - c[0]) * (b[1] - c[1]) - (d[1] - c[1]) * (b[0] - c[0])
v3 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
v4 = (b[0] - a[0]) * (d[1... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: UTF-8 -*-
import os
import winsound
import time
import serial
import serial.tools.list_ports
import shutil
import openpyxl
string 串口端打印ASR 脚本控制本地唤醒词音频播放 ——判断是否唤醒成功 ——唤醒成功,则播放音频语料(如果没有唤醒成功,则再次播放唤醒音频,直到唤醒成功为止) ——读取串口端打印的ASR结果 ——将此ASR结果和期望值比较 ——完全一样,pass。不一样,fail。 需要注意的是: 1.要统计播放唤醒音频测试; 2.需要统计唤醒成功次数; 3... | # -*- coding: UTF-8 -*-
import os
import winsound
import time
import serial
import serial.tools.list_ports
import shutil
import openpyxl
'''
串口端打印ASR
脚本控制本地唤醒词音频播放
——判断是否唤醒成功
——唤醒成功,则播放音频语料(如果没有唤醒成功,则再次播放唤醒音频,直到唤醒成功为止)
——读取串口端打印的ASR结果
——将此ASR结果和期望值比较
——完全一样,pass。不一样,fail。
需要注意的是:
1.要统计播放唤醒音频测试;
2.需要统计唤醒成功次数;
3.需要打印唤醒成... | Python | zaydzuhri_stack_edu_python |
function await_prepared_test test_fn
begin
decorator wraps test_fn
function run test_class_instance *args **kwargs
begin
call trim_kwargs_from_test_function test_fn kwargs
set loop = call get_event_loop
return call run_until_complete call test_fn test_class_instance keyword kwargs
end function
return run
end function | def await_prepared_test(test_fn):
@functools.wraps(test_fn)
def run(test_class_instance, *args, **kwargs):
trim_kwargs_from_test_function(test_fn, kwargs)
loop = asyncio.get_event_loop()
return loop.run_until_complete(test_fn(test_class_instance, **kwargs))
return run | Python | nomic_cornstack_python_v1 |
function entropy_subsys_approx psi_ab dims sysa bsz=none **kwargs
begin
set lo = call LazyPtrOperator psi_ab dims=dims sysa=sysa
if bsz is none
begin
set bsz = call choose_bsz_from_dims dims sysa
end
return - call tr_xlogx_approx lo bsz=bsz keyword kwargs
end function | def entropy_subsys_approx(psi_ab, dims, sysa, bsz=None, **kwargs):
lo = LazyPtrOperator(psi_ab, dims=dims, sysa=sysa)
if bsz is None:
bsz = choose_bsz_from_dims(dims, sysa)
return - tr_xlogx_approx(lo, bsz=bsz, **kwargs) | Python | nomic_cornstack_python_v1 |
from flask import Flask , jsonify , abort , request , make_response
set app = call Flask __name__
decorator call errorhandler 404
function not_found error
begin
return call make_response call jsonify dict string error string Not found 404
end function
set users = list dict string id 1 ; string username string grim_reap... | from flask import Flask, jsonify, abort, request, make_response
app = Flask(__name__)
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
users = [
{
'id': 1,
#These 'u' characters being appended to an object signifies that the ob... | Python | zaydzuhri_stack_edu_python |
for i in range 0 11
begin
if i % 2 != 0
begin
print i
end
end | for i in range(0, 11):
if i % 2 != 0:
print(i) | Python | jtatman_500k |
function filter_catalog self catalog master_filter
begin
set table = call get_catalog catalog
assert is instance table Table
assert callable master_filter
return filter master_filter generator expression call Body row for row in call iterrows
end function | def filter_catalog(self, catalog, master_filter):
table = self.get_catalog(catalog)
assert isinstance(table, tables.Table)
assert callable(master_filter)
return filter(master_filter,
(body.Body(row) for row in table.iterrows())) | Python | nomic_cornstack_python_v1 |
function _get_error self stanza
begin
if stanza
begin
debug format string Roster request failed: {0} condition_name
end
else
begin
debug string Roster request failed: timeout
end
put call RosterNotReceivedEvent self stanza
end function | def _get_error(self, stanza):
if stanza:
logger.debug(u"Roster request failed: {0}".format(
stanza.error.condition_name))
else:
logger.debug(u"Roster request failed: timeout")
self._event_queue.put(RosterNotReceivedEve... | Python | nomic_cornstack_python_v1 |
function foo bar
begin
string This is docstring This is helpful for explaining the purpose function
set bar = string new value
print bar
end function
comment >> 'new value'
set answer_list = string old value
call foo answer_list
print answer_list
function tuplemodify tup1=tuple 1 2 3 lis1=list 1 2 3
begin
print tup1
se... | def foo(bar):
""" This is docstring
This is helpful for explaining the purpose function
"""
bar = 'new value'
print(bar)
# >> 'new value'
answer_list = 'old value'
foo(answer_list)
print(answer_list)
def tuplemodify(tup1=(1, 2, 3), lis1=[1, 2, 3]):
print(tup1)
tup1 = (1, 2, 3)
... | Python | zaydzuhri_stack_edu_python |
import machine , neopixel , time
import ujson
set np = call NeoPixel call Pin 4 5
comment toggle the board led on or off
function toggle_onboard_led state=string on
begin
set led = call Pin 16 OUT
if state == string on
begin
call off
end
else
begin
call on
end
end function
call toggle_onboard_led
function get_data data... | import machine, neopixel, time
import ujson
np = neopixel.NeoPixel(machine.Pin(4), 5)
# toggle the board led on or off
def toggle_onboard_led(state='on'):
led = machine.Pin(16, machine.Pin.OUT)
if state == 'on':
led.off()
else:
led.on()
toggle_onboard_led()
def get_data(data_file='data.j... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Nov 22 21:49:26 2020 @author: subhrohalder
import pandas as pd
comment importng the dat dataset
set news_df = read csv string Data.csv encoding=string unicode_escape
comment checking if the datset is imbalanced or?
value counts news_df at... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 22 21:49:26 2020
@author: subhrohalder
"""
import pandas as pd
#importng the dat dataset
news_df = pd.read_csv('Data.csv', encoding= 'unicode_escape')
#checking if the datset is imbalanced or?
news_df['Label'].value_counts()
#train test split
tr... | Python | zaydzuhri_stack_edu_python |
from flask import Flask , request , jsonify , redirect
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager , UserMixin , login_user , login_required
set app = call Flask __name__
set config at string SQLALCHEMY_DATABASE_URI = string sqlite:///verysecure.db
set secret_key = b'1Th1nkTh1s1sV3ryS3c... | from flask import Flask, request, jsonify, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///verysecure.db'
app.secret_key = b'1Th1nkTh1s1sV3ryS3cr3t_K3y'
db = SQLAlchemy... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set arr = list - 1 * 1000001
end function | def __init__(self):
self.arr = [-1] * 1000001 | Python | nomic_cornstack_python_v1 |
function getGroupChan self groupNumber
begin
return get call getConf call _genGroupNumName groupNumber list
end function | def getGroupChan(self, groupNumber):
return self.getConf().get(self._genGroupNumName(groupNumber), []) | Python | nomic_cornstack_python_v1 |
import os
comment Gather file name and location from user
function file_info
begin
print string WARNING: If a text file exists with the name you enter it will be overwritten.
set file_name = input string What would you like to name the file:
set file_location = input string Where would you like to save the file(ex. C:\... | import os
# Gather file name and location from user
def file_info():
print("WARNING: If a text file exists with the name you enter it will be overwritten.")
file_name = input("What would you like to name the file: ")
file_location = input("Where would you like to save the file(ex. C:\*insert folder path he... | Python | zaydzuhri_stack_edu_python |
import StringIO
import base64
import binascii
from operator import itemgetter
import operator
from string import ascii_lowercase , ascii_uppercase , ascii_letters
import string
function decodeHexString string
begin
return decode string string hex
end function
function encodeAsciiString string
begin
return encode string... | import StringIO
import base64
import binascii
from operator import itemgetter
import operator
from string import ascii_lowercase, ascii_uppercase, ascii_letters
import string
def decodeHexString(string):
return string.decode("hex")
def encodeAsciiString(string):
return string.encode("hex")
def encodeAsciiSt... | Python | zaydzuhri_stack_edu_python |
function class_probability self class_key row
begin
set product = 1
for i in range length row
begin
set var_value = row at i
set var_mean = variable_means at i at class_key
set var_variance = variable_variances at i at class_key
set value_in_class = call probability_distribution var_value var_mean var_variance
set prod... | def class_probability(self, class_key, row):
product = 1
for i in range(len(row)):
var_value = row[i]
var_mean = self.variable_means[i][class_key]
var_variance = self.variable_variances[i][class_key]
value_in_class = self.probability_distribution(... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import argparse
import copy
import csv
import os
import sys
from random import sample
from random import random
import random as rand
import sys , os
from tqdm import tqdm
import string
import time
import numpy as np
import matplotlib.pyplot as plt
comment Disable
function blockPrint
begin... | #!/usr/bin/env python3
import argparse
import copy
import csv
import os
import sys
from random import sample
from random import random
import random as rand
import sys, os
from tqdm import tqdm
import string
import time
import numpy as np
import matplotlib.pyplot as plt
# Disable
def blockPrint():
sys.stdout = op... | Python | zaydzuhri_stack_edu_python |
comment 1
from flask import Flask
decorator call route string /dictionary/<string:word>
function my_dictionary word
begin
set my_dic = dict string apple string 사과 ; string banana string 바나나 ; string melon string 멜론 ; string cherry string 체리 ; string grapefruit string 자몽 ; string pomegranate string 석류
if word in my_dic
... | # 1
from flask import Flask
@app.route('/dictionary/<string:word>')
def my_dictionary(word):
my_dic = {
'apple': '사과',
'banana': '바나나',
'melon': '멜론',
'cherry': '체리',
'grapefruit': '자몽',
'pomegranate': '석류'
}
if word in my_dic:
return f'{word}은(는) {m... | Python | zaydzuhri_stack_edu_python |
comment -*- coding=utf-8 -*-
comment @Time:
comment @Author: zjh
comment @File: VosSpiderClass.py
comment @Software: PyCharm
import os
import re
import sys
import urllib.request
import queue
from tqdm import tqdm
from bs4 import BeautifulSoup
import xlwt
from threading import Thread
import concurrent.futures
class Craw... | #-*- coding=utf-8 -*-
#@Time:
#@Author: zjh
#@File: VosSpiderClass.py
#@Software: PyCharm
import os
import re
import sys
import urllib.request
import queue
from tqdm import tqdm
from bs4 import BeautifulSoup
import xlwt
from threading import Thread
import concurrent.futures
class Craw:
@staticmethod
def askur... | Python | zaydzuhri_stack_edu_python |
function get cls *args **kwargs
begin
try
begin
set ls = filter *args keyword kwargs
if length ls > 1
begin
raise call MultipleObjectsReturned
end
return filter *args keyword kwargs at 0
end
except IndexError
begin
raise call ObjectDoesNotExist
end
end function | def get(cls, *args, **kwargs):
try:
ls = cls.filter(*args, **kwargs)
if len(ls) > 1:
raise MultipleObjectsReturned()
return cls.filter(*args, **kwargs)[0]
except IndexError:
raise ObjectDoesNotExist() | Python | nomic_cornstack_python_v1 |
function extract obj arr key
begin
if is instance obj dict
begin
for tuple k v in items obj
begin
if is instance v tuple dict list
begin
extract v arr key
end
else
if k == key
begin
append arr v
end
end
end
else
if is instance obj list
begin
for item in obj
begin
extract item arr key
end
end
return arr
end function | def extract(obj, arr, key):
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
extract(v, arr, key)
elif k == key:
arr.append(v)
elif isinstance(obj, list):
... | Python | nomic_cornstack_python_v1 |
import pygame
import sys
from pygame.constants import RESIZABLE
from settings import *
from level import Level
from gamedata import level_0
call init
set screen = call set_mode tuple screen_width screen_height RESIZABLE
call set_caption string Basic Platformer
set clock = call Clock
set level = call Level level_0 scree... | import pygame
import sys
from pygame.constants import RESIZABLE
from settings import *
from level import Level
from gamedata import level_0
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height) , RESIZABLE)
pygame.display.set_caption("Basic Platformer")
clock = pygame.time.Clock()
level = Level... | Python | zaydzuhri_stack_edu_python |
function get_win_drives
begin
if platform == string win
begin
import win32api
set drives = call GetLogicalDriveStrings
set drives = split drives string at slice : - 1 :
return drives
end
else
begin
return list
end
end function | def get_win_drives():
if platform == 'win':
import win32api
drives = win32api.GetLogicalDriveStrings()
drives = drives.split('\000')[:-1]
return drives
else:
return [] | Python | nomic_cornstack_python_v1 |
function _prepare_record self group
begin
string compute record dtype and parents dict fro this group Parameters ---------- group : dict MDF group dict Returns ------- parents, dtypes : dict, numpy.dtype mapping of channels to records fields, records fields dtype
set tuple parents dtypes = tuple parents types
set no_pa... | def _prepare_record(self, group):
""" compute record dtype and parents dict fro this group
Parameters
----------
group : dict
MDF group dict
Returns
-------
parents, dtypes : dict, numpy.dtype
mapping of channels to records fields, record... | Python | jtatman_500k |
function test_low_precision_grads self
begin
call run_subtests dict string max_norm list 1 2.5 ; string norm_type list 1 2 decimal string inf ; string sharding_strategy list FULL_SHARD NO_SHARD ; string use_orig_params list false true _test_low_precision_grads
end function | def test_low_precision_grads(self):
self.run_subtests(
{
"max_norm": [1, 2.5],
"norm_type": [1, 2, float("inf")],
"sharding_strategy": [
ShardingStrategy.FULL_SHARD,
ShardingStrategy.NO_SHARD,
],
... | Python | nomic_cornstack_python_v1 |
function get_predicates
begin
string results = GolrAssociationQuery( rows=0, facet_fields=['relation'] ).exec() facet_counts = results['facet_counts'] relations = facet_counts['relation'] return jsonify([{'id' : BiolinkTerm(c).curie(), 'name' : c, 'definition' : None} for key in relations])
comment Not yet implemented.... | def get_predicates():
"""
results = GolrAssociationQuery(
rows=0,
facet_fields=['relation']
).exec()
facet_counts = results['facet_counts']
relations = facet_counts['relation']
return jsonify([{'id' : BiolinkTerm(c).curie(), 'name' : c, 'definition' : None} for key in rel... | Python | nomic_cornstack_python_v1 |
function sort data axis=- 1 is_ascend=1
begin
set data_buf = call decl_buffer shape dtype string data_buf data_alignment=8
set out_buf = call decl_buffer shape dtype string out_buf data_alignment=8
set out = call extern shape list data lambda ins outs -> call call_packed string tvm.contrib.sort.sort ins at 0 outs at 0 ... | def sort(data, axis=-1, is_ascend=1):
data_buf = tvm.tir.decl_buffer(data.shape, data.dtype, "data_buf", data_alignment=8)
out_buf = tvm.tir.decl_buffer(data.shape, data.dtype, "out_buf", data_alignment=8)
out = te.extern(
data.shape,
[data],
lambda ins, outs: tvm.tir.call_packed(
... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
if num_outputs > 1
begin
set name = join string , list comprehension string ele_sym for ele_sym in self
return string <%s group [%s]> % tuple __name__ name
end
else
begin
return string <%s %s> % tuple __name__ name
end
end function | def __repr__(self):
if self.num_outputs > 1:
name = ', '.join([str(ele_sym) for ele_sym in self])
return '<%s group [%s]>' % (self.__class__.__name__, name)
else:
return '<%s %s>' % (self.__class__.__name__, self.name) | Python | nomic_cornstack_python_v1 |
function test_system_case_1
begin
set reproducer_command = string python reproducer.py --log 2020102200gm-0001-7994-1143916f --player 0 --wind 2 --honba 3 --tile=1s --n 2 --action=draw
set allowed_discards = list string 3s string 5s
set with_riichi = false
set tuple result with_riichi_result = call _run_reproducer stri... | def test_system_case_1():
reproducer_command = "python reproducer.py --log 2020102200gm-0001-7994-1143916f --player 0 --wind 2 --honba 3 --tile=1s --n 2 --action=draw"
allowed_discards = ["3s", "5s"]
with_riichi = False
result, with_riichi_result = _run_reproducer("1.txt", reproducer_command)
asse... | Python | nomic_cornstack_python_v1 |
function BUILD_TUPLE self count
begin
call build_container count tuple
end function | def BUILD_TUPLE(self, count):
self.build_container(count, tuple) | Python | nomic_cornstack_python_v1 |
function event_m10_14_x108 z64=10141700
begin
string State 0,1: Single play and queen defeated?
call IsMultiplayer 8 0 1
call CompareEventFlag 8 114000081 1
assert call ConditionGroup 8
string State 3: Activate key guide
call DisableObjKeyGuide z64 0
string State 2: Was OBJ checked or multi?
call IsObjSearched 0 z64
ca... | def event_m10_14_x108(z64=10141700):
"""State 0,1: Single play and queen defeated?"""
IsMultiplayer(8, 0, 1)
CompareEventFlag(8, 114000081, 1)
assert ConditionGroup(8)
"""State 3: Activate key guide"""
DisableObjKeyGuide(z64, 0)
"""State 2: Was OBJ checked or multi?"""
IsObjSearched(0, z... | Python | nomic_cornstack_python_v1 |
function save_model state output_dir rank epoch
begin
set filename = string checkpoint_epoch + string epoch + string .pth.tar
if rank == 0
begin
save state output_dir + string / + filename
call copyfile output_dir + string / + filename output_dir + string / + string model_epoch + string epoch + string .pth.tar
end
end ... | def save_model(state, output_dir, rank, epoch):
filename='checkpoint_epoch' + str(epoch) + '.pth.tar'
if rank == 0:
torch.save(state, output_dir + '/' + filename)
shutil.copyfile(output_dir + '/' + filename,
output_dir + '/' + 'model_epoch' + str(epoch) + '.pth.tar') | Python | nomic_cornstack_python_v1 |
import os
set man = list
set otherman = list
try
begin
with open string sketch.txt as data
begin
for target1 in data
begin
set target1 = strip target1
try
begin
set tuple role word = split target1 string : 1
print role + string : + word
end
except any
begin
print target1
end
if role == string Man
begin
append man wor... | import os
man=[]
otherman=[]
try:
with open('sketch.txt') as data:
for target1 in data:
target1=target1.strip()
try:
(role,word)=target1.split(':',1)
print(role+':'+word)
except:
print(target1)
if role=="Man":
... | Python | zaydzuhri_stack_edu_python |
comment Author: Kendra Andersen
comment Huff Research Group
comment Created: 02/16/18
comment This file, data_setup.py, defines a series of functions useful for
comment importing, plotting, and organizing data.
comment Import modules
import numpy as np
import matplotlib.pyplot as plt
comment This function allows for au... | # Author: Kendra Andersen
# Huff Research Group
# Created: 02/16/18
# This file, data_setup.py, defines a series of functions useful for
# importing, plotting, and organizing data.
# Import modules
import numpy as np
import matplotlib.pyplot as plt
# This function allows for automatic generation of the directory i... | Python | zaydzuhri_stack_edu_python |
function draw_form self
begin
call draw_form
set menu_advert = string + MENU_KEY + string : Menu, ^Q: Quit
set tuple y x = call display_menu_advert_at
call add_line y x menu_advert call make_attributes_list menu_advert call color_pair 5 columns - x - 1
end function | def draw_form(self):
super(npyscreen.FormBaseNewWithMenus, self).draw_form()
menu_advert = " " + self.__class__.MENU_KEY + ": Menu, ^Q: Quit "
y, x = self.display_menu_advert_at()
self.add_line(y, x, menu_advert, self.make_attributes_list(menu_advert, curses.color_pair(5)),
... | Python | nomic_cornstack_python_v1 |
import io
import os
import re
import time
import traceback
from shutil import rmtree
from uuid import uuid4
import dockerstack_agent.builder
set TMP_DIR = string /tmp/dockerstack/
set SERIAL_PATH = string /dev/virtio-ports/org.clouda.0
class Serial extends object
begin
string A serial object used for receiving file dat... | import io
import os
import re
import time
import traceback
from shutil import rmtree
from uuid import uuid4
import dockerstack_agent.builder
TMP_DIR = '/tmp/dockerstack/'
SERIAL_PATH = '/dev/virtio-ports/org.clouda.0'
class Serial(object):
"""A serial object used for receiving file data from Mortar etc.
... | Python | zaydzuhri_stack_edu_python |
function crawl directory
begin
set pages = dictionary
comment Extract all links from HTML files
for filename in list directory directory
begin
if not ends with filename string .html
begin
continue
end
with open join path directory filename as f
begin
set contents = read f
set links = find all string <a\s+(?:[^>]*?)href... | def crawl(directory):
pages = dict()
# Extract all links from HTML files
for filename in os.listdir(directory):
if not filename.endswith(".html"):
continue
with open(os.path.join(directory, filename)) as f:
contents = f.read()
links = re.findall(r"<a\s+(?... | Python | nomic_cornstack_python_v1 |
function get_nlp_api dataset=none
begin
with open join path call get_project_root string data string nb_nlp.pickle string rb as f
begin
set nlp_data = load pickle f
end
set nlp_arches = list keys nlp_data
return dict string nlp_data nlp_data ; string nlp_arches nlp_arches
end function | def get_nlp_api(dataset=None):
with open(os.path.join(get_project_root(), 'data', 'nb_nlp.pickle'), 'rb') as f:
nlp_data = pickle.load(f)
nlp_arches = list(nlp_data.keys())
return {'nlp_data':nlp_data, 'nlp_arches':nlp_arches} | Python | nomic_cornstack_python_v1 |
import tkinter as tk
from tkinter import *
from card import *
comment import all of the main functions
from mainFunctions import *
comment the main root tk window
set root = call Tk
comment set the basic window functions
title root string Random Card Picker
call geometry string 500x500
call resizable false false
call c... | import tkinter as tk
from tkinter import *
from card import *
from mainFunctions import * #import all of the main functions
root = tk.Tk() #the main root tk window
#set the basic window functions
root.title("Random Card Picker")
root.geometry("500x500")
root.resizable(False, False)
root.config(bg="#00700d")
#create ... | Python | zaydzuhri_stack_edu_python |
function find_orf seq startcod
begin
set starts = call start_points seq startcod
set ends = call start_points seq string _
set orfs = list
for start in starts
begin
for end in ends
begin
if end > start
begin
append orfs seq at slice start : end :
end
end
end
return orfs
end function | def find_orf(seq, startcod):
starts = start_points(seq, startcod)
ends = start_points(seq, "_")
orfs = []
for start in starts:
for end in ends:
if end > start:
orfs.append(seq[start:end])
return orfs | Python | nomic_cornstack_python_v1 |
function start_requests self
begin
comment use args to pass the render arguments to SplashRequest object :
comment lua_source used to defined Lua script
comment wait defined the waiting time
info string [+] Crawl [%s] vuls now ... % module_name
yield call SplashRequest start_url callback=parse endpoint=string execute a... | def start_requests(self):
# use args to pass the render arguments to SplashRequest object :
# lua_source used to defined Lua script
# wait defined the waiting time
logging.info("[+] Crawl [%s] vuls now ..." % self.module_name)
yield SplashRequest(self.start_url,
... | Python | nomic_cornstack_python_v1 |
function __init__ self numOfGames muteOutput randomAI AIforHuman
begin
set numOfGames = numOfGames
set muteOutput = muteOutput
set maxTimeOut = 30
set AIforHuman = AIforHuman
set gameRules = call GameRules
set AIPlayer = call TicTacToeAgent
if randomAI
begin
set AIPlayer = call randomAgent
end
else
begin
set AIPlayer =... | def __init__(self, numOfGames, muteOutput, randomAI, AIforHuman):
self.numOfGames = numOfGames
self.muteOutput = muteOutput
self.maxTimeOut = 30
self.AIforHuman = AIforHuman
self.gameRules = GameRules()
self.AIPlayer = TicTacToeAgent()
if randomAI:
... | Python | nomic_cornstack_python_v1 |
function write_icon self symbol_name drawable_path svg_pen rect
begin
set parent = call xpath_one string //svg:g[@id=" { symbol_name } "]
set path = call SubElement parent string path
set attrib at string d = call _draw_svg_path drawable_path svg_pen call _build_transformation symbol_name rect
end function | def write_icon(
self, symbol_name: str, drawable_path: Any, svg_pen: SVGPathPen, rect: Rect
) -> None:
parent = self.symbol.xpath_one(f'//svg:g[@id="{symbol_name}"]')
path = etree.SubElement(parent, "path")
path.attrib["d"] = self._draw_svg_path(
drawable_path, svg_pen, s... | Python | nomic_cornstack_python_v1 |
function apply_alignment_matrix job matrix
begin
comment Get the SVG-style 6-element vector from the 3x3 matrix
set mat = list matrix at 0 at 0 matrix at 1 at 0 matrix at 0 at 1 matrix at 1 at 1 matrix at 0 at 2 matrix at 1 at 2
comment Only the 'defs' list contains coordinates that need to be transformed
set defs = jo... | def apply_alignment_matrix(job, matrix):
# Get the SVG-style 6-element vector from the 3x3 matrix
mat = [matrix[0][0], matrix[1][0], matrix[0][1], matrix[1][1], matrix[0][2], matrix[1][2]]
# Only the 'defs' list contains coordinates that need to be transformed
defs = job['defs']
for one_def in def... | Python | nomic_cornstack_python_v1 |
string Print First 10 natural numbers using while loop
comment i = 0
comment while i < 10:
comment print(i)
comment i += 1
string taken 10 inputs from user and print average
comment sum1 = 0
comment i = 10
comment while i > 0:
comment print("Enter number")
comment num = int(input())
comment sum1 = sum1 + num
comment i ... | """Print First 10 natural numbers using while loop"""
# i = 0
# while i < 10:
# print(i)
# i += 1
"""taken 10 inputs from user and print average"""
# sum1 = 0
# i = 10
# while i > 0:
# print("Enter number")
# num = int(input())
# sum1 = sum1 + num
# i = i - 1
# print("average is", sum1 / 10)
"... | Python | zaydzuhri_stack_edu_python |
from django.db import models
class Attacks extends Model
begin
set name = call CharField max_length=200
set damage = call CharField max_length=20
end class
comment Create your models here.
class CharacterAttributes extends Model
begin
set GENDERS = tuple tuple string M string Male tuple string F string Female
set RACES... | from django.db import models
class Attacks(models.Model):
name = models.CharField(max_length=200)
damage = models.CharField(max_length=20)
# Create your models here.
class CharacterAttributes(models.Model):
GENDERS = (
('M', 'Male'),
('F', 'Female'),
)
RACES = (
('H','Hu... | Python | zaydzuhri_stack_edu_python |
from PyQt5 import QtCore , QtGui , QtWidgets
from PyQt5.QtCore import Qt , QEvent
from PyQt5.QtWidgets import QMessageBox , QListWidgetItem
from string_checks import StringCheck
from Screens.styles import *
from Screens.home import HomeScreen
from Model.database import Database
from Screens.dialogs import Dialogs
class... | from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt, QEvent
from PyQt5.QtWidgets import QMessageBox, QListWidgetItem
from string_checks import StringCheck
from Screens.styles import *
from Screens.home import HomeScreen
from Model.database import Database
from Screens.dialogs import Dialogs
cla... | Python | zaydzuhri_stack_edu_python |
function test_update_released_doi self
begin
comment Submit a release request to get an entry w/ DOI to update
set kwargs = dict string input join input_dir string pds4_bundle_with_doi_and_contributors.xml ; string node string img ; string submitter string my_user@my_node.gov ; string force true
set doi_label = run key... | def test_update_released_doi(self):
# Submit a release request to get an entry w/ DOI to update
kwargs = {
"input": join(self.input_dir, "pds4_bundle_with_doi_and_contributors.xml"),
"node": "img",
"submitter": "my_user@my_node.gov",
"force": True,
... | Python | nomic_cornstack_python_v1 |
from socket import *
from threading import Thread
import time
comment r2 port
set portr2 = 26612
comment s port
set sPort = 26614
comment link cost between (r2-d, r2-s)
set linkCosts = list 0 * 2
comment r2 client to s and d, server to r1 and r3
function R2_client ip_bind ip_send port temp
begin
comment receive from s
... | from socket import *
from threading import Thread
import time
portr2 = 26612 #r2 port
sPort = 26614 #s port
linkCosts = [0]*2 #link cost between (r2-d, r2-s)
#r2 client to s and d, server to r1 and r3
def R2_client(ip_bind,ip_send,port,temp):
#receive from s
server = socket(AF_INET, SOCK_DGRAM)
server.bind((ip_bi... | Python | zaydzuhri_stack_edu_python |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
import sklearn | import sklearn
| Python | flytech_python_25k |
function anomalyDetectionJob anomalyDef_id manualRun=false
begin
from anomaly.services.alerts import SlackAlert
set runType = if expression manualRun then string Manual else string Scheduled
set anomalyDefinition = get objects id=anomalyDef_id
update anomaly_set published=false
delete
set runStatusObj = call create ano... | def anomalyDetectionJob(anomalyDef_id: int, manualRun: bool = False):
from anomaly.services.alerts import SlackAlert
runType = "Manual" if manualRun else "Scheduled"
anomalyDefinition = AnomalyDefinition.objects.get(id=anomalyDef_id)
anomalyDefinition.anomaly_set.update(published=False)
RCAAnomaly... | Python | nomic_cornstack_python_v1 |
import socket
set HOST = string 192.168.28.55
set PORT = 8080
set serverSocket = call socket AF_INET SOCK_STREAM
call bind tuple HOST PORT
call listen
print string Server is listening on port + string PORT
while true
begin
set tuple connection address = call accept
set req = decode call recv 1024
comment print(req)
set... | import socket
HOST = "192.168.28.55"
PORT = 8080
serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind((HOST, PORT))
serverSocket.listen()
print("Server is listening on port " + str(PORT))
while True:
connection, address = serverSocket.accept()
req = connection.recv(1024).decode... | Python | zaydzuhri_stack_edu_python |
import math
import itertools
set N = integer input
set cords = list
set s = split input string
for y in s
begin
append cords list integer y
end
set s = split input string
set i = 0
for x in s
begin
append cords at i integer x
set i = i + 1
end
set cords = sorted cords key=lambda a -> a at 0
function orderedOb a b c d
... | import math
import itertools
N = int(input())
cords = []
s = input().split(" ")
for y in s:
cords.append([int(y)])
s = input().split(" ")
i = 0
for x in s:
cords[i].append(int(x))
i += 1
cords = sorted(cords, key= lambda a: a[0])
def orderedOb(a,b,c,d):
if ordTri(a,b,c) and ordTri(b,c,d) and ordTri(... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python3
import sys
set n = integer strip read line stdin
set total = 0
for i in range 0 n
begin
set a = strip read line stdin
set number = integer a at slice : - 1 :
set power = integer a at - 1
set total = total + number ^ power
end
print total | #! /usr/bin/python3
import sys
n = int(sys.stdin.readline().strip())
total = 0
for i in range(0, n):
a = sys.stdin.readline().strip()
number = int(a[:-1])
power = int(a[-1])
total += number ** power
print(total) | 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.