code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment -*- coding: utf-8 -*-
import sys
import numpy as np
from collections import defaultdict
from NeuralNetwork import NNNetwork
function get_feature words
begin
set feature = dict
for word in words
begin
set feature_id = string UNI: + word
if feature_id not in feature
begin
set feature at feature_id = 0
end
set fe... | # -*- coding: utf-8 -*-
import sys
import numpy as np
from collections import defaultdict
from NeuralNetwork import NNNetwork
def get_feature(words):
feature = {}
for word in words:
feature_id = u"UNI:" + word
if feature_id not in feature:
feature[feature_id] = 0
feature[fea... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mar 18 2020 #GRÁFICA DEL FRACTAL DE MANDELBROT *PILLOW,*RGBA @author: AndrsRamos
from PIL import Image
function mandelbrot c j
begin
set z = 0
for i in range j
begin
set z = z * z + c
if absolute z > 2
begin
return i
end
end
return 0
end function
comment paleta de colores... | # -*- coding: utf-8 -*-
"""
Created on Mar 18 2020
#GRÁFICA DEL FRACTAL DE MANDELBROT
*PILLOW,*RGBA
@author: AndrsRamos
"""
from PIL import Image
def mandelbrot(c,j):
z=0
for i in range(j):
z = z*z + c
if abs(z)>2:
return i
return 0
#paleta de colores
colores=[... | Python | zaydzuhri_stack_edu_python |
comment imports
from flask import Flask , jsonify , request
from flask_sqlalchemy import SQLAlchemy
comment Set up application
set app = call Flask __name__
set config at string SQLALCHEMY_DATABASE_URI = string sqlite:///database.db
set db = call SQLAlchemy app
comment Model for comment table
class Comment extends Mode... | # imports
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
# Set up application
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db"
db = SQLAlchemy(app)
# Model for comment table
class Comment(db.Model):
id = db.Column(db.Integer, primary_key=True... | Python | jtatman_500k |
set motorcycles = list string honda string yamaha string suzuki
print motorcycles
append motorcycles string dukati
print motorcycles
insert motorcycles 2 string bmw
print motorcycles
del motorcycles at 1
print motorcycles
set popped_motorcycle = pop motorcycles
print motorcycles
print popped_motorcycle
remove motorcycl... | motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('dukati')
print(motorcycles)
motorcycles.insert(2, 'bmw')
print(motorcycles)
del motorcycles[1]
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
motorcycles.remove('bmw')
print(motorcycl... | Python | zaydzuhri_stack_edu_python |
comment The MIT License (MIT)
comment Copyright (c) 2019 Simon Kassing
comment Permission is hereby granted, free of charge, to any person obtaining a copy
comment of this software and associated documentation files (the "Software"), to deal
comment in the Software without restriction, including without limitation the ... | # The MIT License (MIT)
#
# Copyright (c) 2019 Simon Kassing
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mod... | Python | zaydzuhri_stack_edu_python |
comment coding utf-8-
set numero = input string ingresa un numero:
if numero % 2 == 0
begin
print string el numero + numero + string es nulo
end
else
if numero >= - 10 and numero <= 40
begin
print string el numero + numero + string es positivo
end
else
begin
print string el numero + numero + string es negativo
end | #coding utf-8-
numero=input("ingresa un numero: ")
if(numero%2==0):
print("el numero " + numero + " es nulo ")
else:
if(numero >=-10 and numero <=40):
print("el numero " + numero + " es positivo")
else:
print("el numero " + numero + " es negativo")
| Python | zaydzuhri_stack_edu_python |
function _set_config self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=yc_config_openconfig_mpls_te__mpls_lsps_constrained_path_named_explicit_paths_named_explicit_path_config is_container=string container yang_name=string config parent=s... | def _set_config(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_config_openconfig_mpls_te__mpls_lsps_constrained_path_named_explicit_paths_named_explicit_path_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_help... | Python | nomic_cornstack_python_v1 |
function make_column options name column
begin
comment (ElasticsearchFDWOptions, str, multicorn.ColumnDefinition) -> Column
assert name not in set literal rowid_column score_column query_column msg format string Programmer error: bad name passed to make_column {name} name=name
if upper base_type_name in set literal str... | def make_column(options, name, column):
# (ElasticsearchFDWOptions, str, multicorn.ColumnDefinition) -> Column
assert name not in {
options.rowid_column,
options.score_column,
options.query_column,
}, "Programmer error: bad name passed to make_column {name}".format(name=name)
if... | Python | nomic_cornstack_python_v1 |
comment Performing real-time audio processing using PyAudio.
import pyaudio
comment Use PyAudio for real-time audio processing.
comment Implement audio recording, playback, and analysis. | # Performing real-time audio processing using PyAudio.
import pyaudio
# Use PyAudio for real-time audio processing.
# Implement audio recording, playback, and analysis.
| Python | flytech_python_25k |
function testTooLarge self
begin
assert raises OutOfRangeError getShowCommand 4294967296
end function | def testTooLarge(self):
self.assertRaises(shellLinkParser.OutOfRangeError, shellLinkParser.getShowCommand, 4294967296) | Python | nomic_cornstack_python_v1 |
function hydrate self bundle
begin
comment Update the fabric
if string fabric in data and call has_perm string acknowledgements.change_fabric
begin
try
begin
set fabric = get objects pk=data at string fabric at string id
set fabric = fabric
info format string {0} changed fabric to {1} description description
end
except... | def hydrate(self, bundle):
#Update the fabric
if "fabric" in bundle.data and bundle.request.user.has_perm('acknowledgements.change_fabric'):
try:
fabric = Fabric.objects.get(pk=bundle.data["fabric"]["id"])
bundle.obj.fabric = fabric
lo... | Python | nomic_cornstack_python_v1 |
function setStyle self style
begin
set style = style
for key in style
begin
set tmp_list = map capitalize split key string -
set method = string set + join string tmp_list
if has attribute canvasContext method and style at key != string none
begin
call get attribute canvasContext method style at key
end
end
comment sa... | def setStyle(self, style):
self.canvasContext.style = style
for key in style:
tmp_list = map(str.capitalize, key.split("-"))
method = "set" + "".join(tmp_list)
if hasattr(self.canvasContext, method) and style[key] != "none":
getattr(self.canvasCo... | Python | nomic_cornstack_python_v1 |
function CenterMap self lon lat opt_zoom=none
begin
if canvas
begin
flush self
delete ALL
set tiles = dict
set tktiles = dict
end
set tuple width height = call GetMapSize
if opt_zoom is not none
begin
set level = opt_zoom
end
comment From maps/api/javascript/geometry/mercator_projection.js
set mercator_range = 256.0
... | def CenterMap(self, lon, lat, opt_zoom=None):
if self.canvas:
self.Flush()
self.canvas.delete(Tkinter.ALL)
self.tiles = {}
self.tktiles = {}
width, height = self.GetMapSize()
if opt_zoom is not None:
self.level = opt_zoom
# From maps/api/javascript/geometry/mercator_projec... | Python | nomic_cornstack_python_v1 |
comment scales the pixels. So if its run on the phone or on ocmputer, it has same ratio
from kivy.metrics import sp
from kivy.core.window import Window
from kivy.app import App
from kivy.clock import Clock
from kivy import properties as kp
from kivy.uix.widget import Widget
from collections import defaultdict
from kivy... | from kivy.metrics import sp #scales the pixels. So if its run on the phone or on ocmputer, it has same ratio
from kivy.core.window import Window
from kivy.app import App
from kivy.clock import Clock
from kivy import properties as kp
from kivy.uix.widget import Widget
from collections import defaultdict
from kivy... | Python | zaydzuhri_stack_edu_python |
function glcm_stat_contrast glcm_matrix
begin
set it = call nditer glcm_matrix flags=list string multi_index
set accum = 0
while not finished
begin
set accum = accum + glcm_matrix at multi_index * power diff np multi_index 2
call iternext
end
return accum
end function | def glcm_stat_contrast(glcm_matrix):
it = np.nditer(glcm_matrix, flags=['multi_index'])
accum = 0
while (not it.finished):
accum += glcm_matrix[it.multi_index] * pow(np.diff(it.multi_index), 2)
it.iternext()
return accum | Python | nomic_cornstack_python_v1 |
function runInThread self
begin
set thread = thread target=__requestLoop
set daemon = true
start thread
debug string broadcast server loop running in own thread
return thread
end function | def runInThread(self):
thread = threading.Thread(target=self.__requestLoop)
thread.daemon = True
thread.start()
log.debug("broadcast server loop running in own thread")
return thread | Python | nomic_cornstack_python_v1 |
function max_subarray_sum arr k
begin
set start = 0
set end = 0
set maxSum = 0
set currentSum = 0
while end < length arr
begin
set currentSum = currentSum + arr at end
if currentSum > maxSum
begin
set maxSum = currentSum
end
if end - start + 1 >= k
begin
if currentSum > 0
begin
set currentSum = currentSum - arr at star... | def max_subarray_sum(arr, k):
start = 0
end = 0
maxSum = 0
currentSum = 0
while end < len(arr):
currentSum += arr[end]
if currentSum > maxSum:
maxSum = currentSum
if end - start + 1 >= k:
if currentSum > 0:
currentSum -= arr[start]
... | Python | jtatman_500k |
import numpy as np
function sigmoid x
begin
return 1 / 1 + exp - x
end function
function sigmoid_derivative x
begin
return x * 1 - x
end function
set training_inputs = array list list 0 0 list 0 1 list 1 0 list 1 1
set training_outputs = T
seed 1
set weights = random tuple 2 1
set bias = 0
print string random staring w... | import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1-x)
training_inputs = np.array([[0,0],
[0,1],
[1,0],
[1,1]])
training_outputs = np.array([[0,0,0,1]]).T
np.... | Python | zaydzuhri_stack_edu_python |
import sys
import json
import requests
function verify_auth
begin
string Verify which AMP cloud the provided client_id and api_key are valid for. Return the Domain and Region Name for the cloud the credentials are valid in.
set region_domains = dict string api.amp.cisco.com string North America ; string api.apjc.amp.ci... | import sys
import json
import requests
def verify_auth():
""" Verify which AMP cloud the provided client_id and api_key are valid for.
Return the Domain and Region Name for the cloud the credentials are valid in.
"""
region_domains = {'api.amp.cisco.com':'North America',
... | Python | zaydzuhri_stack_edu_python |
comment -*-coding:utf-8 -*-
import wiringpi2 as wiringpi
import FaBo9Axis_MPU9250
import time
import serial
import sys
from math import degrees , radians , atan , atan2 , sin , cos , pi , asin , sqrt
comment initialize setting
comment initialize wiringPi
call wiringPiSetup
comment alternative function = PWM
call pinMod... | #-*-coding:utf-8 -*-
import wiringpi2 as wiringpi
import FaBo9Axis_MPU9250
import time
import serial
import sys
from math import degrees, radians, atan, atan2, sin, cos, pi, asin, sqrt
#initialize setting
wiringpi.wiringPiSetup() #initialize wiringPi
wiringpi.pinMode(23, 2) # alternative function = PWM
wiringpi.pinMo... | Python | zaydzuhri_stack_edu_python |
string Name: Thomas Scola I certify this is my work and my work only lab7.py
import math
function cash_conversion
begin
set cash = eval input string Input cash amount
set cash_float = format string {:.2f} cash
print string $ + cash_float
end function
function encode
begin
set inputSentence = string input string Please ... | """
Name: Thomas Scola
I certify this is my work and my work only
lab7.py
"""
import math
def cash_conversion():
cash = eval(input("Input cash amount"))
cash_float = "{:.2f}".format(cash)
print("$" +cash_float)
def encode():
inputSentence = str(input("Please enter a string of plaintext:"))
key_valu... | Python | zaydzuhri_stack_edu_python |
import numpy as np
class MultiAgentCoop extends object
begin
string Gridworld where agents get rewards when they make other agents reach goals Agents start in any position where there isn't a landmark i.e. there can be several agent per grid cell Landmarks are placed on distinct grid cells At each timestep, each agent ... | import numpy as np
class MultiAgentCoop(object):
"""
Gridworld where agents get rewards when they make other agents reach goals
Agents start in any position where there isn't a landmark
i.e. there can be several agent per grid cell
Landmarks are placed on distinct grid cells
At each timestep, e... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Jan 12 08:56:48 2021 @author: ErTodd
function yrp2poe yrp_list investigation_time
begin
string Convert from year return period to probability of exceedence. Parameters ---------- yrp_list : LIST List of year (int or float) return periods from which to calculate probab... | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 12 08:56:48 2021
@author: ErTodd
"""
def yrp2poe(yrp_list, investigation_time):
'''
Convert from year return period to probability of exceedence.
Parameters
----------
yrp_list : LIST
List of year (int or float) return periods from which to c... | Python | zaydzuhri_stack_edu_python |
function compose f g
begin
string Chain functions
set fun = lambda -> f dist call g *args keyword kwargs
set __name__ = string %s o %s % tuple __name__ __name__
return fun
end function | def compose(f, g):
"""Chain functions"""
fun = lambda *args, **kwargs: f(g(*args, **kwargs))
fun.__name__ = "%s o %s" % (f.__name__, g.__name__)
return fun | Python | jtatman_500k |
function make_flat cube mask use=none
begin
comment TODO: SPEED UP!!
from scipy import ndimage
if use is none
begin
comment select a 1000 frames randomly throughout cube
set n = max length cube 1000
set use = random integer 0 length cube n
end
set struct = ones tuple 3 3
set flat = ones shape at slice 1 : :
for tuple ... | def make_flat(cube, mask, use=None):
# TODO: SPEED UP!!
from scipy import ndimage
if use is None:
# select a 1000 frames randomly throughout cube
n = max(len(cube), 1000)
use = np.random.randint(0, len(cube), n)
struct = np.ones((3, 3))
flat = np.ones(cube.shape[1:])
f... | Python | nomic_cornstack_python_v1 |
function left_distance self
begin
return x
end function | def left_distance(self):
return self.x | Python | nomic_cornstack_python_v1 |
comment a bot that roams in and out of its channels
from ircbot import IrcBot
import random
class RoamBot extends IrcBot
begin
function __init__ self jo=0.5 po=0.5 **kwargs
begin
call __init__ keyword kwargs
set current = none
set partmsg = string roaming
set joinodds = jo
set partodds = po
end function
function connec... | #a bot that roams in and out of its channels
from ircbot import IrcBot
import random
class RoamBot(IrcBot):
def __init__(self, jo=0.5, po=0.5, **kwargs):
super().__init__(**kwargs)
self.current = None
self.partmsg = "roaming"
self.joinodds = jo
self.partodds = po
def c... | Python | zaydzuhri_stack_edu_python |
function waitbuffer self ptr bufsize
begin
set timeout = call c_int 20000
call AT_WaitBuffer AT_H call byref ptr call byref bufsize timeout
end function | def waitbuffer(self, ptr, bufsize):
timeout = ct.c_int(20000)
self.lib.AT_WaitBuffer(self.AT_H, ct.byref(ptr), ct.byref(bufsize),
timeout) | Python | nomic_cornstack_python_v1 |
function parseCsvFile filename sep=string , delimiter=none
begin
set col_types = dictionary fn_name=str nthreads=int with_cg=bool mean=float stddev=float max=float min=float mean_per_nodes=float stddev_per_nodes=float
set seq = read csv filename header=0 sep=sep delim_whitespace=false quoting=2 index_col=list 0 1 2 dty... | def parseCsvFile(filename, sep=",", delimiter=None):
col_types = dict(
fn_name=str,
nthreads=int,
with_cg=bool,
mean=float,
stddev=float,
max=float,
min=float,
mean_per_nodes=float,
stddev_per_nodes=float,
)
seq = pd.read_csv(
... | Python | nomic_cornstack_python_v1 |
function test_edge_change_anchor_valuerror db_3_vertices
begin
set tuple db v1 v2 v3 = db_3_vertices
set e1 = call Edge v1 v2
with raises ValueError
begin
call change_anchor v3
end
end function | def test_edge_change_anchor_valuerror(db_3_vertices):
db, v1, v2, v3 = db_3_vertices
e1 = Edge(v1, v2)
with pytest.raises(ValueError):
e1.change_anchor(v3) | Python | nomic_cornstack_python_v1 |
function crossplot dat keys=none lognorm=true bins=25 figsize=tuple 12 12 colourful=true focus_stage=none denominator=none mode=string hist2d cmap=none **kwargs
begin
string Plot analytes against each other. The number of plots is n**2 - n, where n = len(keys). Parameters ---------- dat : dict A dictionary of key: data... | def crossplot(dat, keys=None, lognorm=True, bins=25, figsize=(12, 12),
colourful=True, focus_stage=None, denominator=None,
mode='hist2d', cmap=None, **kwargs):
"""
Plot analytes against each other.
The number of plots is n**2 - n, where n = len(keys).
Parameters
-------... | Python | jtatman_500k |
comment !/usr/bin/python
set animals = dict string duck string quack ; string cow string moo ; string platypus string ... ; string dragon string HEY Y'ALL!! ; string japanese hornet string I WILL DESTROY YOU ALL
function song animals
begin
for i in animals
begin
print format string Old MacDonald had a farm, Ee-igh, Ee-... | #!/usr/bin/python
animals = {'duck': 'quack', 'cow': 'moo', 'platypus': '...', 'dragon': "HEY Y'ALL!!", 'japanese hornet': 'I WILL DESTROY YOU ALL'}
def song(animals):
for i in animals:
print("Old MacDonald had a farm, Ee-igh, Ee-igh, Oh!\nAnd on that farm he had a {0}, Ee-igh, Ee-igh, Oh!\nWith a {1}, {1} here and... | Python | zaydzuhri_stack_edu_python |
function positive x
begin
return max 0 call square x - 100
end function | def positive(x):
return max(0, square(x) - 100) | Python | nomic_cornstack_python_v1 |
comment lambda 表达式,返回匿名函数
function make_incrementor n
begin
return lambda x -> x + n
end function
set f = call make_incrementor 100
print f dist 0
print f dist 2
function genrateResponse
begin
return lambda x y -> x * y
end function
set r = call genrateResponse
print call r 100 200
comment 用户处理非常简单的逻辑
set pairs = list ... | # lambda 表达式,返回匿名函数
def make_incrementor(n) :
return lambda x: x + n
f = make_incrementor(100)
print(f(0))
print(f(2))
def genrateResponse() :
return lambda x, y : x * y
r = genrateResponse()
print(r(100, 200))
# 用户处理非常简单的逻辑
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key= lambda ... | Python | zaydzuhri_stack_edu_python |
function act self state
begin
set suggested_action = call act state
set selected_action = call select_action suggested_action
return selected_action
end function | def act(self, state):
suggested_action = self.learning_element.act(state)
selected_action = self.exploration_element.select_action(suggested_action)
return selected_action | Python | nomic_cornstack_python_v1 |
from pathlib import Path
from typing import Tuple
import numpy as np
import os
from PIL import Image
import re
comment IMPORTANT
comment in this folder, only already functional faces will be stored.
comment If you need something like face detection, DO NOT store those images here
set DATA_PATH = string training_data/
s... | from pathlib import Path
from typing import Tuple
import numpy as np
import os
from PIL import Image
import re
# IMPORTANT
# in this folder, only already functional faces will be stored.
# If you need something like face detection, DO NOT store those images here
DATA_PATH = "training_data/"
WIDTH, HEIGHT = 256, 256
... | Python | zaydzuhri_stack_edu_python |
function __init__ self name bytes
begin
set name = name
set bytes = bytes
if not call is_elf
begin
print string [!]: File is not an ELF file
raise call ValueError string Specified file is not an ELF File
end
set elf_header = call ELF_HEADER bytes
set program_headers = call read_program_headers
set section_headers = cal... | def __init__(self, name: str, bytes: bytearray) -> None:
self.name = name
self.bytes = bytes
if not self.is_elf():
print("[!]: File is not an ELF file")
raise ValueError("Specified file is not an ELF File")
self.elf_header = ELF_HEADER(bytes)
self.program_... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
import COVID19_SIQR as siqr
function susceptible result casename
begin
set S = list comprehension result at i at 0 for i in range 36000
figure dpi=100
plot times S label=string S
title plt string S:susceptible { casename }
x label str... | import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
import COVID19_SIQR as siqr
def susceptible(result, casename:str):
S = [result[i][0] for i in range(36000)]
plt.figure(dpi=100)
plt.plot(times, S,label="S")
plt.title(f"S:susceptible {casename}")
plt.xl... | Python | zaydzuhri_stack_edu_python |
function hide self
begin
return call setDisplayFlag false
end function | def hide(self):
return self.setDisplayFlag(False) | Python | nomic_cornstack_python_v1 |
function shell_command cmd dry_run=false
begin
if cmd at 0 == string /usr/bin/rsync
begin
if dry_run
begin
set cmd = list cmd at 0 string -n + cmd at slice 1 : :
end
info string run: %s join string cmd
check call cmd
end
else
begin
info string run: %s join string cmd
if not dry_run
begin
check call cmd
end
end
end ... | def shell_command(cmd, dry_run=False):
if cmd[0] == '/usr/bin/rsync':
if dry_run:
cmd = [cmd[0], '-n'] + cmd[1:]
LOGGER.info('run: %s', ' '.join(cmd))
subprocess.check_call(cmd)
else:
LOGGER.info('run: %s', ' '.join(cmd))
if not dry_run:
subprocess... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string Note: 1. The correctness is not ensured, just take a look at the thoughts. 2. The code is not optimized, so it is very slow..
import math
import matplotlib.pyplot as plt
from neural_network import Unit , Gate , Network , Neuron , NeuralNetwork , BasicCla... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Note:
1. The correctness is not ensured, just take a look at the thoughts.
2. The code is not optimized, so it is very slow..
"""
import math
import matplotlib.pyplot as plt
from neural_network import Unit, Gate, Network, Neuron, NeuralNetwork, BasicClassifier
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sat Sep 28 05:53:07 2019 Newton-Fractal example code. Solves the Newton-method for a given function on a grid of complex initial guesses. Produces a color-coded graph of the fractal. Includes several presets for function, but is easily extend... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 28 05:53:07 2019
Newton-Fractal example code.
Solves the Newton-method for a given function
on a grid of complex initial guesses.
Produces a color-coded graph of the fractal.
Includes several presets for function, but is easily extendable.
@author... | Python | zaydzuhri_stack_edu_python |
from pyb import UART
import json
import time
class Network
begin
function __init__ self
begin
set network = call UART 6 115200 read_buf_len=200
end function
function count self
begin
return any
end function
function receive self
begin
call sleep_ms 100
set count = count self
set data = decode read network count
set dat... | from pyb import UART
import json
import time
class Network():
def __init__(self):
self.network = UART(6, 115200, read_buf_len=200)
def count(self):
return self.network.any()
def receive(self):
time.sleep_ms(100)
count = self.count()
data = self.network.read(count).decode()
data = data.strip()
ret... | Python | zaydzuhri_stack_edu_python |
import cv2
from PIL import Image
set img = call imread string Face.jpg
set Row = 300
set Col = 300
set threshold = 180
set img = call resize img tuple Col Row
for row in range Row
begin
for col in range Col
begin
if img at row at col at 0 > threshold and img at row at col at 1 > threshold and img at row at col at 2 > t... | import cv2
from PIL import Image
img = cv2.imread('Face.jpg')
Row = 300
Col = 300
threshold = 180
img = cv2.resize(img, (Col, Row))
for row in range(Row):
for col in range(Col):
if img[row][col][0] > threshold and img[row][col][1] > threshold and img[row][col][2] > threshold:
#if (img[row][col][0... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import scipy.linalg as splinalg
comment mat_a
comment ユークリッドノルム
print string ||mat_a||_2 = norm mat_a
print string ||mat_a||_2 = norm mat_a
comment 1ノルム
print string ||mat_a||_1 = norm mat_a 1
print string ||mat_a||_1 = norm mat_a 1
comment 無限大ノルム
print string ||mat_a||_inf = norm mat_a inf
print str... | import numpy as np
import scipy.linalg as splinalg
# mat_a
# ユークリッドノルム
print('||mat_a||_2 = ', np.linalg.norm(mat_a))
print('||mat_a||_2 = ', splinalg.norm(mat_a))
# 1ノルム
print('||mat_a||_1 = ', np.linalg.norm(mat_a, 1))
print('||mat_a||_1 = ', splinalg.norm(mat_a, 1))
# 無限大ノルム
print('||mat_a||_inf = ', np.linalg.n... | Python | zaydzuhri_stack_edu_python |
comment program to mask two images
from PIL import Image
set chess = open string G:\black.jpg
set alpha = open string G:\letters.png
comment print("the chess size is {}".format(chess.size))
comment print("the alpha size is {}".format(alpha.size))
set resize_alpha = call resize size
call putalpha 100
call putalpha 100
c... | #program to mask two images
from PIL import Image
chess = Image.open('G:\\black.jpg')
alpha = Image.open('G:\\letters.png')
#print("the chess size is {}".format(chess.size))
#print("the alpha size is {}".format(alpha.size))
resize_alpha = alpha.resize((chess.size))
chess.putalpha(100)
resize_alpha.putalpha(100)
chess... | Python | zaydzuhri_stack_edu_python |
function is_palindrome text
begin
if length text <= 1
begin
return true
end
if text at 0 == text at - 1
begin
return call is_palindrome text at slice 1 : - 1 :
end
return false
end function
if __name__ == string __main__
begin
if call is_palindrome input string Enter a text:
begin
print string Yes
end
else
begin
print ... | def is_palindrome(text):
if len(text) <= 1:
return True
if text[0] == text[-1]:
return is_palindrome(text[1: -1])
return False
if __name__ == '__main__':
if is_palindrome(input('Enter a text: ')):
print('Yes')
else:
print('No')
| Python | zaydzuhri_stack_edu_python |
import os
import sys
import ijson
import functools
import numpy as np
import nltk
from nltk.stem.lancaster import LancasterStemmer
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
set part = dict string N string n ; string V... | import os
import sys
import ijson
import functools
import numpy as np
import nltk
from nltk.stem.lancaster import LancasterStemmer
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
part = {
'N' : 'n',
... | Python | zaydzuhri_stack_edu_python |
comment break
string i= 0 while i< 10: print(i) i += 1 if i == 5: continue i=0 while True: secim = input("Sayilarin toplamlarini durdurmak icin 'q' yazınız :") if secim == 'q': break i = i +1 print(i) for i in range(10): print(i) if i ==7: break
comment continue
for i in range 1 20
begin
if i % 4 == 0
begin
continue
en... | #break
"""
i= 0
while i< 10:
print(i)
i += 1
if i == 5:
continue
i=0
while True:
secim = input("Sayilarin toplamlarini durdurmak icin 'q' yazınız :")
if secim == 'q':
break
i = i +1
print(i)
for i in range(10):
print(i)
if i ==7:
break"""... | Python | zaydzuhri_stack_edu_python |
function acq self session params
begin
set time_encoder_published = 0
set counter_list = list
set counter_index_list = list
set quad_list = list
set quad_counter_list = list
set received_time_list = list
with call acquire_timeout timeout=0 job=string acq as acquired
begin
if not acquired
begin
warn format string C... | def acq(self, session, params):
time_encoder_published = 0
counter_list = []
counter_index_list = []
quad_list = []
quad_counter_list = []
received_time_list = []
with self.lock.acquire_timeout(timeout=0, job='acq') as acquired:
if not acquired:
... | Python | nomic_cornstack_python_v1 |
string This script discussess the basic math operations used in Python.
comment Only necessary in Python 2
from __future__ import print_function
comment Import biolog module for log messages
import biolog
info 3 * string + 20 * string # + string MATH + 20 * string # + 3 * string
comment Basic operations
comment Add
in... | """This script discussess the basic math operations used in Python."""
from __future__ import print_function # Only necessary in Python 2
import biolog # Import biolog module for log messages
biolog.info(3*'\t' + 20*'#' + 'MATH' + 20*'#' + 3*'\n')
# Basic operations
biolog.info("Adding 132 + 123 : {}".format((132... | Python | zaydzuhri_stack_edu_python |
function visualize detector
begin
set tuple _pixelpositions _pixelareavector _dshape result = detector
set title = string Detector image
figure
title plt title
image show result cmap=string gray origin=string lower
call colorbar shrink=0.92
call xticks list
call yticks list
show
end function | def visualize(detector):
_pixelpositions, _pixelareavector, _dshape, result = detector
title = "Detector image"
plt.figure()
plt.title(title)
plt.imshow(result, cmap='gray', origin='lower')
plt.colorbar(shrink=.92)
plt.xticks([])
plt.yticks([])
plt.show() | Python | nomic_cornstack_python_v1 |
function mutual_friends self target
begin
return all
end function | def mutual_friends(self, target):
return db.session.query(Person).filter(
Person.id.in_([
conn.to_person_id
for conn in
db.session.query(Connection).filter(
(Connection.from_person_id == self.id) |
(Connection.fr... | Python | nomic_cornstack_python_v1 |
string Create portable serialized representations of Python objects. See module cPickle for a (much) faster implementation. See module copy_reg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) ->... | """Create portable serialized representations of Python objects.
See module cPickle for a (much) faster implementation.
See module copy_reg for a mechanism for registering custom picklers.
See module pickletools source for extensive comments.
Classes:
Pickler
Unpickler
Functions:
dump(object, file)
... | Python | jtatman_500k |
string Created on Oct 19, 2017 @author: jennifersikos
import re
import codecs
from frame_instance import FrameInstance
from role_instance import RoleInstance
from sentence_instance import SentenceInstance
import xml.etree.ElementTree as et
class ReadSingleFileFrames extends object
begin
string This class reads a single... | '''
Created on Oct 19, 2017
@author: jennifersikos
'''
import re
import codecs
from frame_instance import FrameInstance
from role_instance import RoleInstance
from sentence_instance import SentenceInstance
import xml.etree.ElementTree as et
class ReadSingleFileFrames(object):
'''
This class reads a single par... | Python | zaydzuhri_stack_edu_python |
comment David Martinez
comment Follow the “eyes_cropped.py” in the HOP09 Manipulating Images
comment and GUI Automation. In the similar way use the image which
comment was used in the previous question and create a program which
comment displays image in the similar pattern of “eyes_cropped.png”
comment and “four_eyes_... | # David Martinez
# Follow the “eyes_cropped.py” in the HOP09 Manipulating Images
# and GUI Automation. In the similar way use the image which
# was used in the previous question and create a program which
# displays image in the similar pattern of “eyes_cropped.png”
# and “four_eyes_bulldog.png”.
from... | Python | zaydzuhri_stack_edu_python |
import sys
set x = argv at 1
set y = argv at 2
set z = x + y
print z | import sys
x = sys.argv[1]
y = sys.argv[2]
z = x + y
print(z) | Python | zaydzuhri_stack_edu_python |
function make_jitter_plots data names ylabel dx=0.1 offset=0.0 ytick_fmt=none xlabels=none ax_handle=none alpha=1 color=none marker=none markersize=12 return_plot_pointer=false
begin
if is instance marker tuple list tuple
begin
assert length marker == length names
end
if is instance color tuple list tuple
begin
assert ... | def make_jitter_plots(data, names, ylabel, dx=0.1, offset=0.0, ytick_fmt=None,
xlabels=None, ax_handle=None, alpha=1, color=None,
marker=None, markersize=12, return_plot_pointer=False):
if isinstance(marker, (list, tuple)):
assert len(marker) == len(names)
if... | Python | nomic_cornstack_python_v1 |
function get_test self index
begin
try
begin
return _tests at index
end
except IndexError
begin
raise call IndexError string list index out of range: there is no TestData at position { index }
end
end function | def get_test(self, index):
try:
return self._tests[index]
except IndexError:
raise(IndexError(f'list index out of range: there is no TestData at position {index}')) | Python | nomic_cornstack_python_v1 |
function predict_inductive self df G return_proba=false
begin
set gen = call preprocess df G
set batch_size = batch_size
set preds = call predict_generator gen
set result = if expression return_proba then preds else list comprehension c at argument maximum pred for pred in preds
return result
end function | def predict_inductive(self, df, G, return_proba=False):
gen = self.preproc.preprocess(df, G)
gen.batch_size = self.batch_size
preds = self.model.predict_generator(gen)
result = preds if return_proba else [self.c[np.argmax(pred)] for pred in preds]
return result | Python | nomic_cornstack_python_v1 |
function YUVwrite y u v path
begin
if length call shape y == 3
begin
set frame_num = call shape y at 0
with open path string wb as file
begin
for fn in range frame_num
begin
write file call tobytes
write file call tobytes
write file call tobytes
end
end
end
else
begin
with open path string wb as file
begin
write file c... | def YUVwrite(y, u, v, path):
if len(np.shape(y)) == 3:
frame_num = np.shape(y)[0]
with open(path, 'wb') as file:
for fn in range(frame_num):
file.write(y[fn].tobytes())
file.write(u[fn].tobytes())
file.write(v[fn].tobytes())
else:
... | Python | nomic_cornstack_python_v1 |
class Restaurant
begin
function __init__ self restaurant_name cuisine_type number_served=0
begin
set restaurant_name = restaurant_name
set cuisine_type = cuisine_type
set number_served = number_served
end function
function describe_restaurant self
begin
print string Restaurant name - + title restaurant_name
print strin... | class Restaurant():
def __init__(self, restaurant_name, cuisine_type, number_served=0):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
self.number_served = number_served
def describe_restaurant(self):
print ("Restaurant name - " + self.restaurant_name.... | Python | zaydzuhri_stack_edu_python |
import pyspark
function preprocess games
begin
return games
end function
from collections import defaultdict
import itertools
from merge import merge_dicts
from psycopg2.extras import execute_batch
import psycopg2
function get_team_combiations won lose
begin
set won_combinations = list tuple
set lose_combinations = li... | import pyspark
def preprocess(games):
return games
from collections import defaultdict;
import itertools;
from merge import merge_dicts
from psycopg2.extras import execute_batch
import psycopg2
def get_team_combiations(won, lose):
won_combinations = [()]
lose_combinations = [()]
for i in range(1, ... | Python | zaydzuhri_stack_edu_python |
function inp
begin
print string Enter your Name :
set name = lower string input
if not is alpha name
begin
print string Error! Not a valid Name!!
return
end
set phone_num = string input string Enter your Phone Number :
if not is digit phone_num or length phone_num > 10
begin
print string Error! Not a valid Phone Number... | def inp():
print("\nEnter your Name : ")
name = str(input()).lower()
if( not name.isalpha()) :
print("Error! Not a valid Name!!")
return
phone_num = str(input("Enter your Phone Number : "));
if((not phone_num.isdigit() ) or len(phone_num) > 10) :
print("Error! Not a valid Pho... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Thu May 28 20:55:48 2020 @author: nehab28
comment Write a Python Program to swap two variables. Read numbers from user
set num1 = integer input string Enter the first number:
set num2 = integer input string Enter the second number:
print stri... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 28 20:55:48 2020
@author: nehab28
"""
#Write a Python Program to swap two variables. Read numbers from user
num1 = int(input("Enter the first number:" ))
num2 = int(input("Enter the second number: "))
print("Before Swapping the numbers: num1 = %d ... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import folium
import folium.plugins as fp
from folium.plugins import HeatMap
from folium.map import Layer
function folium_map map_object data zoom_start=11 popup=false icon=false color=false
begin
string map_object: The variable name of the map object that you have instantiated. data: List of lists,... | import pandas as pd
import folium
import folium.plugins as fp
from folium.plugins import HeatMap
from folium.map import Layer
def folium_map(map_object, data, zoom_start=11, popup=False, icon=False, color=False):
"""
map_object: The variable name of the map object that you have instantiated.
data: List of ... | Python | zaydzuhri_stack_edu_python |
function test_honor_Irange self
begin
set exclude_setrange = list
set exclude_checkrange = list
set tmp = call rand 1 * 90
set Irangein = horizontal stack tuple tmp call rand 1 * 90 + 90
for mod in allmods
begin
if __name__ not in exclude_setrange and __name__ not in exclude_checkrange and string gen_angles in __dict... | def test_honor_Irange(self):
exclude_setrange = []
exclude_checkrange = []
tmp = np.random.rand(1) * 90
Irangein = np.hstack((tmp, np.random.rand(1) * 90 + 90))
for mod in self.allmods:
if (
(mod.__name__ not in exclude_setrange)
and... | Python | nomic_cornstack_python_v1 |
import math
set res = list
for i in range 1 length s + 1
begin
set k = 0
while k + i <= length s
begin
set str = integer s at slice k : k + i :
set a = integer - 1 + square root 1 + 4 * str / 2
if a * a + 1 == str and str != 0
begin
append res str
end
set k = k + 1
end
end
print sorted list set res
comment import iter... | import math
res=[]
for i in range(1,len(s)+1):
k=0
while(k+i<=len(s)):
str = int(s[k:k+i])
a=int((-1+math.sqrt(1+4*str))/2)
if(a*(a+1)==str and str!=0):
res.append(str)
k+=1
print(sorted(list(set(res))))
# import itertools
# list1... | Python | zaydzuhri_stack_edu_python |
import aux_lib as ax
if __name__ == string __main__
begin
set file_path = string ./data/housing.csv
comment leitura do arquivo
set dataset = call leitura file_path
print dataset at string RM
end
comment tamanho das listas
comment n_data_rows = len(dataset['RM'])
comment Predizer valores de MEDV a partir do RM
comment 7... | import aux_lib as ax
if __name__ == "__main__":
file_path = "./data/housing.csv"
# leitura do arquivo
dataset = ax.leitura(file_path)
print(dataset['RM'])
# tamanho das listas
#n_data_rows = len(dataset['RM'])
# Predizer valores de MEDV a partir do RM
# 70% do dataset para pe... | Python | zaydzuhri_stack_edu_python |
import pickle
set books = list tuple string Евгений Онегин string Пушкин А.С. 200 tuple string Муму string Тургенев И.С. 250 tuple string Мастер и Маргарита string Булгаков М.А. 500 tuple string Мертвые души string Гоголь Н.В. 190
try
begin
set file = open string out.bin string wb
try
begin
dump books file
end
finally
... | import pickle
books = [
("Евгений Онегин", "Пушкин А.С.", 200),
("Муму", "Тургенев И.С.", 250),
("Мастер и Маргарита", "Булгаков М.А.", 500),
("Мертвые души", "Гоголь Н.В.", 190),
]
try:
file = open("out.bin", "wb")
try:
pickle.dump(books, file)
finally:
file.close()
excep... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
from FalloutObject import FalloutObject
import random
class Die extends FalloutObject
begin
function __init__ self sides=6 armor=none **kwargs
begin
call __init__ keyword kwargs
if sides < 1
begin
raise call DiceException string Invalid number of die sides %d % sides
end
set sides = sides
... | #!/usr/bin/env python3
from .FalloutObject import FalloutObject
import random
class Die(FalloutObject):
def __init__(self,sides=6,armor=None,**kwargs):
super(Die,self).__init__(**kwargs)
if sides < 1:
raise DiceException("Invalid number of die sides %d" % sides)
self.sides=side... | Python | zaydzuhri_stack_edu_python |
comment 10개의 이미지를 고정 위치에 중복 for문을 이용해 배치하는 프로그램
from tkinter import *
comment Variable Define
set imgList = list string ice-01.gif string ice-02.gif string ice-03.gif string ice-04.gif string ice-05.gif string snow-01.gif string snow-02.gif string snow-03.gif string snow-04.gif string snow-05.gif
set btnList = list non... | # 10개의 이미지를 고정 위치에 중복 for문을 이용해 배치하는 프로그램
from tkinter import *
# Variable Define
imgList = ["ice-01.gif", "ice-02.gif", "ice-03.gif", "ice-04.gif", "ice-05.gif",
"snow-01.gif", "snow-02.gif", "snow-03.gif", "snow-04.gif", "snow-05.gif"]
btnList = [None] * 10
low, col = 0, 0
xPos, yPos = 0, 0
cnt = 0
# M... | Python | zaydzuhri_stack_edu_python |
async function test_select_set_option_light_motion hass light
begin
set tuple _ entity_id = call ids_from_device_description SELECT light LIGHT_SELECTS at 0
set __fields__ at string set_light_settings = call Mock
set set_light_settings = call AsyncMock
await call async_call string select string select_option dict ATTR_... | async def test_select_set_option_light_motion(
hass: HomeAssistant,
light: Light,
):
_, entity_id = ids_from_device_description(Platform.SELECT, light, LIGHT_SELECTS[0])
light.__fields__["set_light_settings"] = Mock()
light.set_light_settings = AsyncMock()
await hass.services.async_call(
... | Python | nomic_cornstack_python_v1 |
function get_normalize_spacing self
begin
return normalize_spacing
end function | def get_normalize_spacing(self):
return self.normalize_spacing | Python | nomic_cornstack_python_v1 |
class Claim extends object
begin
set claim_id = string
set left_space = 0
set top_space = 0
set width = 0
set height = 0
function __init__ self claim_id left_space top_space width height
begin
set claim_id = claim_id
set left_space = left_space
set top_space = top_space
set width = width
set height = height
end functi... | class Claim(object):
claim_id = ""
left_space = 0
top_space = 0
width = 0
height = 0
def __init__(self, claim_id, left_space, top_space, width, height):
self.claim_id = claim_id
self.left_space = left_space
self.top_space = top_space
self.width = width
se... | Python | zaydzuhri_stack_edu_python |
comment ===============================================================================
comment Code handling the title corpus for TAL
comment Author : Damien Gouteux
comment Last updated : 08 April 2018
comment Technologies : Python, Excel XSLX
comment Usage :
comment Load the downloaded notice from HAL in memory and ... | #===============================================================================
# Code handling the title corpus for TAL
# Author : Damien Gouteux
# Last updated : 08 April 2018
# Technologies : Python, Excel XSLX
# Usage :
# Load the downloaded notice from HAL in memory and perform counting:
# Length of title in wo... | Python | zaydzuhri_stack_edu_python |
function test_horizontal_sequence_match self
begin
set dna = call _create_dna
comment Existing codon pair
set correct_codon_pair = data at 2
comment Another codon pair
set other_pair = call _create_codon_pair
assert false call has_sequence other_pair
assert true call has_sequence correct_codon_pair
end function | def test_horizontal_sequence_match(self):
dna = self._create_dna()
# Existing codon pair
correct_codon_pair = dna.data[2]
# Another codon pair
other_pair = self._create_codon_pair()
self.assertFalse(dna.has_sequence(other_pair))
self.assertTrue(dna.has_sequence... | Python | nomic_cornstack_python_v1 |
function filter self command_args
begin
set choice_list = list string Add Filter string Remove Filter
set filters = call filters
function _enable_disable_selected item selected_index
begin
if selected_index == 1
begin
call _select_filtering_file command_args filters false
end
else
if selected_index == 0
begin
call _sel... | def filter(self, command_args):
choice_list = ["Add Filter", "Remove Filter"]
filters = self.open_ports[command_args.comport].filters()
def _enable_disable_selected(item, selected_index):
if selected_index == 1:
self._select_filtering_file(command_args, filters, Fal... | Python | nomic_cornstack_python_v1 |
function manager_id self
begin
return get pulumi self string manager_id
end function | def manager_id(self) -> str:
return pulumi.get(self, "manager_id") | Python | nomic_cornstack_python_v1 |
from numpy import *
from matplotlib.pyplot import *
close string all
set n = array range 0 50
set x = load np string signal-1.npz
set x1 = x at string arr_1
set X1 = call fftshift fft x1
set w = linear space - 0.5 0.5 length X1
set x1 = x1 at slice 0 : 50 :
subplot 3 2 1
call stem n x1 string b
title string vsig = 0.1... | from numpy import *
from matplotlib.pyplot import *
close('all')
n = arange(0,50)
x = np.load('signal-1.npz')
x1 = x['arr_1']
X1 = fft.fftshift(fft.fft(x1))
w = linspace(-.5,.5,len(X1))
x1 = x1[0:50]
subplot(3,2,1)
stem(n,x1,'b')
title('vsig = 0.1vsmpl')
xlabel('t [us]')
ylabel('Volts')
subplot(3,2,2)
plot(w,abs(X1)/... | Python | zaydzuhri_stack_edu_python |
function calLD self col1_id col2_id
begin
set snp1_index = col_id2col_index at col1_id
set snp2_index = col_id2col_index at col2_id
comment only 2 alleles
set counter_matrix = zeros list 2 2
set snp1_allele2index = dict
set snp2_allele2index = dict
for k in range length row_id_ls
begin
set snp1_allele = data_matrix a... | def calLD(self, col1_id, col2_id):
snp1_index = self.col_id2col_index[col1_id]
snp2_index = self.col_id2col_index[col2_id]
counter_matrix = num.zeros([2,2]) #only 2 alleles
snp1_allele2index = {}
snp2_allele2index = {}
for k in range(len(self.row_id_ls)):
snp1_allele = self.data_matrix[k][snp1_index]
... | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
return join string tokens
end function | def __str__(self):
return ''.join(self.tokens) | Python | nomic_cornstack_python_v1 |
class Solution
begin
function gcd self x y
begin
if x == y
begin
return x
end
comment elif x < y:
comment return self.gcd(x, y - x)
comment else:
comment return self.gcd(x - y, y)
while x != y
begin
if x > y
begin
set tuple x y = tuple x - y y
end
else
begin
set tuple x y = tuple x y - x
end
end
return x
end function
f... | class Solution:
def gcd(self, x, y):
if x == y:
return x
# elif x < y:
# return self.gcd(x, y - x)
# else:
# return self.gcd(x - y, y)
while x != y:
if x > y:
x, y = x - y, y
else:
x, y = x, y... | Python | zaydzuhri_stack_edu_python |
function set_ext_arns ForInitializer=none ForExtractor=none ForConsolidator=none ForFinalizer=none ForFinalizerParallelIterations=none LimitedParallelConsolidator=none
begin
function apply_arg val val_name
begin
if not val
begin
raise exception format string set_ext_arns: {} must not be None val_name
end
if not is inst... | def set_ext_arns(ForInitializer=None, ForExtractor=None, ForConsolidator=None,
ForFinalizer=None, ForFinalizerParallelIterations=None,
LimitedParallelConsolidator=None):
def apply_arg(val, val_name):
if not val:
raise Exception("set_ext_arns: {} must not be None".format(val_name))
if not isinstance(val... | Python | nomic_cornstack_python_v1 |
function setCallDuration self
begin
set callTime = random integer 60 300
return callTime
end function | def setCallDuration(self):
callTime = random.randint(60, 300)
return callTime | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function rotate self matrix
begin
string Do not return anything, modify matrix in-place instead.
set matrix at slice : : = list zip *matrix[::-1]
end function
end class
set sol = call Solution
print call rotate list list 1 2 3 list 4 5 6 list 7 8 9 | from typing import List
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
matrix[:] = list(zip(*matrix[::-1]))
sol = Solution()
print(sol.rotate([[1,2,3],[4,5,6],[7,8,9]]))
| Python | zaydzuhri_stack_edu_python |
import csv , sys , math
function processInput fileName target
begin
set file = open fileName string r
set csv_reader = reader file delimiter=string ,
set data = list
set index = 0
set attributes = list
for line in csv_reader
begin
set dictionary = dict
if index == 0
begin
for item in line
begin
append attributes ite... | import csv, sys, math
def processInput(fileName, target):
file = open(fileName, 'r')
csv_reader = csv.reader(file, delimiter=',')
data = []
index = 0
attributes = []
for line in csv_reader:
dictionary = {}
if index == 0:
for item in line:
attributes... | Python | zaydzuhri_stack_edu_python |
function j_times seconds_elapsed
begin
set jstr = string seconds_elapsed at slice - 2 : :
set j = integer jstr + 1
return j
end function | def j_times(seconds_elapsed: int) -> int:
jstr = str(seconds_elapsed)[-2:]
j = int(jstr) + 1
return j | Python | nomic_cornstack_python_v1 |
function get_flight_route_dict
begin
set routes_file = call resource_filename __name__ string airport_routes.json
set routes_dict = load json open routes_file string r
return routes_dict
end function | def get_flight_route_dict():
routes_file = pkg_resources.resource_filename(__name__, 'airport_routes.json')
routes_dict = json.load(open(routes_file, 'r'))
return routes_dict | Python | nomic_cornstack_python_v1 |
function get_data
begin
set word = input string What you want encryp?
set word = lower word
set num = integer input string Enter a number between 1 - 26:
if num > 26 or num == 0
begin
comment while num > 26 or num == 0:
set num = integer input string Enter CORRECT number between 1 - 26:
end
return tuple word num
end fu... | def get_data():
word = input("What you want encryp? ")
word = word.lower()
num = int(input("Enter a number between 1 - 26: "))
if num > 26 or num == 0:
# while num > 26 or num == 0:
num = int(input("Enter CORRECT number between 1 - 26: "))
return word, num
def encrypt(word, num):
ne... | Python | zaydzuhri_stack_edu_python |
function update_dns_account_password samdb secrets_ldb names
begin
set expression = string samAccountName=dns-%s % netbiosname
set secrets_msg = search expression=expression
if length secrets_msg == 1
begin
set res = search expression=expression attrs=list
assert length res == 1
set msg = call Message dn
set machinepas... | def update_dns_account_password(samdb, secrets_ldb, names):
expression = "samAccountName=dns-%s" % names.netbiosname
secrets_msg = secrets_ldb.search(expression=expression)
if len(secrets_msg) == 1:
res = samdb.search(expression=expression, attrs=[])
assert(len(res) == 1)
msg = ldb... | Python | nomic_cornstack_python_v1 |
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import pickle
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import time
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScal... | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import pickle
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import time
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScal... | Python | zaydzuhri_stack_edu_python |
function z2y zc nc=none
begin
set Czz = call cov zc
set tuple e U = call eigh Czz
if nc is none
begin
set nc = length e at e > 0.0
end
set es = e at slice - nc : : ^ 0.5
set Us = U at tuple slice : : slice - nc : :
set y = dot T zc
comment NOTE: we have Cyy = I, already whitened
return tuple y es Us
end function | def z2y(zc, nc=None):
Czz = cov(zc)
e, U = la.eigh(Czz)
if nc is None:
nc = len(e[e>0.0])
es = e[-nc:]**0.5
Us = U[:, -nc:]
y = np.dot((Us/es).T, zc)
# NOTE: we have Cyy = I, already whitened
return y, es, Us | Python | nomic_cornstack_python_v1 |
function map_doc2idx self
begin
set doc2idx = dictionary comprehension doc_id : i for tuple i doc_id in enumerate doc_ids
info format string SQLite iterator: The size of the database is {} documents length doc2idx
return doc2idx
end function | def map_doc2idx(self) -> Dict[int, Any]:
doc2idx = {doc_id: i for i, doc_id in enumerate(self.doc_ids)}
logger.info(
"SQLite iterator: The size of the database is {} documents".format(len(doc2idx)))
return doc2idx | Python | nomic_cornstack_python_v1 |
comment MegaMaid is a robot whose function is to move through a matrix and clean
comment all of its dirty cells. It's positioned in some cell of an matrix of dirty
comment (d) and clean (-) cells. It can perform five types of operations:
comment LEFT: Move one cell to the left.
comment RIGHT: Move one cell to the right... | # MegaMaid is a robot whose function is to move through a matrix and clean
# all of its dirty cells. It's positioned in some cell of an matrix of dirty
# (d) and clean (-) cells. It can perform five types of operations:
# LEFT: Move one cell to the left.
# RIGHT: Move one cell to the right.
# UP: Move one cell up.
#... | Python | zaydzuhri_stack_edu_python |
import requests
import json
set header = dict string User-Agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
function get_data pin date
begin
set r = get requests string https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calend... | import requests
import json
header={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
def get_data(pin, date):
r = requests.get("https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode="+pin+"&date="+... | Python | zaydzuhri_stack_edu_python |
comment 그리디 알고리즘
comment 백준 1138번
function cntcheck i
begin
set cnt = 0
for j in b
begin
if i < j
begin
set cnt = cnt + 1
end
if i == j
begin
break
end
end
return cnt
end function
function movenum i
begin
set cnt = call cntcheck i
while cnt != a at i - 1
begin
set tmp = index b i
set b at tmp = b at tmp - 1
set b at tm... | #그리디 알고리즘
#백준 1138번
def cntcheck(i):
cnt=0
for j in b:
if(i<j):
cnt+=1
if(i==j):
break
return cnt
def movenum(i):
cnt=cntcheck(i)
while(cnt!=a[i-1]):
tmp=b.index(i)
b[tmp]=b[tmp-1]
b[tmp-1]=i
... | Python | zaydzuhri_stack_edu_python |
function apRawSum dg100 dg400
begin
comment ITSs = dg100
set ITSs = dg400
comment ITSs = dg400 + dg100
set mers = range 0 19
set x_names = range 2 21
comment rawSum = [sum([i.rawDataMean[x] for i in ITSs]) for x in mers]
comment apSum = [sum([i.abortiveProb[x] for i in ITSs]) for x in mers]
set rawMean = list comprehen... | def apRawSum(dg100, dg400):
#ITSs = dg100
ITSs = dg400
#ITSs = dg400 + dg100
mers = range(0, 19)
x_names = range(2, 21)
#rawSum = [sum([i.rawDataMean[x] for i in ITSs]) for x in mers]
#apSum = [sum([i.abortiveProb[x] for i in ITSs]) for x in mers]
rawMean = [np.mean([i.rawDataMean[x]... | Python | nomic_cornstack_python_v1 |
comment Convert Celsius to Fahrenheit.
comment 9/22/2018.
comment CTI-110 P2HW1 - Celsius Fahrenheit Converter.
comment Jacob White.
comment Pseudocode - Input the Celsius, Convert Celsius to Fahrenheit using the formule F = 9/5*C + 32, Display output.
set celsius = decimal input string Enter the celsius:
comment Conve... | # Convert Celsius to Fahrenheit.
# 9/22/2018.
# CTI-110 P2HW1 - Celsius Fahrenheit Converter.
# Jacob White.
# Pseudocode - Input the Celsius, Convert Celsius to Fahrenheit using the formule F = 9/5*C + 32, Display output.
celsius = float(input('Enter the celsius: '))
#Convert the Celsius to Fahrenheit
fahrenh... | Python | zaydzuhri_stack_edu_python |
function window_placement self arg0
begin
set place = arg0
if arg0 == string top left
begin
call geometry string +0+0
end
else
if arg0 == string bottom left
begin
call geometry string +0+750
end
else
if arg0 == string top right
begin
call geometry string +1000+0
end
else
if arg0 == string bottom right
begin
call geomet... | def window_placement(self, arg0):
RSSticker.place = arg0
if arg0 == "top left":
self.geometry("+0+0")
elif arg0 == "bottom left":
self.geometry("+0+750")
elif arg0 == "top right":
self.geometry("+1000+0")
elif arg0 == "bottom right":
... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.