code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function initpeer self sock
begin
string Creates a new peer object for a nvalid socket and adds it to reactor's listen list
set location_json = content
set location = loads location_json
set tpeer = call Peer sock reactor self location
set peer_dict at sock = tpeer
append select_list tpeer
end function | def initpeer(self, sock):
'''
Creates a new peer object for a nvalid socket and adds it to reactor's
listen list
'''
location_json = requests.request("GET", "http://freegeoip.net/json/"
+ sock.getpeername()[0]).content
location = j... | Python | jtatman_500k |
import pickle
import retino
from retino.plot import *
from retino.utils import *
call set_style string ticks
function plot_axon_growth_direction_algorithm origin end target ax
begin
set a_origin = origin
set a_end = end
set desired_direction_weight = 1.1
set momentum_direction_weight = 1
set desired_direction = call ge... | import pickle
import retino
from retino.plot import *
from retino.utils import *
sns.set_style("ticks")
def plot_axon_growth_direction_algorithm(origin, end, target, ax):
a_origin = origin
a_end = end
desired_direction_weight = 1.1
momentum_direction_weight = 1
desired_direction = get_unit_dir... | Python | zaydzuhri_stack_edu_python |
class Dog
begin
set species = string Canis familiaris
function __init__ self name age
begin
set name = name
set age = age
end function
function __str__ self
begin
return string { name } is { age } years old
end function
function speak self sound
begin
return string { name } says { sound }
end function
end class
class G... | class Dog:
species = "Canis familiaris"
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return f"{self.name} is {self.age} years old"
def speak(self,sound):
return f"{self.name} says {sound}"
class GoldenRetriever(Dog):
def speak(self... | Python | zaydzuhri_stack_edu_python |
function convert_to_binary integer_schedule
begin
set binary_schedule = where integer_schedule > 0 1 0
return binary_schedule
end function | def convert_to_binary(integer_schedule):
binary_schedule = np.where(integer_schedule > 0, 1, 0)
return binary_schedule | Python | nomic_cornstack_python_v1 |
function create_app self stack_id name type shortname=none description=none app_source=none domains=none enable_ssl=none ssl_configuration=none attributes=none
begin
set params = dict string StackId stack_id ; string Name name ; string Type type
if shortname is not none
begin
set params at string Shortname = shortname
... | def create_app(self, stack_id, name, type, shortname=None,
description=None, app_source=None, domains=None,
enable_ssl=None, ssl_configuration=None, attributes=None):
params = {'StackId': stack_id, 'Name': name, 'Type': type, }
if shortname is not None:
... | Python | nomic_cornstack_python_v1 |
import cv2
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.neighbors import LocalOutlierFactor
from utils_old import coord_generator , des_list , best_score_label , average_score_label
comment import modules
set img1 = call imread string images\img_test1.jpg 0
comment ... | import cv2
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.neighbors import LocalOutlierFactor
from utils_old import coord_generator, des_list, best_score_label, average_score_label
# import modules
img1 = cv2.imread('images\\img_test1.jpg', 0)
# import testing image
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
from sklearn.datasets import load_digits
comment 导入三种常用的朴素贝叶斯算法
from sklearn.naive_bayes import GaussianNB , MultinomialNB , BernoulliNB
comment 分类准确率分数是指所有分类正确的百分比。
from sklearn.metrics import accuracy_score
comment 返回切分的数据集train/test
from sklearn.model... | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from sklearn.datasets import load_digits
from sklearn.naive_bayes import GaussianNB,MultinomialNB,BernoulliNB #导入三种常用的朴素贝叶斯算法
from sklearn.metrics import accuracy_score #分类准确率分数是指所有分类正确的百分比。
from sklearn.model_selection import train... | Python | zaydzuhri_stack_edu_python |
function get_line_ids self
begin
set line_ids = dict
set line_list = list call GetObjectsInGroup string Lines
for line_object in line_list
begin
comment TODO Problem with GetObjectIDByName
try
begin
set line_ids at line_object = string call GetObjectIDByName line_object
end
except any
begin
warning format string Line ... | def get_line_ids(self):
line_ids = {}
line_list = list(self.oeditor.GetObjectsInGroup("Lines"))
for line_object in line_list:
# TODO Problem with GetObjectIDByName
try:
line_ids[line_object] = str(self.oeditor.GetObjectIDByName(line_object))
ex... | Python | nomic_cornstack_python_v1 |
import io
from tkinter.filedialog import *
from PIL import Image
class Paint extends Frame
begin
set result_image_size = tuple 28 28
function __init__ self parent neuron_net
begin
call __init__ self parent
set neuron_net = neuron_net
set parent = parent
set digit_label = none
set canvas = none
set color = string black
... | import io
from tkinter.filedialog import *
from PIL import Image
class Paint(Frame):
result_image_size = 28, 28
def __init__(self, parent, neuron_net):
Frame.__init__(self, parent)
self.neuron_net = neuron_net
self.parent = parent
self.digit_label = None
self.canvas =... | Python | zaydzuhri_stack_edu_python |
function check_updates self
begin
try
begin
if not call latest_version version
begin
call update_notify
end
end
except any
begin
call neterror
end
end function | def check_updates(self):
try:
if not common.latest_version(version):
self.update_notify()
except:
self.neterror() | Python | nomic_cornstack_python_v1 |
function format_length self key
begin
return call calcsize self at key
end function | def format_length( self, key ) :
return struct.calcsize( self[key] ) | Python | nomic_cornstack_python_v1 |
from CharGen.Rulesets.Pathfinder.Rules import *
class DokuWikiFormatter
begin
function __init__ self
begin
pass
end function
function write self character
begin
set output = string
comment First the name of the character.
set output = string ===== + call getName + string =====
set output = output + get size character ... | from CharGen.Rulesets.Pathfinder.Rules import *
class DokuWikiFormatter:
def __init__(self):
pass
def write(self, character):
output = ""
# First the name of the character.
output = "===== " + character.getName() + " =====\n"
output += character.getSize() + " " + chara... | Python | zaydzuhri_stack_edu_python |
comment grid.pyde
comment set the range of x-values
set xmin = - 10
set xmax = 10
comment range of y-values
set ymin = - 10
set ymax = 10
comment calculate the range
set rangex = xmax - xmin
set rangey = ymax - ymin
function setup
begin
global xscl yscl
size 600 600
set xscl = width / rangex
set yscl = - height / range... | #grid.pyde
#set the range of x-values
xmin=-10
xmax=10
#range of y-values
ymin = -10
ymax = 10
#calculate the range
rangex = xmax - xmin
rangey = ymax - ymin
def setup():
global xscl, yscl
size(600,600)
xscl= width / rangex
yscl= -height / rangey
def draw():
global xscl, ys... | Python | zaydzuhri_stack_edu_python |
with open string Shortcut-GPS.html string w as f
begin
write f string <head><link rel='stylesheet' href='shortcut.css'></head>
write f string <h1>Shortcut GPS</h1>
write f string <table style='font-size:400%'>
write f string <tr><td><a href='https://github.com/ChristerNilsson/Lab/blob/master/2018/037-Shortcut-GPS/READM... | with open("Shortcut-GPS.html", "w") as f:
f.write("<head><link rel='stylesheet' href='shortcut.css'></head>\n")
f.write("<h1>Shortcut GPS</h1>\n")
f.write("<table style='font-size:400%'>\n")
f.write("<tr><td><a href='https://github.com/ChristerNilsson/Lab/blob/master/2018/037-Shortcut-GPS/README.md#shortcut-gps'>In... | Python | zaydzuhri_stack_edu_python |
comment import text
import sys
comment search for patterns in text
import re
comment if the command line only receives one argument (i.e $python nazgul.py) it will send an error message because you need to send the text file as an argument as well | # import text
import sys
# search for patterns in text
import re
# if the command line only receives one argument (i.e $python nazgul.py) it will send an error message because you need to send the text file as an argument as well | Python | zaydzuhri_stack_edu_python |
string Decision Tree & Random Forest
import pandas as pd
import numpy as np
import csv
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn import cross_validation
from random import randint
from sklearn.pipeline import Pipeline
from sklearn.preprocessing im... | '''
Decision Tree & Random Forest
'''
import pandas as pd
import numpy as np
import csv
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn import cross_validation
from random import randint
from sklearn.pipeline import Pipeline
from sklearn.preprocessing i... | Python | zaydzuhri_stack_edu_python |
function get_exif_location self exif_data lonlat
begin
if lonlat == string lonlat
begin
set lat = string
set lon = string
set gps_latitude = call _get_if_exist exif_data string GPS GPSLatitude
set gps_latitude_ref = call _get_if_exist exif_data string GPS GPSLatitudeRef
set gps_longitude = call _get_if_exist exif_dat... | def get_exif_location(self, exif_data, lonlat):
if lonlat=='lonlat':
lat = ''
lon = ''
gps_latitude = self._get_if_exist(exif_data, 'GPS GPSLatitude')
gps_latitude_ref = self._get_if_exist(exif_data, 'GPS GPSLatitudeRef')
gps_longitude = self._get_if_... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import spacy
import re
import string
comment load reviews data
set reviews = read csv string 7282_1.csv
comment extract only reviews
set comments = reviews at string reviews.text
set comments = as type comments string str
comment function to remove non-ascii characters
function _r... | import pandas as pd
import numpy as np
import spacy
import re
import string
#load reviews data
reviews = pd.read_csv('7282_1.csv')
#extract only reviews
comments = reviews['reviews.text']
comments = comments.astype('str')
#function to remove non-ascii characters
def _removeNonAscii(s): return "".join(i for i in s if ... | Python | zaydzuhri_stack_edu_python |
function _add_open_file self file_obj
begin
string Add file_obj to the list of open files on the filesystem. Used internally to manage open files. The position in the open_files array is the file descriptor number. Args: file_obj: File object to be added to open files list. Returns: File descriptor number for the file ... | def _add_open_file(self, file_obj):
"""Add file_obj to the list of open files on the filesystem.
Used internally to manage open files.
The position in the open_files array is the file descriptor number.
Args:
file_obj: File object to be added to open files list.
Re... | Python | jtatman_500k |
set x = 10
set y = 10
set z = x + y
set a = x - y
print x
print a | x = 10
y = 10
z = x + y
a = x - y
print(x)
print(a) | Python | zaydzuhri_stack_edu_python |
function _get_binary_from_equalized_grayscale self image
begin
set gray = call cvtColor image COLOR_BGR2GRAY
set eq_global = call equalizeHist gray
set tuple _ th = call threshold eq_global thresh=250 maxval=255 type=THRESH_BINARY
return th
end function | def _get_binary_from_equalized_grayscale(self, image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
eq_global = cv2.equalizeHist(gray)
_, th = cv2.threshold(eq_global, thresh=250, maxval=255, type=cv2.THRESH_BINARY)
return th | Python | nomic_cornstack_python_v1 |
function som stenen
begin
return sum stenen
end function
function is_Yathzee stenen
begin
set gesorteerd = sorted stenen
return gesorteerd at 0 == gesorteerd at - 1
end function
function is_grote_straat stenen
begin
set lengte = length stenen
set gesorteerd = sorted stenen
set antwoord = true
set i = 0
while i in range... | def som(stenen):
return sum(stenen)
def is_Yathzee(stenen):
gesorteerd = sorted(stenen)
return gesorteerd[0] == gesorteerd[-1]
def is_grote_straat(stenen):
lengte = len(stenen)
gesorteerd = sorted(stenen)
antwoord = True
i = 0
while i in range(lengte-1):
if gesorteerd[i] + 1 !=... | Python | zaydzuhri_stack_edu_python |
from geometry.bangun_ruang import BangunRuang
from geometry.persegipanjang import PersegiPanjang
from geometry.segitiga import Segitiga
print string menggunakan OOP
set p11 = call PersegiPanjang 10 3
print info
print call hitung_luas
set s12 = call Segitiga 10 3
print info
print call hitung_luas
print string Mencoba me... | from geometry.bangun_ruang import BangunRuang
from geometry.persegipanjang import PersegiPanjang
from geometry.segitiga import Segitiga
print('menggunakan OOP')
p11 = PersegiPanjang(10, 3)
print(p11.info())
print(p11.hitung_luas())
s12 = Segitiga(10,3)
print (s12.info())
print(s12.hitung_luas())
print('\nMencoba mem... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sat Apr 4 17:04:21 2020 @author: tianrenmi
import tensorflow as tf
set x = call constant list 64.3 99.6 145.45 63.75 135.46 92.85 86.97 144.76 59.3 116.03
set y = call constant list 62.55 82.42 132.62 73.31 131.05 86.57 85.49 127.44 55.25 104.84
set n = size tf x
set n = ... | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 4 17:04:21 2020
@author: tianrenmi
"""
import tensorflow as tf
x = tf.constant([ 64.3, 99.6, 145.45, 63.75, 135.46, 92.85, 86.97, 144.76, 59.3, 116.03])
y = tf.constant([ 62.55, 82.42, 132.62, 73.31, 131.05, 86.57, 85.49, 127.44, 55.25, 104.84])
n = tf.siz... | Python | zaydzuhri_stack_edu_python |
comment Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
comment For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
comment Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
string Check for imports on private external modules and names.
from __future__ i... | # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
# Copyright (c) https://github.com/PyCQA/pylint/blob/main/CONTRIBUTORS.txt
"""Check for imports on private external modules and names."""
from __future__ import annotations... | Python | zaydzuhri_stack_edu_python |
function some_data
begin
return 42.0
end function | def some_data():
return 42. | Python | nomic_cornstack_python_v1 |
from collections import deque
set tuple n k = map int split input
set data = list
set graph = list
for i in range n
begin
append graph list map int split input
for j in range n
begin
if graph at i at j > 0
begin
comment 바이러스 타입, x좌표, y좌표 순
append data tuple graph at i at j i j 0
end
end
end
set tuple s x y = map int ... | from collections import deque
n, k = map(int, input().split())
data = []
graph = []
for i in range(n):
graph.append(list(map(int, input().split())))
for j in range(n):
if graph[i][j] > 0:
# 바이러스 타입, x좌표, y좌표 순
data.append((graph[i][j], i, j, 0))
s, x, y = map(int, input().... | Python | zaydzuhri_stack_edu_python |
import os
from django.db import models
from django.conf import settings
from django.core.files.storage import FileSystemStorage
comment Create your models here.
comment 이미지 덮어쓰기
class OverwriteStorage extends FileSystemStorage
begin
function get_available_name self name max_length=none
begin
if exists self name
begin
r... | import os
from django.db import models
from django.conf import settings
from django.core.files.storage import FileSystemStorage
# Create your models here.
# 이미지 덮어쓰기
class OverwriteStorage(FileSystemStorage):
def get_available_name(self, name, max_length=None):
if self.exists(name):
os.remove(... | Python | zaydzuhri_stack_edu_python |
string Dit is commentaar. Je herkent dit aan de drie aanhalingstekens. Alles dat hier tussen wordt geschreven wordt door Python genegeerd.
comment Commentaar op 1 regel kan ook, met een hashtag.
comment Hier importeren we functionaliteit uit een andere module
from random import randrange
comment Definieer een functie m... | '''
Dit is commentaar. Je herkent dit aan de drie aanhalingstekens.
Alles dat hier tussen wordt geschreven wordt door Python
genegeerd.
'''
# Commentaar op 1 regel kan ook, met een hashtag.
# Hier importeren we functionaliteit uit een andere module
from random import randrange
# Definieer een functie met... | Python | zaydzuhri_stack_edu_python |
function print self line
begin
write tw string { line }
end function | def print(self, line):
self.tw.write(f"{line}\n") | Python | nomic_cornstack_python_v1 |
function hf_energy hf_state hamiltonian_sp
begin
set qpu = call get_default_qpu
set res = call submit call to_job job_type=string OBS observable=hamiltonian_sp
return value
end function | def hf_energy(hf_state, hamiltonian_sp):
qpu = get_default_qpu()
res = qpu.submit(hf_state.to_job(job_type="OBS", observable=hamiltonian_sp))
return res.value | Python | nomic_cornstack_python_v1 |
function _run_bq_load source_blob_path source_bucket_name=string ghtrends target_dataset_name=string ghtrends target_table_name=string gitlog_records job_config=BQ_JOB_CONFIG
begin
assert call _verify_blob blob_path=source_blob_path bucket_name=source_bucket_name
set source_uri = string gs:// { source_bucket_name } / {... | def _run_bq_load(
source_blob_path: str,
source_bucket_name: str = "ghtrends",
target_dataset_name: str = "ghtrends",
target_table_name: str = "gitlog_records",
job_config: bigquery.LoadJobConfig = BQ_JOB_CONFIG,
) -> bool:
assert _verify_blob(blob_path=source_blob_path, bucket_name=source_bucke... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Problem 56 - Powerful digit sum A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the f... | # -*- coding: utf-8 -*-
"""
Problem 56 - Powerful digit sum
A googol (10^100) is a massive number: one followed by one-hundred zeros;
100^100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, a^... | Python | zaydzuhri_stack_edu_python |
function center_ship self
begin
set center = centerx
end function | def center_ship(self):
self.center = self.screen_rect.centerx | Python | nomic_cornstack_python_v1 |
import engines
from board2 import Board
set royalTour = list string [FEN "W:W27,19,18,11,7,6,5:B28,26,25,20,17,10,9,4,3,2"] string [FEN "B:W27,18,15,11,5,6,7:B25,26,28,17,20,9,10,2,3,4"] string [FEN "W:W27,18,11,5,6,7:B25,26,28,17,19,20,9,2,3,4"] string [FEN "B:W27,18,11,6,7,K1:B25,26,28,17,19,20,9,2,3,4"] string [FEN ... | import engines
from board2 import Board
royalTour = [
'[FEN "W:W27,19,18,11,7,6,5:B28,26,25,20,17,10,9,4,3,2"]',
'[FEN "B:W27,18,15,11,5,6,7:B25,26,28,17,20,9,10,2,3,4"]',
'[FEN "W:W27,18,11,5,6,7:B25,26,28,17,19,20,9,2,3,4"]',
'[FEN "B:W27,18,11,6,7,K1:B25,26,28,17,19,20,9,2,3,4"]',
'[FEN "W:W27,1... | Python | zaydzuhri_stack_edu_python |
function get_fitness self use_opacity=true
begin
set chromosome_img = call generate_chromosome_image use_opacity=use_opacity
set fitness = sum as type chromosome_img string float - as type _img string float ^ 2
set fitness = fitness / decimal shape at 0 * shape at 1
return fitness
end function | def get_fitness(self, use_opacity=True):
chromosome_img = self.generate_chromosome_image(use_opacity=use_opacity)
fitness = np.sum((chromosome_img.astype("float") - self._img.astype("float")) ** 2)
fitness /= float(chromosome_img.shape[0] * chromosome_img.shape[1])
return fitness | Python | nomic_cornstack_python_v1 |
import pyautogui
import keyboard
import numpy as np
import cv2
from solver import SudokuSolver
from mss import mss
from tensorflow import keras
comment import matplotlib.pyplot as plt
comment import pandas as pd
function get_positions
begin
print string Press x
while true
begin
if call is_pressed string x
begin
set P1 ... | import pyautogui
import keyboard
import numpy as np
import cv2
from solver import SudokuSolver
from mss import mss
from tensorflow import keras
# import matplotlib.pyplot as plt
# import pandas as pd
def get_positions():
print('Press x')
while(True):
if keyboard.is_pressed('x'):
... | Python | zaydzuhri_stack_edu_python |
function __init__ self kubeconfig_path=none k8s_namespace=string thecombine
begin
set kubectl_opts = list string -n string { k8s_namespace }
if kubeconfig_path is not none and call is_file
begin
append kubectl_opts string --kubeconfig= { kubeconfig_path }
end
comment Cache the pod id so we only have to look it up once
... | def __init__(
self, *, kubeconfig_path: Optional[Path] = None, k8s_namespace: str = "thecombine"
) -> None:
self.kubectl_opts = ["-n", f"{k8s_namespace}"]
if kubeconfig_path is not None and kubeconfig_path.is_file():
self.kubectl_opts.append(f"--kubeconfig={kubeconfig_path}")
... | Python | nomic_cornstack_python_v1 |
function test_fma_invalid_param_bytes_bytes_str_str_1208 self
begin
comment This version is expected to pass.
call fma floatarrayx floatarrayy floatarrayz floatarrayout
comment This is the actual test.
with assert raises TypeError
begin
call fma bytesx bytesy strz strout
end
end function | def test_fma_invalid_param_bytes_bytes_str_str_1208(self):
# This version is expected to pass.
arrayfunc.fma(self.floatarrayx, self.floatarrayy, self.floatarrayz, self.floatarrayout)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.fma(self.bytesx, self.bytesy, self.strz, self.strout) | Python | nomic_cornstack_python_v1 |
function extract_access_token header_content
begin
return split header_content at 1
end function | def extract_access_token(header_content: str) -> str:
return header_content.split()[1] | Python | nomic_cornstack_python_v1 |
import re
comment The caret(^) in this case specifies that the match must be at the start of the string.
set beginsWithRegex = compile string ^Hello
comment This would match as Hello is at the start.
set ma = search string Hello there!
print call group
comment This would not as it is not at the start.
set ma = search s... | import re
beginsWithRegex = re.compile(r'^Hello') #The caret(^) in this case specifies that the match must be at the start of the string.
ma = beginsWithRegex.search('Hello there!') #This would match as Hello is at the start.
print(ma.group())
ma = beginsWithRegex.search('He said "Hello there!"') #This would not as... | Python | zaydzuhri_stack_edu_python |
function decrypt_file self input_file_name=string output_file_name=string
begin
comment Checking if input and output files selected right
assert input_file_name and is file input_file_name msg string Input file wasn't selected!
assert output_file_name msg string Output file wasn't selected!
with open output_file_name ... | def decrypt_file(self, input_file_name='', output_file_name=''):
# Checking if input and output files selected right
assert input_file_name and isfile(input_file_name), "Input file wasn't selected!"
assert output_file_name, "Output file wasn't selected!"
with open(output_file_name, 'wb... | Python | nomic_cornstack_python_v1 |
from pytube import Playlist
import os
from pydub import AudioSegment
from moviepy.editor import *
set playlist_url = string https://www.youtube.com/playlist?list=PLXnQbBsB_NnJuevcSpBO1_0wibuceFxE9
set playlist = call Playlist playlist_url
print string Playlist Title: title
comment Download each video in the playlist an... | from pytube import Playlist
import os
from pydub import AudioSegment
from moviepy.editor import *
playlist_url = "https://www.youtube.com/playlist?list=PLXnQbBsB_NnJuevcSpBO1_0wibuceFxE9"
playlist = Playlist(playlist_url)
print("Playlist Title:", playlist.title)
# Download each video in the playlist and extr... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment --------------------------------------
comment lcd2004.py
comment 20x4 LCD Test Script with
comment backlight control and text justification
comment https://www.sunfounder.com/
comment --------------------------------------
comment The wiring for the LCD is as follows:
comment 1 : ... | #!/usr/bin/env python3
#--------------------------------------
#
# lcd2004.py
# 20x4 LCD Test Script with
# backlight control and text justification
#
# https://www.sunfounder.com/
#
#--------------------------------------
# The wiring for the LCD is as follows:
# 1 : GND
# 2 : 5V
# 3 : Contrast (0-5V)* Ground thi... | Python | zaydzuhri_stack_edu_python |
function execute self command retry=3 retry_interval=10
begin
import logging
debug string execute node: { leased_resource_name } , management_ip: { mgmt_ip } , command: { command }
for attempt in range retry
begin
try
begin
set key = call __get_paramiko_key private_key_file=private_key_file
set client = call SSHClient
... | def execute(self, command, retry=3, retry_interval=10):
import logging
logging.debug(f"execute node: {self.leased_resource_name}, management_ip: {self.mgmt_ip}, command: {command}")
for attempt in range(retry):
try:
key = self.__get_paramiko_key(private_key_file=sel... | Python | nomic_cornstack_python_v1 |
import operator , json , copy , pickle
from math import log | import operator, json, copy, pickle
from math import log
| Python | zaydzuhri_stack_edu_python |
import os
import csv
import time
import random
import requests
import socket
import socks
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from selenium import webdriver
from selenium.webdriver import Chrome
from docx import Document
from docx.shared import Inches
from colorama import init as colorini... | import os
import csv
import time
import random
import requests
import socket
import socks
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
from selenium import webdriver
from selenium.webdriver import Chrome
from docx import Document
from docx.shared import Inches
from colorama import ini... | Python | zaydzuhri_stack_edu_python |
import mrcfile as mf
import numpy as np
import argparse
import math
import sys
import warnings
from pyrelion.metadata import MetaData
from matrix import rotMatrix
class Recenter
begin
function __init__ self starfile mask dmap l angpix
begin
string Initialization of rencenter Args: starfile: .star file that stores the s... | import mrcfile as mf
import numpy as np
import argparse
import math
import sys
import warnings
from pyrelion.metadata import MetaData
from matrix import rotMatrix
class Recenter():
def __init__(self, starfile, mask, dmap, l, angpix):
'''
Initialization of rencenter
Args: \n
starfile: .star file tha... | Python | zaydzuhri_stack_edu_python |
comment Tutbot by Da532
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import chalk
set bot = call Bot command_prefix=string .
print __version__
decorator event
async function on_ready
begin
print string Hi I'm Lash!
print string I will be your personal assistant!
pr... | # Tutbot by Da532
import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import chalk
bot = commands.Bot(command_prefix='.')
print (discord.__version__)
@bot.event
async def on_ready():
print ("Hi I'm Lash!")
print ("I will be your personal assist... | Python | zaydzuhri_stack_edu_python |
function __init__ self required=dict excluded=dict exact_match=true DEBUG=false
begin
set logger = call get_logger name=string Filter DEBUG=DEBUG
set required = none
set excluded = none
if is instance required dict
begin
set required = required
end
else
begin
set required = dict
error msg=string Required is not a di... | def __init__(self, required={}, excluded={}, exact_match=True, DEBUG=False):
self.logger = get_logger(name="Filter", DEBUG=DEBUG)
self.required = None
self.excluded = None
if isinstance(required, dict):
self.required = required
else:
self.required = {}
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding=utf-8 | #!/usr/bin/env python
# coding=utf-8
| Python | zaydzuhri_stack_edu_python |
comment M1 x V1 = M2 x V2
comment import re
comment from fractions import fraction
set concentration = string
set startvol = string
set finalconcentration = string
set finalvol = string
function m1
begin
set C = decimal concentration
return C
end function
function v1
begin
set V1 = decimal startvol
return V1
end fu... | # M1 x V1 = M2 x V2
#import re
#from fractions import fraction
concentration = ''
startvol = ''
finalconcentration = ''
finalvol = ''
def m1():
C = float(concentration)
return C
def v1():
V1 = float(startvol)
return V1
def m2():
fC = float(finalconcentration)
return fC
def v2():
V = float(... | Python | zaydzuhri_stack_edu_python |
function _associate_dd_span self ddspan
begin
comment type: (DatadogSpan) -> None
comment get the datadog span context
set _dd_span = ddspan
set _dd_context = context
end function | def _associate_dd_span(self, ddspan):
# type: (DatadogSpan) -> None
# get the datadog span context
self._dd_span = ddspan
self.context._dd_context = ddspan.context | Python | nomic_cornstack_python_v1 |
import sys
import pandas as pd
import numpy as np
import gzip
import matplotlib.pyplot as plt
import math
comment function below derived from:
comment https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula?page=1&tab=votes#tab-top
function distance city stat... | import sys
import pandas as pd
import numpy as np
import gzip
import matplotlib.pyplot as plt
import math
#function below derived from:
#https://stackoverflow.com/questions/27928/calculate-distance-between-two-latitude-longitude-points-haversine-formula?page=1&tab=votes#tab-top
def distance(city, station):
R = 6... | Python | zaydzuhri_stack_edu_python |
function __geo_interface__ self
begin
return call _to_geo na=string null show_bbox=true drop_id=false
end function | def __geo_interface__(self):
return self._to_geo(na="null", show_bbox=True, drop_id=False) | Python | nomic_cornstack_python_v1 |
function wait_seconds self seconds
begin
print string
for seconds_left in range seconds 0 - 1
begin
write stdout string Waiting { seconds_left } seconds... ending=string
sleep 1
end
print string
end function | def wait_seconds(self, seconds):
print("")
for seconds_left in range(seconds, 0, -1):
self.stdout.write(f"Waiting {seconds_left} seconds...", ending="\r")
time.sleep(1)
print("") | Python | nomic_cornstack_python_v1 |
import numpy as np
import networkx as nx
import generation as GEN
set __all__ = list string conductance string cut_size string normalized_cut_size string volume
function eval_cut input_adj input_comm output_file
begin
set G = call edgelist2networkxG input_adj
comment print (min(list(G.nodes())))
set content_comm = call... | import numpy as np
import networkx as nx
import generation as GEN
__all__ = ['conductance', 'cut_size', 'normalized_cut_size',
'volume']
def eval_cut(input_adj,input_comm,output_file):
G = GEN.edgelist2networkxG(input_adj)
#print (min(list(G.nodes())))
content_comm = open(input_comm,'r').read().... | Python | zaydzuhri_stack_edu_python |
function preset_canary_guizhou self
begin
return get pulumi self string preset_canary_guizhou
end function | def preset_canary_guizhou(self) -> Optional['outputs.ErEnvConfPresetCanaryGuizhou']:
return pulumi.get(self, "preset_canary_guizhou") | Python | nomic_cornstack_python_v1 |
string ref Book : Machine Learning for Asset Managers (Ch4.Optimal Clustering) codes for Optimal Clustering Author : Eugene Kim (brownian@kakao.com)
comment Import general libs
import numpy as np
import statsmodels.api as sml
import pandas as pd
comment Import project defined libs
function tValLinR close
begin
string T... | """
ref Book : Machine Learning for Asset Managers (Ch4.Optimal Clustering)
codes for Optimal Clustering
Author : Eugene Kim (brownian@kakao.com)
"""
# Import general libs
import numpy as np
import statsmodels.api as sml
import pandas as pd
# Import project defined libs
def tValLinR(close):
"""
TODO add comm... | Python | zaydzuhri_stack_edu_python |
function from_poscar_string poscar_string transformations=none
begin
string Generates TransformedStructure from a poscar string. Args: poscar_string (str): Input POSCAR string. transformations ([Transformations]): Sequence of transformations to be applied to the input structure.
set p = call from_string poscar_string
i... | def from_poscar_string(poscar_string, transformations=None):
"""
Generates TransformedStructure from a poscar string.
Args:
poscar_string (str): Input POSCAR string.
transformations ([Transformations]): Sequence of transformations
to be applied to the inp... | Python | jtatman_500k |
import glob
import re
import os
import csv
import numpy as np
class YearSummary extends object
begin
function __init__ self year_start year_finish=none
begin
comment Starting year
set year_start = year_start
comment Ending year
if not year_finish
begin
set year_finish = year_start
end
else
begin
set year_finish = year_... | import glob
import re
import os
import csv
import numpy as np
class YearSummary(object):
def __init__(self, year_start, year_finish=None):
# Starting year
self.year_start = year_start
# Ending year
if not year_finish:
self.year_finish = year_start
else: self.year_finish = year_finish
self.top_path =... | Python | zaydzuhri_stack_edu_python |
from segmentoTCP import *
from socket import *
import sys
import random
import threading
import time
import pickle
set timer_running = false
comment remove segmentos reconhecidos do buffer
function update_buffer buffer ack
begin
set aux = 0
for i in range 0 length buffer
begin
if seq_num >= ack
begin
break
end
else
beg... | from segmentoTCP import*
from socket import*
import sys
import random
import threading
import time
import pickle
timer_running = False
#remove segmentos reconhecidos do buffer
def update_buffer(buffer, ack):
aux = 0
for i in range(0, len(buffer)):
if buffer[i].seq_num >= ack:
break
else:
... | Python | zaydzuhri_stack_edu_python |
import LearningStyles
class Student
begin
function __init__ self name age auditory visual kinetic pace social
begin
set name = name
set age = age
set learningStyles = list
append learnignStyles call LearningStyles auditory visual kinetic pace social 0
bestLearningStyle
end function
function addAttributes self attribut... | import LearningStyles
class Student():
def __init__(self, name, age, auditory, visual, kinetic, pace, social):
self.name = name
self.age = age
self.learningStyles = []
self.learnignStyles.append(LearningStyles(auditory, visual, kinetic, pace, social, 0))
self.bestLearningSt... | Python | zaydzuhri_stack_edu_python |
function on_defaultHomeButton_clicked self
begin
call setText helpDefaults at string HomePage
end function | def on_defaultHomeButton_clicked(self):
self.homePageEdit.setText(Preferences.Prefs.helpDefaults["HomePage"]) | Python | nomic_cornstack_python_v1 |
set DEFINE_OneDimModel = true
import argparse
import os
from readLabeledData import readLabeledData
if DEFINE_OneDimModel == true
begin
from trainLstmModelOneDim import trainLstmModel
end
else
begin
from trainLstmModelTwoDim import trainLstmModel
end
function main
begin
set learningRate = list 0.001 0.002 0.003 0.004 0... | ##############################################
DEFINE_OneDimModel = True
##############################################
import argparse
import os
from readLabeledData import readLabeledData
if DEFINE_OneDimModel == True:
from trainLstmModelOneDim import trainLstmModel
else:
from trainLstmModelTwoDim i... | Python | zaydzuhri_stack_edu_python |
string Q1. (a) Outline briefly the various advantages of modular programming [5] A. http://pnagila.blogspot.ie/2012/05/advantages-and-disadvantages-of-modular_15.html (b) As expenses, a travelling sales representative receives 50c for the first 500 kilometres travelled and 75c for any remaining kilometres travelled. Wr... | """
Q1.
(a) Outline briefly the various advantages of modular programming [5]
A. http://pnagila.blogspot.ie/2012/05/advantages-and-disadvantages-of-modular_15.html
(b) As expenses, a travelling sales representative receives 50c for the first 500 kilometres travelled and 75c for
any remaining kilometres... | Python | zaydzuhri_stack_edu_python |
function _save_order_testers order
begin
delete
for tester_name in pop data_dict string tes
begin
call create f_order=order f_id_tester=get objects tester_name=tester_name
end
end function | def _save_order_testers(order):
OrdTes.objects.filter(f_order=order).delete()
for tester_name in data_dict.pop('tes'):
OrdTes.objects.create(
f_order=order,
f_id_tester=Testers.objects.get(tester_name=tester_name)
) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
class SpatioTemporalData extends object
begin
set _metadata = list string added_property
set added_property = 1
decorator property
function _constructor self
begin
return SubclassedDataFrame
end function
function __init__ self data
begin
set df = data
end funct... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class SpatioTemporalData(object):
_metadata = ['added_property']
added_property = 1
@property
def _constructor(self):
return SubclassedDataFrame
def __init__(self, data):
self.df = data
def when(self, location):
dates = self.df[self.df["City"] == location... | Python | zaydzuhri_stack_edu_python |
function formatResult self result
begin
set tuple data sample_names = result
return call format_distance_matrix sample_names data
end function | def formatResult(self, result):
data, sample_names = result
return format_distance_matrix(sample_names, data) | Python | nomic_cornstack_python_v1 |
function test_blocked_reactions model
begin
set ann = annotation
set ann at string data = call find_blocked_reactions model open_exchanges=true
set ann at string metric = length ann at string data / length reactions
set ann at string message = call fill format string There are {} ({:.2%}) blocked reactions in the model... | def test_blocked_reactions(model):
ann = test_blocked_reactions.annotation
ann["data"] = find_blocked_reactions(model, open_exchanges=True)
ann["metric"] = len(ann["data"]) / len(model.reactions)
ann["message"] = wrapper.fill(
"""There are {} ({:.2%}) blocked reactions in
the model: {}""... | Python | nomic_cornstack_python_v1 |
function timeout_initialize self
begin
return call timeout_initialize
end function | def timeout_initialize(self):
return self.__api.timeout_initialize() | Python | nomic_cornstack_python_v1 |
import torch
from gpt2.modeling.embedding import PositionalEmbedding , TokenEmbedding
function test_the_shape_from_positional_embedding_layer
begin
comment Create positional embedding layer.
set layer = call PositionalEmbedding num_embeddings=100 embedding_dim=32
comment Check shape-invariance for grouped batch tensors... | import torch
from gpt2.modeling.embedding import PositionalEmbedding, TokenEmbedding
def test_the_shape_from_positional_embedding_layer():
# Create positional embedding layer.
layer = PositionalEmbedding(num_embeddings=100, embedding_dim=32)
# Check shape-invariance for grouped batch tensors.
input_t... | Python | zaydzuhri_stack_edu_python |
class FLD
begin
string Ferramenta auxiliar destinada a limpeza dos dados scrapeados do site
function unescapeXml s
begin
set s = replace s string < string <
set s = replace s string > string >
set s = replace s string & string &
set s = replace s string string
return s
end function
function unescapeStr... | class FLD:
"""
Ferramenta auxiliar destinada a limpeza dos dados scrapeados do site
"""
def unescapeXml(s):
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace("&", "&")
s = s.replace(" ", " ")
return s
def unescapeStr(s):
s ... | Python | zaydzuhri_stack_edu_python |
function write_list_to_file list_to_write file_path=string students_list.json
begin
try
begin
with open file_path string w as fout
begin
dump list_to_write fout
end
return 1
end
except Exception as file_error
begin
print string EXCEPTION Writing to the file: file_path file_error
exit - 1
end
end function | def write_list_to_file(list_to_write,file_path='students_list.json'):
try:
with open(file_path, 'w') as fout:
json.dump(list_to_write, fout)
return 1
except Exception as file_error:
print("EXCEPTION Writing to the file:",file_path,file_error)
exit(-1) | Python | nomic_cornstack_python_v1 |
async function getreddit self ctx sub n
begin
set main = call getPosts sub integer n
for submis in main
begin
await call send string ``` + string + string Title: + submis at 0 + string ``` + submis at 1 + string
end
end function | async def getreddit(self, ctx, sub, n):
main = getPosts(sub, int(n))
for submis in main:
await ctx.send("```" + '\n' + "Title: " + submis[0] + " ``` " + submis[1] + '\n\n') | Python | nomic_cornstack_python_v1 |
function get_device_type_from_data device_data
begin
try
begin
return call DeviceTypes device_data at string type
end
except ValueError
begin
error string Unknown device type: %s device_data at string type
return UNKNOWN
end
end function | def get_device_type_from_data(device_data: dict[str, Any]) -> DeviceTypes:
try:
return DeviceTypes(device_data["type"])
except ValueError:
LOGGER.error("Unknown device type: %s", device_data["type"])
return DeviceTypes.UNKNOWN | Python | nomic_cornstack_python_v1 |
function test_fma_nan_param_nanarray_ninfnum_ninfarray_okarray_b_244 self
begin
comment The expected results.
set expected = list comprehension x * y + z for tuple x y z in zip nanarrayx repeat ninfnumy ninfarrayz
comment Exceptions are turned off so we can use the results to test for correct values.
call fma nanarrayx... | def test_fma_nan_param_nanarray_ninfnum_ninfarray_okarray_b_244(self):
# The expected results.
expected = [(x * y + z) for x,y,z in zip(self.nanarrayx, itertools.repeat(self.ninfnumy), self.ninfarrayz)]
# Exceptions are turned off so we can use the results to test for correct values.
arrayfunc.fma(self.nanarra... | Python | nomic_cornstack_python_v1 |
comment 실행문만 있는 모듈
set width = 3
set height = 5
print string 가로 width string 세로 height string 인 삼각형의 넓이: 3 * 5 * 1 / 2
print string 가로 width string 세로 height string 인 사각형의 넓이: 3 * 5 | #실행문만 있는 모듈
width = 3
height = 5
print("가로",width,"세로",height,"인 삼각형의 넓이: ",3*5*1/2)
print("가로",width,"세로",height,"인 사각형의 넓이: ",3*5)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[2]:
import torch
from torch import nn
from torch.utils.data import Dataset
import pandas as pd
from pytorch_model_summary import summary
import pickle
from torch.utils.data import DataLoader
from q81 import ID2List
from q81 import read_csv
class my_RNN exten... | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import torch
from torch import nn
from torch.utils.data import Dataset
import pandas as pd
from pytorch_model_summary import summary
import pickle
from torch.utils.data import DataLoader
from q81 import ID2List
from q81 import read_csv
class my_RNN(nn.Mod... | Python | zaydzuhri_stack_edu_python |
comment Flask hello world!
from flask import Flask
comment create app object
set app = call Flask __name__
decorator call route string /
decorator call route string /hello
comment error handling
comment define the view using a function to return a string
comment use decorator to link to an url
comment define the view u... | # Flask hello world!
from flask import Flask
# create app object
app = Flask(__name__)
# error handling
# define the view using a function to return a string
# use decorator to link to an url
@app.route("/")
@app.route("/hello")
# define the view using a function to return a string
def hello_world():
return "He... | Python | zaydzuhri_stack_edu_python |
import requests
from tabulate import tabulate
import json
import urllib.parse
from pprint import pprint
from pb.playfield_service import PlayfieldService
from pb.table import Table
class PopbumperCommand
begin
function __init__ self host
begin
set playfield = call PlayfieldService host
end function
decorator staticmeth... | import requests
from tabulate import tabulate
import json
import urllib.parse
from pprint import pprint
from pb.playfield_service import PlayfieldService
from pb.table import Table
class PopbumperCommand:
def __init__(self, host):
self.playfield = PlayfieldService(host)
@staticmethod
def action_... | Python | zaydzuhri_stack_edu_python |
import collections
from typing import Tuple , List
function reverse_words_in_char_list chars
begin
call _reverse chars
set tuple word_start word_length = tuple 0 0
for tuple i char in enumerate chars
begin
if char == string
begin
call _reverse chars word_start word_length
set word_length = 0
end
else
begin
set word_st... | import collections
from typing import Tuple, List
def reverse_words_in_char_list(chars: List[str]) -> None:
_reverse(chars)
word_start, word_length = 0,0
for i, char in enumerate(chars):
if char == ' ':
_reverse(chars, word_start, word_length)
word_length = 0
else:
... | Python | zaydzuhri_stack_edu_python |
set tekst = string Oto jest jakiś tekst
print tekst at 4
comment TO NIE ZADZIAŁA! obiekt `str` nie jest modyfikowalny
set tekst at 4 = string J
print tekst | tekst = 'Oto jest jakiś tekst'
print(tekst[4])
tekst[4] = 'J' # TO NIE ZADZIAŁA! obiekt `str` nie jest modyfikowalny
print(tekst)
| Python | zaydzuhri_stack_edu_python |
function match coord center R
begin
from kdcount import KDTree
set pos = call radec2pos center at 0 center at 1
set tree = call KDTree pos
if call isscalar R
begin
comment print('This is the value of R =%g'%(R))
set R = center at 0 * 0 + R
end
set R = 2 * sin call radians R * 0.5
set pos = call radec2pos coord at 0 coo... | def match(coord, center, R):
from kdcount import KDTree
pos = radec2pos(center[0], center[1])
tree = KDTree(pos)
if numpy.isscalar(R):
#print('This is the value of R =%g'%(R))
R = center[0]*0 + R
R = 2 * numpy.sin(numpy.radians(R) * 0.5)
pos = radec2pos(coord[0], coord[1... | Python | nomic_cornstack_python_v1 |
function calc_delay_avg self data
begin
info string Calculating average delay...
function avg x
begin
if x at string train_count < 1 or call isnan x at string train_count
begin
error format string Errornous train count ({}) x at string train_count
return 0
end
else
begin
return x at string delay / x at string train_cou... | def calc_delay_avg(self, data):
logging.info('Calculating average delay...')
def avg(x):
if x['train_count'] < 1 or np.isnan(x['train_count']):
logging.error('Errornous train count ({})'.format(x['train_count']))
return 0
else:
ret... | Python | nomic_cornstack_python_v1 |
function save self implementation_context=none
begin
raise call NotImplementedError
end function | def save(self, implementation_context=None):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
async function help ctx args
begin
comment `help` can have 0 or more arguments, so this needs to check
comment the number of args to decide what to display.
if length args == 0
begin
await call show_all_commands ctx
return
end
set command = args at 0
if command not in COMMANDS
begin
await call say string Sorry, but I d... | async def help(ctx, args):
# `help` can have 0 or more arguments, so this needs to check
# the number of args to decide what to display.
if len(args) == 0:
await show_all_commands(ctx)
return
command = args[0]
if command not in COMMANDS:
await client.say(
f"Sorry... | Python | nomic_cornstack_python_v1 |
function SetDomainSigma self *args
begin
return call itkBilateralImageFilterIUS2IUS2_SetDomainSigma self *args
end function | def SetDomainSigma(self, *args):
return _itkBilateralImageFilterPython.itkBilateralImageFilterIUS2IUS2_SetDomainSigma(self, *args) | Python | nomic_cornstack_python_v1 |
comment EJERCICIO 6
print string Escriu dos números
set a = integer input
set b = integer input
set suma = a + b
set resta = a - b
set multi = a * b
set divi = a / b
print string La suma dels dos números és: suma string , la resta és: resta string , la multiplicació és: multi string i finalment la divisió és: divi stri... | #EJERCICIO 6
print("Escriu dos números")
a=int(input())
b=int(input())
suma=a+b
resta=a-b
multi=a*b
divi=a/b
print("La suma dels dos números és:",suma,", la resta és:",resta,", la multiplicació és:",multi," i finalment la divisió és:",divi,".") | Python | zaydzuhri_stack_edu_python |
function get self revision
begin
set build = call fetch_build_for_revision revision
if not build
begin
return call respond status=404
end
set parent = get args string parent
set build_ids = list comprehension id for original in original
set query = call order_by call asc
if parent
begin
set query = filter starts with f... | def get(self, revision: Revision):
build = fetch_build_for_revision(revision)
if not build:
return self.respond(status=404)
parent = request.args.get("parent")
build_ids = [original.id for original in build.original]
query = FileCoverage.query.filter(
F... | Python | nomic_cornstack_python_v1 |
import plotly.graph_objects as go
import plotly.offline as pyo
import pandas as pd
set df = read csv string Data/2018WinterOlympics.csv
comment data = [go.Bar(x=df['NOC'], y=df['Total'])]
set trace1 = bar x=df at string NOC y=df at string Gold name=string Gold marker=dict string color string #FFD700
set trace2 = bar x=... | import plotly.graph_objects as go
import plotly.offline as pyo
import pandas as pd
df = pd.read_csv('Data/2018WinterOlympics.csv')
# data = [go.Bar(x=df['NOC'], y=df['Total'])]
trace1 = go.Bar(x=df['NOC'], y=df['Gold'], name='Gold', marker={'color':'#FFD700'})
trace2 = go.Bar(x=df['NOC'], y=df['Silver'], name='Silver'... | Python | zaydzuhri_stack_edu_python |
import electrostatics
from electrostatics import *
string Ejemplo 2.11 La densidad de flujo magnetico 𝔹 alrededor de un alambre muy largo que transporta una corriente es circunferencial e inversamente proporcional a la distancia del alambre. Calcule 𝛁·𝔹
print string =====================
string Situamos el alambre e... | import electrostatics
from electrostatics import *
'''
Ejemplo 2.11
La densidad de flujo magnetico 𝔹 alrededor
de un alambre muy largo que transporta
una corriente es circunferencial
e inversamente proporcional a
la distancia del alambre.
Calcule 𝛁·𝔹
'''
print("=====================")
'''Situamos el alambre en ... | Python | zaydzuhri_stack_edu_python |
function deactivate self request queryset
begin
set selected_cats = filter pk__in=list comprehension integer x for x in call getlist string _selected_action
for item in selected_cats
begin
if active
begin
set active = false
save
update all active=false
end
end
end function | def deactivate(self, request, queryset):
selected_cats = Category.objects.filter(
pk__in=[int(x) for x in request.POST.getlist('_selected_action')])
for item in selected_cats:
if item.active:
item.active = False
item.save()
... | Python | nomic_cornstack_python_v1 |
function init_params self
begin
set _elite_size = integer round elite_proportion * population_size
set _mutant_size = integer round mutant_proportion * population_size
set _elapsed_time = 0.0
set _last_perf_count = performance counter
call _init_pool
set current_population = list
call init_params
end function | def init_params(self):
self._elite_size = int(round(self.elite_proportion * self.population_size))
self._mutant_size = int(round(self.mutant_proportion * self.population_size))
self._elapsed_time = 0.0
self._last_perf_count = time.perf_counter()
self._init_pool()
self.cur... | Python | nomic_cornstack_python_v1 |
function get_saved_model_path self saved_model_dir
begin
set models_data = call load_models_data saved_model_dir
if models_data is none
begin
return none
end
if stock_code not in models_data at string models
begin
return none
end
set model_type_hash = call get_model_type_hash
if model_type_hash not in models_data at st... | def get_saved_model_path(self, saved_model_dir):
models_data = self.load_models_data(saved_model_dir)
if models_data is None:
return None
if self.stock_code not in models_data["models"]:
return None
model_type_hash = self.get_model_type_hash()
if model... | Python | nomic_cornstack_python_v1 |
import requests
import json
import random
class SocBot
begin
set number_of_users = 0
set max_post_per_user = 0
set max_likes_per_user = 0
set user_tokens = list
function __init__ self path
begin
with open path string r as f
begin
set data = read lines f
end
set number_of_users = integer data at 0
set max_post_per_user... | import requests
import json
import random
class SocBot():
number_of_users = 0
max_post_per_user = 0
max_likes_per_user = 0
user_tokens = []
def __init__(self, path):
with open(path, 'r') as f:
data = f.readlines()
self.number_of_users = int(data[0])
self.max_po... | Python | zaydzuhri_stack_edu_python |
from app import db
from constants import CONSTANTS
from sqlalchemy_utils import UUIDType
class ShoppingList extends Model
begin
set __tablename__ = string shopping_list
set user_id = call Column call UUIDType call ForeignKey string user.user_id nullable=false primary_key=true
set item_name = call Column call String CON... | from app import db
from constants import CONSTANTS
from sqlalchemy_utils import UUIDType
class ShoppingList(db.Model):
__tablename__ = 'shopping_list'
user_id = db.Column(
UUIDType(),
db.ForeignKey('user.user_id'),
nullable=False,
primary_key=True
)
item_name = db.Colum... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed May 19 20:49:01 2021 @author: susan333
import sys
from typing import Tuple
import pygame
function check_events ship
begin
for event in get event
begin
if type == QUIT
begin
exit
end
else
if type == KEYDOWN
begin
if key == K_RIGHT
begin
set moving_right = true
end
if k... | # -*- coding: utf-8 -*-
"""
Created on Wed May 19 20:49:01 2021
@author: susan333
"""
import sys
from typing import Tuple
import pygame
def check_events(ship):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.t... | Python | zaydzuhri_stack_edu_python |
comment Para un número N imprimir su tabla de multiplicar.
from random import randint
set n = random integer 1 13
for i in range 1 13
begin
print string { i } * { n } = { i * n }
end | # Para un número N imprimir su tabla de multiplicar.
from random import randint
n = randint(1,13)
for i in range(1,13):
print(f'{i} * {n} = {i*n}') | Python | zaydzuhri_stack_edu_python |
import cv2
from enum import Enum
class CameraType extends Enum
begin
set WEB_CAM = 1
set PI_CAM = 2
end class
class Camera
begin
function __init__ self mode
begin
set mode = mode
comment self.is_camera_open = False
if mode == WEB_CAM
begin
print string [Camera] Initializing camera in mode: WEB_CAM
comment Initialize We... | import cv2
from enum import Enum
class CameraType(Enum):
WEB_CAM = 1
PI_CAM = 2
class Camera:
def __init__(self, mode: CameraType):
self.mode = mode
# self.is_camera_open = False
if mode == CameraType.WEB_CAM:
print("[Camera] Initializing camera in mode: WEB_CAM")
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.