code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import spotipy
import spotipy.util as util
import random
comment Change this to your Client ID
set SPOTIPY_CLIENT_ID = string YOUR_ID_HERE
comment Change this to your Client Secret
set SPOTIPY_CLIENT_SECRET = string YOUR_SECRET_HERE
set SPOTIPY_REDIR_URI = string http://localhost:8888/callback
set sp = call Spotify
com... | import spotipy
import spotipy.util as util
import random
SPOTIPY_CLIENT_ID='YOUR_ID_HERE' #Change this to your Client ID
SPOTIPY_CLIENT_SECRET='YOUR_SECRET_HERE' #Change this to your Client Secret
SPOTIPY_REDIR_URI='http://localhost:8888/callback'
sp = spotipy.Spotify()
user = 'YOUR_USER_ID_HERE' ... | Python | zaydzuhri_stack_edu_python |
import threading
comment def do_this(what):
comment whoami(what)
comment def whoami(what):
comment print("Thread %s says: %s" % (threading.current_thread(), what))
comment if __name__ == '__main__':
comment whoami("I'm the main program")
comment for n in range(4):
comment p = threading.Thread(target=do_this, args=("I'm... | import threading
# def do_this(what):
# whoami(what)
# def whoami(what):
# print("Thread %s says: %s" % (threading.current_thread(), what))
# if __name__ == '__main__':
# whoami("I'm the main program")
# for n in range(4):
# p = threading.Thread(target=do_this, args=("I'm function %s" % n,))
# ... | Python | zaydzuhri_stack_edu_python |
function json_path_serializer obj
begin
if is instance obj Path
begin
return string obj
end
else
begin
raise call TypeError string TypeError: Object of type { __class__ } + string is not JSON serializable
end
end function | def json_path_serializer(obj):
if isinstance(obj, pathlib.Path):
return str(obj)
else:
raise TypeError(f"TypeError: Object of type {obj.__class__} "
+ "is not JSON serializable") | Python | nomic_cornstack_python_v1 |
from elements import MiddlePoint , SpinnerMiddleHands , ChaserScreen , DoubleScreen , AngledChaserScreen , ChaserSpinner , TunnelMiddleHands , CenteredLines
class AnimationState
begin
function __init__ self animation
begin
set animation = animation
end function
function key_handler self key
begin
raise NotImplementedEr... | from elements import (
MiddlePoint, SpinnerMiddleHands, ChaserScreen,
DoubleScreen, AngledChaserScreen, ChaserSpinner,
TunnelMiddleHands, CenteredLines
)
class AnimationState:
def __init__(self, animation):
self.animation = animation
def key_handler(self, key):
raise NotImplement... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import time
import board
import Adafruit_DHT
import mariadb
import sys
function log_db temp hum
begin
try
begin
execute cur string INSERT INTO data (timestamp,temperature, humidity) VALUES (CURRENT_TIMESTAMP , ?, ?) tuple temp hum
commit conn
end
except e
begin
print string Mariadb Error: ... | #!/usr/bin/env python3
import time
import board
import Adafruit_DHT
import mariadb
import sys
def log_db(temp, hum):
try:
cur.execute(
"INSERT INTO data (timestamp,temperature, humidity) VALUES (CURRENT_TIMESTAMP , ?, ?)",
(temp, hum))
conn.commit()
except e:
p... | Python | zaydzuhri_stack_edu_python |
function download_image image_url image_format main_directory dir_name count print_urls socket_timeout prefix print_size no_numbering no_download
begin
if print_urls or no_download
begin
info string Image URL: %s % image_url
end
if no_download
begin
return tuple string success string Printed url without downloading non... | def download_image(image_url, image_format, main_directory, dir_name, count, print_urls, socket_timeout,
prefix, print_size, no_numbering, no_download):
if print_urls or no_download:
logging.info("Image URL: %s" % image_url)
if no_download:
return "success"... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding:utf-8
string 这是一个 echo 服务器的例子代码,服务器只能一次处理一个连接
import socket
import traceback
import sys
set tuple host port = tuple string 8123
try
begin
comment 创建一个 socket
set sock = call socket AF_INET SOCK_STREAM
comment SO_REUSEADDR 是一个可以将释放掉的端口立即重新使用的一个选项,但实际上 TCP 原则是不建议这样,因为这样会影响 TCP... | #!/usr/bin/env python
#coding:utf-8
'''这是一个 echo 服务器的例子代码,服务器只能一次处理一个连接'''
import socket
import traceback
import sys
host, port = '', 8123
try:
#创建一个 socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#SO_REUSEADDR 是一个可以将释放掉的端口立即重新使用的一个选项,但实际上 TCP 原则是不建议这样,因为这样会影响 TCP 连接的释放中的2MSL
sock.setsockopt(soc... | Python | zaydzuhri_stack_edu_python |
function predict_ensemble ensemble X
begin
set probs = list comprehension call predict_proba X at tuple slice : : 1 for r in ensemble
return mean vertical stack probs axis=0
end function | def predict_ensemble(ensemble, X):
probs = [r.predict_proba(X)[:, 1] for r in ensemble]
return np.vstack(probs).mean(axis=0) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
import pandas as pd
import html5lib
comment scraping football league tables from 1947-2015 from wikipedia
comment does not include tier 1.1 (Premier League) from 1993 onwards
comment defining tiers based on order each league with appear on webpage
set tiers = dict ... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
import html5lib
#scraping football league tables from 1947-2015 from wikipedia
#does not include tier 1.1 (Premier League) from 1993 onwards
#defining tiers based on order each league with appear on webpage
tiers = {1947: [11, 21, 31, 32],
1959: [11, ... | Python | zaydzuhri_stack_edu_python |
import random
set my_list = list 1 2 3
set students = list string 김태균 string 박찬우 string 차봉승
print random choice students
append students string 박원기
print students at 3
set my_tuple = tuple string 요거트 string 바밤바 string 우유
set my_dict = dict string 태균 string 남 ; string 찬우 string 남 ; string 샘 string 여
print my_dict at str... | import random
my_list = [1, 2, 3]
students = ['김태균', '박찬우', '차봉승']
print(random.choice(students))
students.append('박원기')
print(students[3])
my_tuple = ('요거트', '바밤바', '우유')
my_dict = {'태균' : '남', '찬우' : '남', '샘' : '여'}
print(my_dict['태균'])
| Python | zaydzuhri_stack_edu_python |
function verify_user_existance self user
begin
for client in clients
begin
if user == call get_name
begin
return true
end
end
return false
end function | def verify_user_existance(self, user):
for client in self.clients:
if user == client.get_name():
return True
return False | Python | nomic_cornstack_python_v1 |
import os
import random
import time
import pygame
set BLACK = tuple 0 0 0
set WHITE = tuple 255 255 255
set RED = tuple 255 0 0
set GREEN = tuple 0 255 0
set BLUE = tuple 0 0 255
set YELLOW = tuple 255 255 0
set WIDTH = 1800
set HEIGHT = 800
set FPS = 60
set scores = 0
set screen = call set_mode tuple WIDTH HEIGHT
set ... | import os
import random
import time
import pygame
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
WIDTH = 1800
HEIGHT = 800
FPS = 60
scores = 0
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
game_folder = os.path.... | Python | zaydzuhri_stack_edu_python |
function persist_curves self asset_manager_id business_date curves update_existing_curves=true
begin
string :param asset_manager_id: :param business_date: :param curves: :param update_existing_rates: :return:
info string Persist curves - Asset Manager: %s - Business Date: %s asset_manager_id business_date
set url = str... | def persist_curves(self, asset_manager_id, business_date, curves, update_existing_curves=True):
"""
:param asset_manager_id:
:param business_date:
:param curves:
:param update_existing_rates:
:return:
"""
self.logger.info('Persist curves - Asset Manager: %... | Python | jtatman_500k |
from h2o_wave import site
class CardsManager
begin
function __init__ self route
begin
set page = site at route
drop page
set rows_of_type = dict
end function
function get_free_row self
begin
return if expression rows_of_type then max values rows_of_type key=lambda x -> x at string end at string end + 1 else 1
end func... | from h2o_wave import site
class CardsManager:
def __init__(self, route: str):
self.page = site[route]
self.page.drop()
self.rows_of_type = {}
def get_free_row(self):
return max(self.rows_of_type.values(), key=lambda x: x["end"])["end"] + 1 if self.rows_of_type else 1
| Python | zaydzuhri_stack_edu_python |
import math
set tuple ns ss = split strip string 3 4 string
set tuple ns ss = split strip input string
set n = integer ns
set s = integer ss
set vstr = split strip string 5 3 4 string
set vstr = split strip input string
set v = list map int vstr
set min_v = min v
for i in range n
begin
if v at i > min_v
begin
set s = s... | import math
(ns, ss) = '3 4'.strip().split(' ')
(ns, ss) = input().strip().split(' ')
n = int(ns)
s = int(ss)
vstr = '5 3 4'.strip().split(' ')
vstr = input().strip().split(' ')
v = list(map(int, vstr))
min_v = min(v)
for i in range(n):
if v[i] > min_v:
s -= (v[i]-min_v)
v[i] -= (v[i]-... | Python | zaydzuhri_stack_edu_python |
set a = string John
set b = string is a developer!
print a + b | a = "John "
b = "is a developer!"
print(a + b)
| Python | zaydzuhri_stack_edu_python |
function __truediv__ self scalar
begin
if not is instance scalar Number
begin
raise call TypeError string BasicExpression objects only support *scalar* division
end
return call BasicExpression list comprehension tt / scalar for tt in _terms
end function | def __truediv__(self, scalar):
if not isinstance(scalar, numbers.Number):
raise TypeError("BasicExpression objects only support *scalar* division")
return BasicExpression([tt / scalar for tt in self._terms]) | Python | nomic_cornstack_python_v1 |
function test_remove_supersaturation self
begin
set temperature_in = 300
set pressure_in = 1010
set qv_sat = call calculate_qv_sat_liq temperature_in pressure_in
set qv = call DataArray array list 1.1 * qv_sat 1.0 * qv_sat 0.9 * qv_sat
set ncol = length values
set temperature = call DataArray list temperature_in * ncol... | def test_remove_supersaturation(self):
temperature_in = 300
pressure_in = 1010
qv_sat = hsa.calculate_qv_sat_liq(temperature_in,pressure_in)
qv = xr.DataArray(np.array([ 1.1*qv_sat , 1.0*qv_sat , 0.9*qv_sat ]))
ncol = len(qv.values)
temperature = xr.DataArray([temperature_in]*ncol)
pressu... | Python | nomic_cornstack_python_v1 |
function merge self dataset
begin
function merge_data source dest
begin
for tuple key value in items source
begin
if is instance value dict
begin
call merge_data value set default dest key dict
end
else
begin
set dest at key = value
end
end
return dest
end function
call merge_data data _data
for h in task_history
begin... | def merge(self, dataset):
def merge_data(source, dest):
for key, value in source.items():
if isinstance(value, dict):
merge_data(value, dest.setdefault(key, {}))
else:
dest[key] = value
return dest
merge_dat... | Python | nomic_cornstack_python_v1 |
import doctest
import unittest
import string
function fizzbizz n
begin
string Takes an integer as input which acts as a range and returns fizz for the numbers in that range which are divisible by 3, bizz for numbers in that range divisible by 5, fizzbizz for the numbers in that range divisible by both 3 and 5 and the n... | import doctest
import unittest
import string
def fizzbizz(n):
"""Takes an integer as input which acts as a range and returns fizz for the numbers in that range which are divisible by 3, bizz for numbers in that range divisible by 5, fizzbizz for the numbers in that range divisible by both 3 and 5 and the number it... | Python | zaydzuhri_stack_edu_python |
function bug_activity self bug_id
begin
string Get the activity of a bug in HTML format. :param bug_id: bug identifier
set params = dict PBUG_ID bug_id
set response = call CGI_BUG_ACTIVITY params
return response
end function | def bug_activity(self, bug_id):
"""Get the activity of a bug in HTML format.
:param bug_id: bug identifier
"""
params = {
self.PBUG_ID: bug_id
}
response = self.call(self.CGI_BUG_ACTIVITY, params)
return response | Python | jtatman_500k |
function test_get_absolute_url self
begin
set event = call EventFactory
assert equal call get_absolute_url format string /events/{0}/ pk
end function | def test_get_absolute_url(self):
event = EventFactory()
self.assertEqual(event.get_absolute_url(),
'/events/{0}/'.format(event.pk)) | Python | nomic_cornstack_python_v1 |
from datetime import datetime
from random import randint
from discord import Embed , Colour
from auth import Auth
function _to_time sec
begin
set day = sec // 24 * 3600
set sec = sec % 24 * 3600
set hour = sec // 3600
set sec = sec % 3600
set minutes = sec // 60
return string D: { day } H: { hour } M: { minutes }
end f... | from datetime import datetime
from random import randint
from discord import Embed, Colour
from .auth import Auth
def _to_time(sec):
day = sec // (24 * 3600)
sec %= (24 * 3600)
hour = sec // 3600
sec %= 3600
minutes = sec // 60
return f"D: {day} H: {hour} M: {minutes}"
def general(player, ... | Python | zaydzuhri_stack_edu_python |
function loadcategory self file=none
begin
comment print(self.abs_dirpath + file)
set fpath = call get_file join path abs_dirpath file origin=none
with open fpath string r as f
begin
return dictionary generator expression tuple name ind for tuple ind name in enumerate list comprehension right strip line for line in f
e... | def loadcategory(self, file=None):
# print(self.abs_dirpath + file)
fpath = get_file(os.path.join(self.abs_dirpath, file), origin=None)
with open(fpath, 'r') as f:
return dict((name, ind) for ind, name in enumerate([line.rstrip() for line in f])) | Python | nomic_cornstack_python_v1 |
function max num_list
begin
set i : int = 0
if length num_list == 0
begin
raise call ValueError string max() arg is an empty List
end
else
begin
set num_max : int = num_list at i
while i < length num_list
begin
if num_max == num_list at i
begin
set i = i + 1
end
else
if num_max > num_list at i
begin
set i = i + 1
end
e... | def max(num_list: list[int]) -> int:
i: int = 0
if len(num_list) == 0:
raise ValueError("max() arg is an empty List")
else:
num_max: int = num_list[i]
while i < len(num_list):
if num_max == num_list[i]:
i += 1
else:
if num_max >... | Python | nomic_cornstack_python_v1 |
from lightgbm import LGBMClassifier
import numpy as np
from sklearn.feature_selection import SelectFromModel
from sklearn.preprocessing import MinMaxScaler
class Classifier
begin
function __init__ self
begin
set clf = call LGBMClassifier n_estimators=2000 max_depth=- 1 random_state=44 n_jobs=- 1
print clf
set std = min... | from lightgbm import LGBMClassifier
import numpy as np
from sklearn.feature_selection import SelectFromModel
from sklearn.preprocessing import MinMaxScaler
class Classifier:
def __init__(self):
self.clf = LGBMClassifier(
n_estimators=2000, max_depth=-1, random_state=44, n_jobs=-1)
pri... | Python | zaydzuhri_stack_edu_python |
set tuple hour minute = map int split input
set timeSum = hour * 60 + minute - 30
print timeSum // 60 + 24 % 24 timeSum % 60 | hour,minute=map(int,input().split())
timeSum=hour*60+minute-30
print((timeSum//60+24)%24,timeSum%60) | Python | zaydzuhri_stack_edu_python |
function decodetype type_
begin
set reg = compile string (r)([1-9]?)
set mat = match type_
if mat
begin
set read = call group 1 is not none
set prio = if expression call group 2 then integer call group 2 else none
end
else
begin
set tuple read prio = tuple false none
end
set write = string w in type_
set update = not r... | def decodetype(type_):
reg = re.compile(r"(r)([1-9]?)")
mat = reg.match(type_)
if mat:
read = mat.group(1) is not None
prio = int(mat.group(2)) if mat.group(2) else None
else:
read, prio = False, None
write = "w" in type_
update = not read and len(type_) > (1 if write els... | Python | nomic_cornstack_python_v1 |
function similar_face_tracks face_track1 face_track2 max_diff min_int_area min_pct
begin
set sim = false
comment Check if start and end of the two face tracks correspond
set start1 = face_track1 at SEGMENT_START_KEY
set start2 = face_track2 at SEGMENT_START_KEY
if absolute start1 - start2 <= max_diff
begin
set dur1 = f... | def similar_face_tracks(
face_track1, face_track2, max_diff, min_int_area, min_pct):
sim = False
# Check if start and end of the two face tracks correspond
start1 = face_track1[c.SEGMENT_START_KEY]
start2 = face_track2[c.SEGMENT_START_KEY]
if abs(start1 - start2) <= max_diff:
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment This file is part of mpv.
comment mpv is free software; you can redistribute it and/or
comment modify it under the terms of the GNU Lesser General Public
comment License as published by the Free Software Foundation; either
comment version 2.1 of the License, or (at your option) any... | #!/usr/bin/env python3
#
# This file is part of mpv.
#
# mpv is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# mpv is distr... | Python | zaydzuhri_stack_edu_python |
string Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay should be the normal rate for hours up to 40 and time-and-a-half for the hourly rate for all hours worked above 40 hours. Put the logic to do the computation of pay in a function called computepay() and use the f... | """ Write a program to prompt the user for hours and rate per hour using input to
compute gross pay. Pay should be the normal rate for hours up to 40 and time-and-a-half
for the hourly rate for all hours worked above 40 hours. Put the logic to do the
computation of pay in a function called computepay() and use the f... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment creating a new network
comment drawing the created network
import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
import networkx as nx
set epsilon = 0.001
set fname = string ./adjacent.dat
comment fname2 = "./config_S_step0.dat"
comment fnam... | # -*- coding: utf-8 -*-
# creating a new network
# drawing the created network
import numpy as np
import sys
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
import networkx as nx
epsilon =1e-3
fname = "./adjacent.dat"
#fname2 = "./config_S_step0.dat"
#fname2 = "./config_S_step5000.dat"
fname2 = ".... | Python | zaydzuhri_stack_edu_python |
function void_endpoint self void_endpoint
begin
set _void_endpoint = void_endpoint
end function | def void_endpoint(self, void_endpoint):
self._void_endpoint = void_endpoint | Python | nomic_cornstack_python_v1 |
function discriminator params=dict string input_dim 64 ; string strides tuple 2 2 2 ; string kernel_size tuple 4 4 4 ; string leak_value 0.2
begin
set input_dim = params at string input_dim
set strides = params at string strides
set kernel_size = params at string kernel_size
set leak_value = params at string leak_value... | def discriminator(params={'input_dim': 64, 'strides': (2, 2, 2), 'kernel_size': (4, 4, 4), 'leak_value': 0.2}):
input_dim = params['input_dim']
strides = params['strides']
kernel_size = params['kernel_size']
leak_value = params['leak_value']
dropout = 0.25
inputs = Input(shape=(input_dim, input... | Python | nomic_cornstack_python_v1 |
function add_tex_to_binning self binning_dict
begin
if string reco in binning_dict at string name
begin
set sub_string = string reco
end
else
if string true in binning_dict at string name
begin
set sub_string = string true
end
else
begin
set sub_string = none
end
if string energy in binning_dict at string name
begin
se... | def add_tex_to_binning(self, binning_dict):
if 'reco' in binning_dict['name']:
sub_string = 'reco'
elif 'true' in binning_dict['name']:
sub_string = 'true'
else:
sub_string = None
if 'energy' in binning_dict['name']:
binning_dict['tex'] = r... | Python | nomic_cornstack_python_v1 |
comment coding=UTF-8
comment 通过键盘输入一串字符,输出其中不同的字符以及他们各自的个数,例如输入adafdsfds,输出:
comment a,2
set data_list = list
set dict_ori = dict
set a = 1
while a
begin
set x = input string 请输入字符串:
if x == string
begin
break
end
else
begin
set data_list = x
end
end
for i in data_list
begin
set dict_ori at i = count data_list i
end... | # coding=UTF-8
# 通过键盘输入一串字符,输出其中不同的字符以及他们各自的个数,例如输入adafdsfds,输出:
# a,2
data_list = []
dict_ori = {}
a = 1
while a:
x = (input("请输入字符串: "))
if x == '':
break
else:
data_list = x
for i in data_list:
dict_ori[i] = data_list.count(i)
print(dict_ori)
for key in dict_ori.keys():
print(... | Python | zaydzuhri_stack_edu_python |
string Feladatod, hogy automatizáld selenium webdriverrel az alábbi funkcionalitásokat a kör területe appban: * Helyes kitöltés esete: * r: 10 * Eredmény: 314 * Nem számokkal történő kitöltés: * r: kiscica * Eredmény: NaN * Üres kitöltés: * r: <üres> * Eredmény: NaN
from selenium import webdriver
from selenium.webdrive... | """
Feladatod, hogy automatizáld selenium webdriverrel az alábbi funkcionalitásokat a kör területe appban:
* Helyes kitöltés esete:
* r: 10
* Eredmény: 314
* Nem számokkal történő kitöltés:
* r: kiscica
* Eredmény: NaN
* Üres kitöltés:
* r: <üres>
* Eredmény: NaN
"""
from selenium import webd... | Python | zaydzuhri_stack_edu_python |
function get_nearest_indices vector matrix num=5
begin
if length matrix < num
begin
set num = length matrix
end
set tuple m n = shape
set diff_matrix = call tile vector tuple m 1 - matrix
set diff_matrix = absolute diff_matrix
set distance = sum axis=1
set sortIndices = call argsort distance
set sortIndices = sortIndic... | def get_nearest_indices(vector, matrix, num=5):
if len(matrix) < num:
num = len(matrix)
m, n = matrix.shape
diff_matrix = np.tile(vector, (m, 1)) - matrix
diff_matrix = abs(diff_matrix)
distance = diff_matrix.sum(axis=1)
sortIndices = np.argsort(distance)
sortIndices = sortIndices[... | Python | nomic_cornstack_python_v1 |
function are_pad_on_graph self subgraph
begin
call visit subgraph
return on_graph
end function | def are_pad_on_graph(self, subgraph) -> bool:
self.visit(subgraph)
return self.on_graph | Python | nomic_cornstack_python_v1 |
function get_plot_params
begin
set FONT_SIZE = 7
set COASTLINES_LW = 0.5
set LINEWIDTH = 1.3
set PATHEFFECT_LW_ADD = LINEWIDTH * 1.8
return dict string lines.linewidth LINEWIDTH ; string hatch.linewidth 0.5 ; string font.size FONT_SIZE ; string legend.fontsize FONT_SIZE - 1 ; string legend.columnspacing 0.7 ; string le... | def get_plot_params():
FONT_SIZE = 7
COASTLINES_LW = 0.5
LINEWIDTH = 1.3
PATHEFFECT_LW_ADD = LINEWIDTH * 1.8
return {'lines.linewidth': LINEWIDTH,
'hatch.linewidth': 0.5,
'font.size': FONT_SIZE,
'legend.fontsize' : FONT_SIZE - 1,
'legend.columnspacing... | Python | nomic_cornstack_python_v1 |
import PySimpleGUI as sg
import time
from src.windows import menu_window
from src.component import disney_component , countries_component
function start
begin
string Funcion encargada de iniciar la ventana del menu
set window = call loop
close window
end function
function loop
begin
string Funcion encargada de captar l... | import PySimpleGUI as sg
import time
from src.windows import menu_window
from src.component import disney_component, countries_component
def start():
''' Funcion encargada de iniciar la ventana del menu '''
window = loop()
window.close()
def loop():
''' Funcion encargada de captar los eventos de l... | Python | zaydzuhri_stack_edu_python |
function check_node_parent self resource_id new_parent_id db_session=none *args **kwargs
begin
string Checks if parent destination is valid for node :param resource_id: :param new_parent_id: :param db_session: :return:
return call check_node_parent *args resource_id=resource_id new_parent_id=new_parent_id db_session=db... | def check_node_parent(
self, resource_id, new_parent_id, db_session=None, *args, **kwargs
):
"""
Checks if parent destination is valid for node
:param resource_id:
:param new_parent_id:
:param db_session:
:return:
"""
return self.service.check... | Python | jtatman_500k |
import requests
from bs4 import BeautifulSoup as bs
from selenium import webdriver
set git_user = input string Enter Github User Name:
set url = string https://github.com/ + git_user
set r = get requests url
set soup = call bs content string html.parser
set profile_img = find soup string img dict string alt string Avat... | import requests
from bs4 import BeautifulSoup as bs
from selenium import webdriver
git_user = input('Enter Github User Name: ')
url = "https://github.com/"+git_user
r = requests.get(url)
soup = bs(r.content, 'html.parser')
profile_img = soup.find('img', {'alt':'Avatar'})['src']
driver = webdriver.Chrome()
dr... | Python | zaydzuhri_stack_edu_python |
import sqlite3
from constants import CREATE_TABLE , INSERT_IN_TABLE
class DBConn
begin
string SQLite Database operations
function __init__ self
begin
set db = call connect
set db_iterator = call cursor
call create_table
end function
function connect self
begin
set db = call connect string dict.db
return db
end function... | import sqlite3
from constants import CREATE_TABLE, INSERT_IN_TABLE
class DBConn:
""" SQLite Database operations """
def __init__(self):
self.db = self.connect()
self.db_iterator = self.db.cursor()
self.create_table()
def connect(self):
self.db = sqlite3.connect("d... | Python | zaydzuhri_stack_edu_python |
function get_ast self name
begin
return get mapping name none
end function | def get_ast(self, name):
return self.mapping.get(name, None) | Python | nomic_cornstack_python_v1 |
function apply self state
begin
set action = call obtain_action action_type description state timestamp
set resource = call get_assigned_resource
if resource is not none
begin
call host action timestamp
call hosted resource timestamp
set resource_name = name
end
else
begin
print string Unassigned resource to action + s... | def apply(self, state):
action = Action.obtain_action(self.action_type, self.description, state, self.timestamp)
resource = action.get_assigned_resource()
if resource is not None:
resource.host(action, self.timestamp)
action.hosted(resource, self.timestamp)
se... | Python | nomic_cornstack_python_v1 |
function index self request extra_context=none
begin
set app_dict = dict
set user = user
for tuple model model_admin in items _registry
begin
set app_label = app_label
set has_module_perms = call has_module_perms app_label
if has_module_perms
begin
set perms = call get_model_perms request
comment Check whether user ha... | def index(self, request, extra_context=None):
app_dict = {}
user = request.user
for model, model_admin in self._registry.items():
app_label = model._meta.app_label
has_module_perms = user.has_module_perms(app_label)
if has_module_perms:
perms ... | Python | nomic_cornstack_python_v1 |
comment !/Python27/python
import cgi
function dispForm
begin
print string <form action='statcalc2.py' method='get'> <br>Data Values: <br><input type='text' name='data' /> <br>Data Values Separating Character: <br><input type="text" name='sep' /> <br><br>Operations: <br><input type='checkbox' name='op[]' value='min' che... | #!/Python27/python
import cgi
def dispForm():
print('''
<form action='statcalc2.py' method='get'>
<br>Data Values:
<br><input type='text' name='data' />
<br>Data Values Separating Character:
<br><input type="text" name='sep' />
<br><br>Operations:
<br><input type='checkbox' name='op[]' value='min' checked />Min
<... | Python | zaydzuhri_stack_edu_python |
comment Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos.
import random
set lista = list
set max = 5
for i in range 0 max
begin
set lista = lista + list random integer 40 120
end
set cresc = sorted lista
print format string O maior peso é {} e o menor peso é {} ... | #Faça um programa que leia o peso de cinco pessoas. No final, mostre qual foi o maior e o menor peso lidos.
import random
lista = []
max = 5
for i in range(0,max):
lista += [random.randint(40,120)]
cresc = sorted(lista)
print('O maior peso é {} e o menor peso é {}'.format(cresc[-1], cresc[0]))
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment http://wiki.ros.org/actionlib_tutorials/Tutorials/Writing%20a%20Simple%20Action%20Server%20using%20the%20Execute%20Callback%20%28Python%29
import rospy
import actionlib
from control_msgs.msg import FollowJointTrajectoryAction
from sensor_msgs.msg import JointState
class RobotTraject... | #!/usr/bin/env python
# http://wiki.ros.org/actionlib_tutorials/Tutorials/Writing%20a%20Simple%20Action%20Server%20using%20the%20Execute%20Callback%20%28Python%29
import rospy
import actionlib
from control_msgs.msg import FollowJointTrajectoryAction
from sensor_msgs.msg import JointState
class RobotTrajectoryFollower... | Python | zaydzuhri_stack_edu_python |
import random
set secretNum = random integer 1 100
print string Im thinking of a number between 1 and 100. Git Gud.
set guess = 0
set tries = 1
while guess != secretNum
begin
print string Take a guess! This is try number + string tries
set tries = tries + 1
set guess = integer input
if guess > secretNum
begin
print str... | import random
secretNum = random.randint(1, 100)
print('Im thinking of a number between 1 and 100. Git Gud.')
guess = 0
tries = 1
while guess != secretNum:
print('Take a guess! This is try number ' + str(tries))
tries = tries + 1
guess = int(input())
if guess > secretNum:
print('Enter a smaller number')
elif ... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment Let's Investigate P4K scores
comment Setup and Data Preparation
comment In[9]:
comment %matplotlib inline
comment Display all outputs from cells
from IPython.core.interactiveshell import InteractiveShell
set ast_node_interactivity = string all
comment Import Packages
comment fs
import os a... | # coding: utf-8
# Let's Investigate P4K scores
# Setup and Data Preparation
# In[9]:
# %matplotlib inline
#Display all outputs from cells
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
#Import Packages
#fs
import os as os
#Data manipulation
import num... | Python | zaydzuhri_stack_edu_python |
from pymorse import Morse
from time import sleep
with call Morse as morse
begin
set victim_detector = victim_detector
set waypoint = waypoint
set pose = pose
set go = call goto 10.0 0.0 0.0 1.0 1.0
for i in range 0 3
begin
print string Position %s status %s % tuple call result call result
sleep 1.0
end
call result
prin... | from pymorse import Morse
from time import sleep
with Morse() as morse:
victim_detector = morse.robot.victim_detector
waypoint = morse.robot.waypoint
pose = morse.robot.pose
go = waypoint.goto(10.0, 0.0, 0.0, 1.0, 1.0)
for i in range(0, 3):
print("Position %s status %s\n" % (
... | Python | zaydzuhri_stack_edu_python |
function showEditor self typeInfo
begin
for tuple type editor in items _editor_dict
begin
if type == string Node
begin
continue
end
if type == typeInfo
begin
call setVisible true
end
else
begin
call setVisible false
end
end
end function | def showEditor(self, typeInfo):
for type, editor in self._editor_dict.items():
if type == "Node":
continue
if type == typeInfo:
editor.setVisible(True)
else:
editor.setVisible(False) | Python | nomic_cornstack_python_v1 |
function _get_vel self vehicle_id
begin
set id1 = vehicle_ids at index vehicle_ids vehicle_id - 1
set pos1 = positions at id1
set pos2 = positions at vehicle_id
set dist = call get_distance list pos1 at 0 pos1 at 1 list pos2 at 0 pos2 at 1
set e = e_ref - dist - distance_offset
set vel = call get_u e
if vel < vmin
begi... | def _get_vel(self, vehicle_id):
id1 = self.vehicle_ids[self.vehicle_ids.index(vehicle_id) - 1]
pos1 = self.positions[id1]
pos2 = self.positions[vehicle_id]
dist = self.pt.get_distance([pos1[0], pos1[1]], [pos2[0], pos2[1]])
e = self.e_ref - (dist - self.distance_offset)
... | Python | nomic_cornstack_python_v1 |
import requests , random
while true
begin
set poster = random sample string abcdefghijklmnopqrstuvwxyz!@#$%^&*() 5
set poster = join string poster
set content = random sample string abcdefghijklmnopqrstuvwxyz!@#$%^&*() 10
set content = join string content
set url = string https://paste.ubuntu.com/
set headers = dict ... | import requests,random
while True:
poster = random.sample('abcdefghijklmnopqrstuvwxyz!@#$%^&*()',5)
poster = "".join(poster)
content = random.sample('abcdefghijklmnopqrstuvwxyz!@#$%^&*()',10)
content = "".join(content)
url = 'https://paste.ubuntu.com/'
headers = {'User-Agent': 'Mozilla/5.0 (Wind... | Python | zaydzuhri_stack_edu_python |
function search listy n
begin
set idx = 1
while at listy idx != 1 and at listy idx < n
begin
set idx = idx * 2
end
return call binary_search listy n idx / 2 idx
end function
function binary_search listy n l r
begin
while l <= r
begin
set m = l + r // 2
if at listy m == n
begin
return m
end
if at listy m > n or at listy... | def search(listy, n):
idx = 1
while listy.at(idx) != 1 and listy.at(idx) < n:
idx *= 2
return binary_search(listy, n, idx / 2, idx)
def binary_search(listy, n, l, r):
while l <= r:
m = (l + r) // 2
if listy.at(m) == n:
return m
if listy.at(m) > n or lis... | Python | zaydzuhri_stack_edu_python |
import sys
comment sys.stdin = open("input.txt", "rt")
set a = list range 21
comment _를 넣으면 변수가 없이 10번 도는 것
for _ in range 10
begin
set tuple s e = map int split input
for i in range e - s + 1 // 2
begin
comment reverse 함수보다 직접 바꿔주는 것을 지향
set tuple a at s + i a at e - i = tuple a at e - i a at s + i
end
end
comment 0번 ... | import sys
#sys.stdin = open("input.txt", "rt")
a = list(range(21))
for _ in range(10): # _를 넣으면 변수가 없이 10번 도는 것
s, e = map(int, input().split())
for i in range((e-s+1)//2):
a[s+i], a[e-i] = a[e-i], a[s+i] # reverse 함수보다 직접 바꿔주는 것을 지향
a.pop(0) # 0번 index있는 값을 삭제
for x in a:
print(x, end = ' ')
'... | Python | zaydzuhri_stack_edu_python |
function fasta_format self line_width=none
begin
return call fasta_formatted_string name _sequence description=description line_width=line_width
end function | def fasta_format(self, line_width=None):
return fasta_formatted_string(self.name, self._sequence,
description=self.description,
line_width=line_width) | Python | nomic_cornstack_python_v1 |
function __init__ self name
begin
set name = name
end function | def __init__(self, name):
self.name = name | Python | nomic_cornstack_python_v1 |
function get_current_season_name
begin
set month_nr = call get_current_season
return call get_season_name month_nr
end function | def get_current_season_name():
month_nr = get_current_season()
return get_season_name(month_nr) | Python | nomic_cornstack_python_v1 |
function _push_engine_redis fake_crawl_id crawl_json redis_info
begin
set e = call Redis *redis_info
set fake_crawl_id crawl_json
call expire fake_crawl_id 60 * 60
return e
end function | def _push_engine_redis(fake_crawl_id, crawl_json, redis_info):
e = redis.Redis(*redis_info)
e.set(fake_crawl_id, crawl_json)
e.expire(fake_crawl_id, (60*60))
return e | Python | nomic_cornstack_python_v1 |
function social_choice self
begin
set social_preference = call social_preference
return social_preference at 0
end function | def social_choice (self):
social_preference = self.social_preference()
return social_preference[0] | Python | nomic_cornstack_python_v1 |
comment int
set a = integer a
set b = integer b
set c = integer c
set d = integer d
if a - c == b - d and a - c >= 0
begin
print string YES
end
else
if absolute a - c == absolute b - d
begin
print string YES
end
else
begin
print string NO
end | #int
a = int(a)
b = int(b)
c = int(c)
d = int(d)
if(a - c == b - d and a - c >= 0):
print("YES")
elif(abs(a - c) == abs(b - d)):
print("YES")
else:
print("NO")
| Python | zaydzuhri_stack_edu_python |
function negSamplingCostAndGradient predicted target outputVectors dataset K=10
begin
comment Sampling of indices is done for you. Do not modify this if you
comment wish to match the autograder and receive points!
set indices = list target
extend indices call getNegativeSamples target dataset K
comment YOUR CODE HERE
c... | def negSamplingCostAndGradient(predicted, target, outputVectors, dataset,
K=10):
# Sampling of indices is done for you. Do not modify this if you
# wish to match the autograder and receive points!
indices = [target]
indices.extend(getNegativeSamples(target, dataset, K))
... | Python | nomic_cornstack_python_v1 |
comment get
set a = dict 1 2 ; 2 3 ; 3 4 ; 4 5
print get a 2 0 + get a 4 32
set b = dict 3 2 ; 4 5 ; 6 12
print get a 2 0 + get b 3 19 | #get
a={1:2,2:3,3:4,4:5}
print(a.get(2,0)+a.get(4,32))
b={3:2,4:5,6:12}
print(a.get(2,0)+b.get(3,19))
| Python | zaydzuhri_stack_edu_python |
function threadStart self
begin
print string iniciado
set thread = thread target=thread args=tuple
start thread
end function | def threadStart(self):
print("iniciado")
self.thread = threading.Thread(target=self.thread, args=())
self.thread.start() | Python | nomic_cornstack_python_v1 |
function parse text
begin
from SequencerDSLParser import SequencerDSLParser
set comment_stripped_text = call strip_block_comments text
set parser = call SequencerDSLParser whitespace=string ;
set semantics = call Semantics
set ast = parse parser comment_stripped_text rule_name=string readout semantics=semantics
set ast... | def parse(text):
from SequencerDSLParser import SequencerDSLParser
comment_stripped_text = strip_block_comments(text)
parser = SequencerDSLParser(whitespace='\t ;\n')
semantics = Semantics()
ast = parser.parse(comment_stripped_text,
rule_name='readout',
... | Python | nomic_cornstack_python_v1 |
from heapq import *
class Votes
begin
function __init__ self votes
begin
set candi_count = dict
for tuple candi time in votes
begin
if time < current
begin
if candi_count not in candi_count
begin
set candi_count at candi = 1
end
else
begin
set candi_count at candi = candi_count at candi + 1
end
end
end
set heap = list... | from heapq import *
class Votes():
def __init__(self, votes):
self.candi_count = {}
for candi, time in votes:
if time<current:
if candi_count not in self.candi_count:
self.candi_count[candi] = 1
else:
self.candi_cou... | Python | zaydzuhri_stack_edu_python |
function pic_time bot update
begin
global DAILY_PIC_TIME
if call is_daily_sender update
begin
comment Check new time
try
begin
comment Check valid
set time = integer replace text string /pic_time string
if not 0 < time <= 23
begin
raise call ValueError string Number not in range!
end
comment All checks good, set new ti... | def pic_time(bot, update):
global DAILY_PIC_TIME
if is_daily_sender(update):
# Check new time
try:
# Check valid
time = int(update.message.text.replace("/pic_time ", ""))
if not 0 < time <= 23:
raise ValueError('Number not in range!')
... | Python | nomic_cornstack_python_v1 |
function get_distance node value
begin
return get get dic_list at value - 1 value value
end function | def get_distance(node, value):
return dic_list[node.value - 1].get(node.value).get(value) | Python | nomic_cornstack_python_v1 |
function _get_environ environ
begin
comment type: (Dict[str, str]) -> Iterator[Tuple[str, str]]
set keys = list string SERVER_NAME string SERVER_PORT
if call _should_send_default_pii
begin
comment make debugging of proxy setup easier. Proxy headers are
comment in headers.
set keys = keys + list string REMOTE_ADDR
end
f... | def _get_environ(environ):
# type: (Dict[str, str]) -> Iterator[Tuple[str, str]]
keys = ["SERVER_NAME", "SERVER_PORT"]
if _should_send_default_pii():
# make debugging of proxy setup easier. Proxy headers are
# in headers.
keys += ["REMOTE_ADDR"]
for key in keys:
if key i... | Python | nomic_cornstack_python_v1 |
function get_length self
begin
return length
end function | def get_length(self):
return self.length | Python | nomic_cornstack_python_v1 |
import threading
from queue import Queue
from crawler import Crawler
import fileManipulation as files
import time
from urllib.parse import urlparse
comment Get domain name (edu.pk)
function get_domain_name url
begin
try
begin
comment results = ['lms', 'nust', 'edu', 'pk']
set results = split call get_subdomain_name url... | import threading
from queue import Queue
from crawler import Crawler
import fileManipulation as files
import time
from urllib.parse import urlparse
# Get domain name (edu.pk)
def get_domain_name(url):
try:
results = get_subdomain_name(url).split(".") #results = ['lms', 'nust', 'edu', 'pk']
... | Python | zaydzuhri_stack_edu_python |
function __init__ self channel_group=none gain_provider=none name=none floating=false field=none derivative_order=0
begin
set field = string field
set is_floating = boolean floating
set derivative_order = integer derivative_order
call __init__ channel_group=channel_group gain_provider=gain_provider name=name
end functi... | def __init__(self, channel_group=None, gain_provider=None, name=None,
floating=False, field=None, derivative_order=0):
self.field = str(field)
self.is_floating = bool(floating)
self.derivative_order = int(derivative_order)
super().__init__(channel_group=channel_group,
... | Python | nomic_cornstack_python_v1 |
from sense_hat import SenseHat
from random import randint
from time import sleep
set sense = call SenseHat
while 1
begin
function pick_color
begin
set r = random integer 180 255
set g = random integer 180 255
set b = random integer 180 255
return tuple r g b
end function
function pick_color_text
begin
set r = random in... | from sense_hat import SenseHat
from random import randint
from time import sleep
sense = SenseHat()
while 1:
def pick_color():
r = randint(180,255)
g = randint(180,255)
b = randint(180,255)
return(r,g,b)
def pick_color_text():
r = randint(0,180)
g = randin... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
call set_option string display.max_columns none
import glob
import seaborn as sns
set totol_times = 0
set df = read csv string ../input/bike_aws/bike_1_7.csv
set df = count group by df at string nbBikes df at string BikeP... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
pd.set_option('display.max_columns', None)
import glob
import seaborn as sns
totol_times=0
df = pd.read_csv('../input/bike_aws/bike_1_7.csv')
df = df['nbBikes'].groupby(df['BikePointId']).count()
nobike = pd.Series(index=df.index)... | Python | zaydzuhri_stack_edu_python |
set ages = dict string Alice 24 ; string Bob 3 ; string Carol 15 ; string Dave 15
set sorted_ages = sorted values ages
set sorted_names = list comprehension name for tuple name age in items ages if age in sorted_ages
class AgeData
begin
function __init__ self
begin
set names_by_age = dict
end function
function add_nam... | ages = {"Alice": 24, "Bob": 3, "Carol": 15, "Dave": 15}
sorted_ages = sorted(ages.values())
sorted_names = [name for name, age in ages.items() if age in sorted_ages]
class AgeData:
def __init__(self):
self.names_by_age = {}
def add_name(self, name, age):
if age in self.names_by_age:
... | Python | jtatman_500k |
function decode_replay_initdata contents
begin
set decoder = call BitPackedDecoder contents typeinfos
return call instance replay_initdata_typeid
end function | def decode_replay_initdata(contents):
decoder = BitPackedDecoder(contents, typeinfos)
return decoder.instance(replay_initdata_typeid) | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
from __future__ import print_function
import time , os , traceback
function get_time
begin
set current_time = time
set current_ms = string string : + string round current_time * 1000000 at slice - 6 : :
set current_time = string format time time string %Y/%m/%d | %H:%M:%S call localtime +... | # -*- coding:utf-8 -*-
from __future__ import print_function
import time, os, traceback
def get_time():
current_time = time.time()
current_ms = str(':') + str(round(current_time * 1000000))[-6:]
current_time = time.strftime("%Y/%m/%d | %H:%M:%S", time.localtime()) + current_ms
return current_time
def... | Python | zaydzuhri_stack_edu_python |
function spectral_window self
begin
if _spectral_window is none
begin
set spec_lc = copy lc
set flux = zeros length flux + 1
set _spectral_window = call from_lightcurve spec_lc
end
return _spectral_window
end function | def spectral_window(self):
if self._spectral_window is None:
spec_lc = self.lc.copy()
spec_lc.flux = np.zeros(len(self.lc.flux)) + 1
self._spectral_window = Periodogram.from_lightcurve(spec_lc)
return self._spectral_window | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string Задание 9.2a Сделать копию функции generate_trunk_config из задания 9.2 Изменить функцию таким образом, чтобы она возвращала не список команд, а словарь: - ключи: имена интерфейсов, вида 'FastEthernet0/1' - значения: список команд, который надо выполнить... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Задание 9.2a
Сделать копию функции generate_trunk_config из задания 9.2
Изменить функцию таким образом, чтобы она возвращала не список команд, а словарь:
- ключи: имена интерфейсов, вида 'FastEthernet0/1'
- значения: список команд, который надо выполнить на эт... | Python | zaydzuhri_stack_edu_python |
function logServer port base_dir logFilename=string logFile.log
begin
call basicConfig filename=join path base_dir logFilename level=DEBUG format=string
info string format time call utcnow string %Y/%m/%d %H:%M:%S.%f + string [LOGGER][INFO][logServer] : started logging server
set context = call Context
set theSocket = ... | def logServer(port, base_dir, logFilename="logFile.log"):
logging.basicConfig(filename=os.path.join(base_dir, logFilename), level=logging.DEBUG, format='')
logging.info(datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S.%f") +
" [LOGGER][INFO][logServer] : started logging server")
context = zmq.... | Python | nomic_cornstack_python_v1 |
function test_first_id self
begin
set ids = split string R27DLI_4812 R27DLI_600 R27DLI_727 U1PLI_403 U1PLI_8969
assert equal call first_id ids dict string R27DLI_4812
end function | def test_first_id(self):
ids = \
"R27DLI_4812 R27DLI_600 R27DLI_727 U1PLI_403 U1PLI_8969".split(
)
self.assertEqual(first_id(ids, {}), 'R27DLI_4812') | Python | nomic_cornstack_python_v1 |
import turtle
comment Draw Four Circles
call pensize 5
function drawCircle
begin
call circle 45
call circle - 45
call penup
call goto 90 0
call pendown
end function
call drawCircle
call drawCircle | import turtle
#Draw Four Circles
turtle.pensize(5)
def drawCircle():
turtle.circle(45)
turtle.circle(-45)
turtle.penup()
turtle.goto(90, 0)
turtle.pendown()
drawCircle()
drawCircle()
| Python | zaydzuhri_stack_edu_python |
function _optimize_field_by_name self store model selection field_def
begin
set name = call _get_name_from_field_dev field_def
if not model_field := call _get_model_field_from_name model name
begin
return false
end
info string _optimize_field_by_name %r %r name model_field
if call _is_foreign_key_id model_field name
be... | def _optimize_field_by_name(self, store: QueryOptimizerStore, model, selection, field_def) -> bool:
name = self._get_name_from_field_dev(field_def)
if not (model_field := self._get_model_field_from_name(model, name)):
return False
_logger.info('_optimize_field_by_name %r %r', name, m... | Python | nomic_cornstack_python_v1 |
import numpy as np
import numpy.linalg as la
import copy
string Swarm intelligence algorithms, e.g. particle swarm optimization (PSO)
class PSO extends object
begin
function __init__ self sde=none **kwargs
begin
set dynamics = sde
set item = item
set world = world
set d = dim
comment Number of particles
set N = N
set o... | import numpy as np
import numpy.linalg as la
import copy
''' Swarm intelligence algorithms, e.g. particle swarm optimization (PSO)
'''
class PSO(object):
def __init__(self, sde=None, **kwargs):
self.dynamics = sde
self.item = self.dynamics.item
self.world = self.d... | Python | zaydzuhri_stack_edu_python |
comment Q1
function is_odd number
begin
if number % 2 == 1
begin
return true
end
else
begin
return false
end
end function
print call is_odd 5
comment Q2
function avg_numbers *args
begin
set result = 0
for i in args
begin
set result = result + i
end
return result / length args
end function
print call avg_numbers 1 2
pri... | # Q1
def is_odd(number):
if number % 2==1:
return True
else:
return False
print(is_odd(5))
# Q2
def avg_numbers(*args):
result = 0
for i in args:
result += i
return result / len(args)
print(avg_numbers(1,2))
print(avg_numbers(1,2,3,4,5))
#Q3
input1 = input("첫번째 숫자를 입력하세요:... | Python | zaydzuhri_stack_edu_python |
string 8. Матрица 5x4 заполняется вводом с клавиатуры кроме последних элементов строк. Программа должна вычислять сумму введенных элементов каждой строки и записывать ее в последнюю ячейку строки. В конце следует вывести полученную матрицу.
set N = 5
set M = 4
set array1 = list
print string Заполним двумерный массив, ... | """
8. Матрица 5x4 заполняется вводом с клавиатуры кроме последних элементов строк.
Программа должна вычислять сумму введенных элементов каждой строки и
записывать ее в последнюю ячейку строки.
В конце следует вывести полученную матрицу.
"""
N = 5
M = 4
array1 = []
print(f"Заполним двумерный массив, размером [{N}][{M... | Python | zaydzuhri_stack_edu_python |
comment make_countries_json.py
comment dependencies
comment GDAL/ogr
comment usage:
comment ensure that the input and output filenames are correct, below
comment python3 make_countries_json.py
comment when complete, copy countries.json to ../static/data
comment Update 4/2022:
comment Mason/GEM has a standardized set of... | # make_countries_json.py
# dependencies
# GDAL/ogr
# usage:
# ensure that the input and output filenames are correct, below
# python3 make_countries_json.py
# when complete, copy countries.json to ../static/data
# Update 4/2022:
# Mason/GEM has a standardized set of global country names, and I have copied these ... | Python | zaydzuhri_stack_edu_python |
set number = 9
comment print type of variable "number"
print type number
set float_number = 9.0
print string xxxxxx float_number
print string xxxxxx + string float_number | number = 9
print(type(number)) # print type of variable "number"
float_number = 9.0
print("xxxxxx",float_number)
print("xxxxxx"+str(float_number))
| Python | zaydzuhri_stack_edu_python |
function get_cl_precision self
begin
return cl_precision
end function | def get_cl_precision(self):
return self.arrays[0].cl_precision | Python | nomic_cornstack_python_v1 |
function create_auth_perm self owner_uuid permission_name description=none
begin
set payload = dict string owner string owner_uuid ; string name permission_name ; string description description
set resp = post AUTH_BASE_URL string /api/v1/permissions payload=payload timeout=1.0
if status_code == 201
begin
return json r... | def create_auth_perm(self, owner_uuid, permission_name, description=None):
payload = {
"owner": str(owner_uuid),
"name": permission_name,
"description": description,
}
resp = self.post(
AUTH_BASE_URL, "/api/v1/permissions", payload=payload, timeout... | Python | nomic_cornstack_python_v1 |
from urllib import request , parse
import json
if __name__ == string __main__
begin
set url = string https://fanyi.baidu.com/sug
set kw = input string INPUT:
set data = dict string kw kw
set data = encode url encode data
set rsp = url open url data=data
print rsp
set json_data = decode read rsp
print json_data
set rst ... | from urllib import request,parse
import json
if __name__ == "__main__":
url = "https://fanyi.baidu.com/sug"
kw = input("INPUT:")
data = {
"kw": kw
}
data = parse.urlencode(data).encode()
rsp = request.urlopen(url, data=data)
print(rsp)
json_data = rsp.read().decode()
print(... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Nov 6 08:54:38 2018 @author: yuanz
import pdb
from PIL import Image , ImageFilter
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
import skimage
import cv2
comment from skimage.morphology import disk
set img = open string E:/实验三/图3-1.tif
se... | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 6 08:54:38 2018
@author: yuanz
"""
import pdb
from PIL import Image,ImageFilter
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
import skimage
import cv2
#from skimage.morphology import disk
img=Image.open('E:/实验三/图3-1.tif')
... | Python | zaydzuhri_stack_edu_python |
function getClientSSLContext self
begin
string Returns an ssl.SSLContext appropriate for initiating a TLS session
set sslctx = call create_default_context SERVER_AUTH
call _loadCasIntoSSLContext sslctx
return sslctx
end function | def getClientSSLContext(self):
'''
Returns an ssl.SSLContext appropriate for initiating a TLS session
'''
sslctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
self._loadCasIntoSSLContext(sslctx)
return sslctx | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
import models as md
import random , time
set pubnub = call inicializador
set publicador = call Publicador
function publicaTemp canal num_leituras
begin
for i in range num_leituras
begin
set temperatura = round uniform 0 100 2
call publica_mensagem pubnub canal string temperatura
sleep 0.5
... | # -*- coding: utf-8 -*-
import models as md
import random, time
pubnub = md.InicializadorPubnub('sub-c-c52c96a4-3f6c-11e9-978c-aae2bd4c3b77', 'pub-c-3d596091-11f9-4424-9796-7a67018f578d').inicializador()
publicador = md.Publicador()
def publicaTemp(canal, num_leituras):
for i in range(num_leituras):
... | Python | zaydzuhri_stack_edu_python |
class C
begin
function __contains__ self other
begin
return true
end function
function __iter__ self
begin
for x in range 3
begin
yield x
end
end function
end class
set c = call C
if 10 in c
begin
print string yes
end
for i in c
begin
print i
end | class C:
def __contains__(self, other):
return True
def __iter__(self):
for x in range(3):
yield x
c = C()
if 10 in c:
print('yes')
for i in c:
print(i)
| Python | zaydzuhri_stack_edu_python |
string Part 1 answer: 72070 Part 2 answer: 211805
from y2022.python.shared import get_data_file_path
function main
begin
set tallies = call tally_calories
print string PART 1: tallies at - 1
print string PART 2: sum tallies at slice - 3 : :
end function
function tally_calories
begin
set tallies = list
set elf_total =... | """
Part 1 answer: 72070
Part 2 answer: 211805
"""
from y2022.python.shared import get_data_file_path
def main():
tallies = tally_calories()
print("PART 1:", tallies[-1])
print("PART 2:", sum(tallies[-3:]))
def tally_calories() -> list[int]:
tallies = []
elf_total = 0
with open(get_data_file... | Python | zaydzuhri_stack_edu_python |
function _check_email_changed cls username email
begin
string Compares email to one set on SeAT
set ret = call exec_request format string user/{} username string get raise_for_status=true
return ret at string email != email
end function | def _check_email_changed(cls, username, email):
"""Compares email to one set on SeAT"""
ret = cls.exec_request('user/{}'.format(username), 'get', raise_for_status=True)
return ret['email'] != email | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.