code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Python: Sum string lengths
set length = sum generator expression length s for s in strings | # Python: Sum string lengths
length = sum(len(s) for s in strings)
| Python | zaydzuhri_stack_edu_python |
comment 3. Создайте класс который будет хранить параметры для подключения к физическому юниту(например switch).
comment В своем списке атрибутов он должен иметь минимальный набор (unit_name, mac_address, ip_address, login, password).
comment Вы должны описать каждый из этих атрибутов в виде гетеров и сеттеров(@property... | # 3. Создайте класс который будет хранить параметры для подключения к физическому юниту(например switch).
# В своем списке атрибутов он должен иметь минимальный набор (unit_name, mac_address, ip_address, login, password).
# Вы должны описать каждый из этих атрибутов в виде гетеров и сеттеров(@property).
# У вас долж... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import random
import math
function pi
begin
set count = 0
for i in range 10000
begin
set x = random
set y = random
if x * x + y * y < 1
begin
set count = count + 1
end
end
return count * 4 / 10000
end function | # -*- coding: utf-8 -*-
import random
import math
def pi():
count = 0
for i in range(10000):
x = random.random()
y = random.random()
if (x*x + y*y)<1:
count += 1
return count * 4/ 10000
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sat Nov 24 15:50:58 2018 @author: anikkengjeruldsen
comment %%
comment Exercise 1 non-connected nodes ina graph
set graph = dict string a list string b string c ; string b list string d ; string c list string d ; string d list ; string e lis... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 24 15:50:58 2018
@author: anikkengjeruldsen
"""
#%%
# Exercise 1 non-connected nodes ina graph
graph={
"a":["b","c"],
"b":["d"],
"c":["d"],
"d":[],
"e":[]
}
def non_connected(g):
non_connected_nodes=[]
outgoin... | Python | zaydzuhri_stack_edu_python |
class Movie
begin
function __init__ self movie_id movie_name ticket_cost
begin
set movie_id = movie_id
set movie_name = movie_name
set ticket_cost = ticket_cost
end function
function pricecategory self
begin
set cat = list string General string Silver string Gold string Platinum
if ticket_cost in range 0 150
begin
set ... | class Movie:
def __init__(self,movie_id,movie_name,ticket_cost):
self.movie_id=movie_id
self.movie_name=movie_name
self.ticket_cost=ticket_cost
def pricecategory(self):
cat=["General","Silver","Gold","Platinum"]
if self.ticket_cost in range(0,150):
sel... | Python | zaydzuhri_stack_edu_python |
for i in d1
begin
print i string = d1 at i
end | for i in d1:
print(i,"=",d1[i])
| Python | zaydzuhri_stack_edu_python |
comment defining a function read
function read
begin
print string ---------------------------------------------------------------------
print string Movie ID Movie-Name Price Quantity
print string ---------------------------------------------------------------------
comment to read the text file named movies
set file =... | def read(): #defining a function read
print("---------------------------------------------------------------------")
print("Movie ID Movie-Name Price Quantity")
print("---------------------------------------------------------------------")
#to read the text file named movies
... | Python | zaydzuhri_stack_edu_python |
function GetJulianDate yr mnth dy tme
begin
set cal = string g
set t = tme / 24
set dy = dy + t
if mnth == 1 or mnth == 2
begin
set mnth = mnth + 12
set yr = yr - 1
end
if yr <= 1582
begin
set cal = string j
if yr == 1582 and mnth >= 10
begin
set cal = string g
end
end
set A = 0
set B = 0
if cal == string g
begin
set A... | def GetJulianDate(yr, mnth, dy, tme):
cal = 'g'
t = tme / 24
dy = dy + t
if mnth == 1 or mnth ==2:
mnth += 12
yr = yr - 1
if yr <= 1582:
cal = 'j'
if yr == 1582 and mnth >= 10:
cal = 'g'
A = 0
B = 0
if cal == 'g':... | Python | zaydzuhri_stack_edu_python |
function getProfile self profile
begin
for network in networks
begin
if call getProfileName == profile
begin
return network
end
end
for else
begin
raise exception string Network with profile name "%s" not found % profile
end
end function | def getProfile(self, profile):
for network in self.networks:
if network.getProfileName() == profile:
return network
else:
raise Exception('Network with profile name "%s" not found' % profile) | Python | nomic_cornstack_python_v1 |
class Solver
begin
decorator staticmethod
function solve kakuro solutions_count
begin
for i in range 10
begin
for block in blocks
begin
set partitions = call get_block_partitions block
if length partitions == 1
begin
set partitions = partitions at 0
for cell in value_cells
begin
if length values == 0
begin
call assign ... | class Solver:
@staticmethod
def solve(kakuro, solutions_count):
for i in range(10):
for block in kakuro.blocks:
partitions = Solver.get_block_partitions(block)
if len(partitions) == 1:
partitions = partitions[0]
for cell... | Python | zaydzuhri_stack_edu_python |
import random , pygame , sys
from pygame.locals import *
comment constants
set FPS = 30
set WINDOWWIDTH = 640
set WINDOWHEIGHT = 480
set LANES = 10
set LANEHEIGHT = WINDOWHEIGHT / LANES
set MISSILESPEED = 40
set FIRINGINTEVAL = 5
set MISSILERAD = integer LANEHEIGHT / 2
comment colors
set WHITE = tuple 255 255 255
set B... | import random, pygame, sys
from pygame.locals import *
#constants
FPS = 30
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
LANES = 10
LANEHEIGHT = WINDOWHEIGHT / LANES
MISSILESPEED = 40
FIRINGINTEVAL = 5
MISSILERAD = int(LANEHEIGHT / 2)
#colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BGCOLOR = WHITE
SH... | Python | zaydzuhri_stack_edu_python |
comment Email address program
set n = integer input string Enter the number of email address :
set flag = 0
for i in range 0 n
begin
set email = input string Enter the emaill address :
set b = split email string @
set d = split b at 1 string .
if d at 0 == string prof
begin
set flag = 1
end
end
if flag == 0
begin
print... | # Email address program
n=int(input("Enter the number of email address :"))
flag=0
for i in range(0,n):
email=input("Enter the emaill address :")
b=email.split('@')
d=b[1].split('.')
if d[0]=="prof":
flag=1
if flag==0:
print("All students:")
else:
print("Professor detcted :")
| Python | zaydzuhri_stack_edu_python |
import datetime
class Person
begin
function __init__ self name date_of_birth gender
begin
set name = name
set date_of_birth = date_of_birth
set gender = gender
set _id = call generate_id
set _address = none
set _phone_number = none
end function
decorator property
function id self
begin
return _id
end function
decorator... | import datetime
class Person:
def __init__(self, name, date_of_birth, gender):
self.name = name
self.date_of_birth = date_of_birth
self.gender = gender
self._id = self.generate_id()
self._address = None
self._phone_number = None
@property
def id(self):
... | Python | greatdarklord_python_dataset |
comment !/usr/bin python3
comment -*- coding: utf-8 -*-
comment @Time : 19-1-17 下午5:08
comment @Author : 林利芳
comment @File : word_embedding.py
import numpy as np
from config.config import WORD2VEC_DATA
class Vocab extends object
begin
function __init__ self
begin
set word2vec = list
set word2idx = dict string <PAD> 0 ... | #!/usr/bin python3
# -*- coding: utf-8 -*-
# @Time : 19-1-17 下午5:08
# @Author : 林利芳
# @File : word_embedding.py
import numpy as np
from config.config import WORD2VEC_DATA
class Vocab(object):
def __init__(self):
self.word2vec = []
self.word2idx = {'<PAD>': 0, '<UNK>': 1}
self.max_len = 0
def add_wor... | Python | zaydzuhri_stack_edu_python |
function comment_count self
begin
return count _comments
end function | def comment_count(self):
return self._comments.count() | Python | nomic_cornstack_python_v1 |
function get_911_category_training feature_path category_911
begin
set tuple features output = call get_training feature_path
set output at where output == category_911 = 1
set output at where output != category_911 = 0
return tuple features output
end function | def get_911_category_training(feature_path, category_911):
features, output = get_training(feature_path)
output[np.where(output == category_911)] = 1
output[np.where(output != category_911)] = 0
return features, output | Python | nomic_cornstack_python_v1 |
comment Cloning or Copying a List ########################
comment 1st Approach
set a = list
set n = integer input string Enter the Number of Elements:
for i in range 0 n
begin
set element = integer input
append a element
end
set b = a at slice : :
print *b
comment 2nd Approach
set a = list
set n = integer input s... | ################################## Cloning or Copying a List ########################
############### 1st Approach
a=[]
n=int(input("Enter the Number of Elements: "))
for i in range(0,n):
element=int(input())
a.append(element)
b=a[:]
print(*b)
############### 2nd Approach
a=[]
n=int(input("Enter the Numb... | Python | zaydzuhri_stack_edu_python |
from challenges import ransom_note
from expects import *
with call description string ransom_note
begin
with call context string when the magazine contains all the required words for the note
begin
with call it string is true
begin
to call expect call ransom_note list string foo string Bar string baz list string baz st... | from challenges import ransom_note
from expects import *
with description('ransom_note'):
with context('when the magazine contains all the required words for the note'):
with it('is true'):
expect(ransom_note.ransom_note(['foo', 'Bar', 'baz'], ['baz', 'Bar'])).to(be_true)
with context('when... | Python | zaydzuhri_stack_edu_python |
function test_logged_in_admin self
begin
comment self.factory = RequestFactory()
comment request = self.factory.get('/map')
comment request.user = EmailUser.objects.get(email=self.adminUN)
comment adBooking = AdmissionsBooking.objects.all().first()
comment lines = admissions_price_or_lineitems(request, adBooking)
comme... | def test_logged_in_admin(self):
# self.factory = RequestFactory()
# request = self.factory.get('/map')
# request.user = EmailUser.objects.get(email=self.adminUN)
# adBooking = AdmissionsBooking.objects.all().first()
# lines = admissions_price_or_lineitems(request, adBooking)
... | Python | nomic_cornstack_python_v1 |
import RPi.GPIO as GPIO
import time
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
call setmode BCM
comment Button to GPIO23
setup GPIO 23 IN pull_up_down=PUD_UP
comment LED to GPIO24
setup GPIO 24 OUT
comment Button to GPIO23
setup GPIO 25 IN pull_up_down=PUD_UP
commen... | import RPi.GPIO as GPIO
import time
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)#Button to GPIO23
GPIO.setup(24, GPIO.OUT) #LED to GPIO24
GPIO.setup(25, GPIO.IN, pull_up_down=GPIO.... | Python | zaydzuhri_stack_edu_python |
function ensure_not_ipa_client module
begin
comment Check if IPA client is already configured
if not call is_client_configured
begin
comment Nothing to do
call exit_json changed=false
end
comment Client is configured
comment If in check mode, do nothing but return changed=True
if check_mode
begin
call exit_json changed... | def ensure_not_ipa_client(module):
# Check if IPA client is already configured
if not is_client_configured():
# Nothing to do
module.exit_json(changed=False)
# Client is configured
# If in check mode, do nothing but return changed=True
if module.check_mode:
module.exit_json... | Python | nomic_cornstack_python_v1 |
function removed self dbObj
begin
comment Remove fully from database
for delta in get dbObj string deltas search=list list string state string removed
begin
print string Remove { delta at string id } delta
delete string deltas list list string id delta at string id
end
end function | def removed(self, dbObj):
# Remove fully from database
for delta in dbObj.get('deltas', search=[['state', 'removed']]):
print(f"Remove {delta['id']} delta")
dbObj.delete('deltas', [['id', delta['id']]]) | Python | nomic_cornstack_python_v1 |
import tkinter as tk
import datetime
class TelaPrincipal
begin
function __init__ self master
begin
set nossaTela = master
set lblRelogio = call Label nossaTela font=tuple string Arial 40 fg=string Black
call pack pady=30 padx=30
call alteracao
end function
function alteracao self
begin
set now = now
set lblRelogio at s... | import tkinter as tk
import datetime
class TelaPrincipal:
def __init__(self, master):
self.nossaTela = master
self.lblRelogio = tk.Label(
self.nossaTela, font=('Arial', 40), fg='Black')
self.lblRelogio.pack(pady=30, padx=30)
self.alteracao()
def alteracao(self):
... | Python | zaydzuhri_stack_edu_python |
from pathlib import Path
from enums import ProgrammingLanguage
from file import File
class Project
begin
function __init__ self id name path
begin
string Constructor Args: id (int): id of the project name (str): name of the project path (str): path to the project
set id = id
set name = name
set path = path
set _files =... | from pathlib import Path
from ..enums import ProgrammingLanguage
from file import File
class Project():
def __init__(self, id, name, path):
"""Constructor
Args:
id (int): id of the project
name (str): name of the project
path (str): path to the project
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
function x_pilot_and_noise_pilot N Ns Nr SNR modulation_mode
begin
string output_matrix = input_matrix * transmit_matrix :param input_matrix: N :param output_matrix: Nr :return: x_pilot noise_pilot
comment x_pilot
set list _ _ _ signal = call signal_generator N Ns modulation_mode string power_normali... | import numpy as np
def x_pilot_and_noise_pilot(N, Ns, Nr, SNR, modulation_mode):
"""
output_matrix = input_matrix * transmit_matrix
:param input_matrix: N
:param output_matrix: Nr
:return: x_pilot
noise_pilot
"""
# x_pilot
[_, _, _, signal] = signal_generator(N... | Python | zaydzuhri_stack_edu_python |
function update self
begin
set __step = __step + 1
comment LINK UPDATE ----- count_step
comment self._links[pos] = (LINK_TYPE_NAMES["OUT"], id_, id_pos)
comment Check links IN
set in_id = LINK_TYPE_NAMES at string IN
for tuple pos data in call viewitems
begin
set tuple type_ id_ id_pos = data
if type_ == in_id
begin
in... | def update(self):
self.__step += 1
# LINK UPDATE ----- count_step
#self._links[pos] = (LINK_TYPE_NAMES["OUT"], id_, id_pos)
# Check links IN
in_id = LINK_TYPE_NAMES["IN"]
for pos, data in self._links.viewitems():
type_, id_, id_pos = data
if type_... | Python | nomic_cornstack_python_v1 |
import clr
import Autodesk.Revit.DB as DB
set doc = Document
set uidoc = ActiveUIDocument
comment Accesses the ID# associated with the built-in paramater "System Classification"
comment See RevitApiDocs: BuiltInParameter Enumeration
set sysClass_id = call ElementId RBS_SYSTEM_CLASSIFICATION_PARAM
comment The filter nee... | import clr
import Autodesk.Revit.DB as DB
doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument
# Accesses the ID# associated with the built-in paramater "System Classification"
# See RevitApiDocs: BuiltInParameter Enumeration
sysClass_id = DB.ElementId(DB.BuiltInParameter.RBS_SYSTEM_CLASSIFIC... | Python | zaydzuhri_stack_edu_python |
if fizz
begin
print string Fizz
end
else
begin
print numero
end | if (fizz):
print("Fizz")
else:
print(numero) | Python | zaydzuhri_stack_edu_python |
function create_query_from_post user_id post
begin
set start = string parse time post at string time_start string %m/%d/%Y
set end = string parse time post at string time_end string %m/%d/%Y
comment hardcoded product, user id. Will be changed.
set query = query query_start=now query_end=now user_id=user_id query_type=p... | def create_query_from_post(user_id, post):
start = datetime.strptime(post['time_start'], '%m/%d/%Y')
end = datetime.strptime(post['time_end'], '%m/%d/%Y')
# hardcoded product, user id. Will be changed.
query = Query(query_start=datetime.now(), query_end=datetime.now(), user_id=user_id,
... | Python | nomic_cornstack_python_v1 |
from Grid import Grid
from Scheduler import RandomActivation
from Agent import Agent
class Model
begin
string Model class for the Schelling segregation model.
function __init__ self width height density similarity
begin
set width = width
set height = height
comment so agent moi loai, chua ra 20% empty cell
set num_agen... | from Grid import Grid
from Scheduler import RandomActivation
from Agent import Agent
class Model:
'''
Model class for the Schelling segregation model.
'''
def __init__(self, width, height, density, similarity):
self.width = width
self.height = height
num_agent = (int)(height * ... | Python | zaydzuhri_stack_edu_python |
from pylab import *
from random import randint
set brikke = 0
set fengsel = 0
set runder = 0
set teller = 0
set B = list
set LB = list
set Ro = list
set O = list
set R = list
set Gu = list
set Gr = list
set Bl = list
set brunF = 0
set lyseblaaF = 0
set rosaF = 0
set oransjF = 0
set rodF = 0
set gulF = 0
set gro... | from pylab import *
from random import randint
brikke = 0
fengsel = 0
runder = 0
teller = 0
B = []
LB = []
Ro = []
O = []
R = []
Gu = []
Gr = []
Bl = []
brunF = 0
lyseblaaF = 0
rosaF = 0
oransjF = 0
rodF = 0
gulF = 0
gronnF = 0
blaaF = 0
brun1F = 0
brun2F = 0
lyseblaa1F = 0
lyseblaa2F = 0
lyseblaa3F = 0
rosa1F = 0... | Python | zaydzuhri_stack_edu_python |
function loadUiType uiFile
begin
set parsed = parse xml uiFile
set widget_class = get find parsed string widget string class
set form_class = text
with open uiFile string r as f
begin
set o = call StringIO
set frame = dict
call compileUi f o indent=0
set pyc = compile call getvalue string <string> string exec
end
end ... | def loadUiType(uiFile):
parsed = xml.parse(uiFile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(uiFile, 'r') as f:
o = StringIO()
frame = {}
uic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec... | Python | nomic_cornstack_python_v1 |
function clear_snippets self priority triggers
begin
if not triggers
begin
if _clear_priority is none or priority > _clear_priority
begin
set _clear_priority = priority
end
end
else
begin
for trigger in triggers
begin
if trigger not in _cleared or priority > _cleared at trigger
begin
set _cleared at trigger = priority
... | def clear_snippets(self, priority, triggers):
if not triggers:
if self._clear_priority is None or priority > self._clear_priority:
self._clear_priority = priority
else:
for trigger in triggers:
if (trigger not in self._cleared or
... | Python | nomic_cornstack_python_v1 |
function view_task request task_id
begin
set task = call get_object_or_404 Task pk=task_id
comment Ensure user has permission to view item.
comment Get the users this task belongs to.
comment Admins can edit all tasks.
if assigned_to == user or is_staff
begin
set auth_ok = true
if POST
begin
set form = call EditTaskFor... | def view_task(request, task_id):
task = get_object_or_404(Task, pk=task_id)
# Ensure user has permission to view item.
# Get the users this task belongs to.
# Admins can edit all tasks.
if task.assigned_to == request.user or request.user.is_staff:
auth_ok = True
if request.POST:
... | Python | nomic_cornstack_python_v1 |
function forward self
begin
return call forward layer
end function | def forward(self) -> list:
return self.net.forward(self.layer) | Python | nomic_cornstack_python_v1 |
function test_error_fitted
begin
set havok = call HAVOK
with raises RuntimeError
begin
set _ = linear_embeddings
end
with raises RuntimeError
begin
set _ = forcing_input
end
with raises RuntimeError
begin
set _ = A
end
with raises RuntimeError
begin
set _ = B
end
with raises RuntimeError
begin
set _ = r
end
end functio... | def test_error_fitted():
havok = HAVOK()
with raises(RuntimeError):
_ = havok.linear_embeddings
with raises(RuntimeError):
_ = havok.forcing_input
with raises(RuntimeError):
_ = havok.A
with raises(RuntimeError):
_ = havok.B
with raises(RuntimeError):
_ = ... | Python | nomic_cornstack_python_v1 |
function display_speaker self speaker title visual
begin
print string = * 70 + string + title + string :
set goals = list comprehension format string r_{}(f_{}(s),a) r f for r in list string s string a string sa for f in list string e string a
if visual
begin
set
set tuple f axes = call subplots length goals length af... | def display_speaker(self, speaker, title, visual):
print("="*70 + "\n" + title + ": ")
goals = ["r_{}(f_{}(s),a)".format(r,f) for r in ['s','a','sa'] for f in ['e','a']]
if visual:
sns.set()
f, axes = plt.subplots(len(goals), len(self.affects), figsize=(6,12))
... | Python | nomic_cornstack_python_v1 |
comment This file reads in the cleaned template data directory and creates
comment csv file with topic and png pairs.
import os
set topic_pngs_filename = string topic_pngs.csv
set root_dir = string ../templates_data/full
print string Reading root_dir
with open topic_pngs_filename string w as outfile
begin
for tuple dir... | # This file reads in the cleaned template data directory and creates
# csv file with topic and png pairs.
import os
topic_pngs_filename = 'topic_pngs.csv'
root_dir = '../templates_data/full'
print("Reading", root_dir)
with open(topic_pngs_filename, 'w') as outfile:
for dir_name, subdir_list, file_list in os.walk(... | Python | zaydzuhri_stack_edu_python |
function _set_credentials
begin
comment Override credentials here if necessary
if user == string ubuntu
begin
set key_filename = list expand user path string ~/.ssh/ubuntu-id_dsa
end
set abort_on_prompts = true
set disable_known_hosts = true
set use_shell = false
end function | def _set_credentials():
# Override credentials here if necessary
if env.user == 'ubuntu':
env.key_filename = [
os.path.expanduser('~/.ssh/ubuntu-id_dsa')]
env.abort_on_prompts = True
env.disable_known_hosts = True
env.use_shell = False | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function generateParenthesis self n
begin
string :type n: int :rtype: List[str]
set ans = list
set temp = list
function dfs t l
begin
if t == 0
begin
append ans join string temp
end
else
begin
if l > 0
begin
append temp string (
call dfs t - 1 l - 1
pop temp
end
if t - l > l
begin... | class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
ans = []
temp = []
def dfs(t, l):
if t == 0:
ans.append(''.join(temp))
else:
if l > 0:
... | Python | zaydzuhri_stack_edu_python |
function get_items self assessment_id
begin
string Gets the items in sequence from an assessment. arg: assessment_id (osid.id.Id): the ``Id`` of the ``Assessment`` return: (osid.assessment.ItemList) - list of items raise: NotFound - ``assessmentid`` not found raise: NullArgument - ``assessment_id`` is ``null`` raise: O... | def get_items(self, assessment_id):
"""Gets the items in sequence from an assessment.
arg: assessment_id (osid.id.Id): the ``Id`` of the
``Assessment``
return: (osid.assessment.ItemList) - list of items
raise: NotFound - ``assessmentid`` not found
raise: Nul... | Python | jtatman_500k |
function evaluate policies env reward_stat=none n_episodes=20 seed=none
begin
set reward_stat = reward_stat or sum
set rng = random seed
for episode in range n_episodes
begin
set episode_policies = list comprehension clone policy for policy in policies
set episode_env = deep copy env
call reset seed=random integer 0 2 ... | def evaluate(
policies: list[bandit.base.Policy],
env: gym.Env,
reward_stat: stats.base.Univariate | None = None,
n_episodes: int = 20,
seed: int | None = None,
):
reward_stat = reward_stat or stats.Sum()
rng = random.Random(seed)
for episode in range(n_episodes):
episode_polic... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import socket
import sys
from datetime import datetime
comment Ask for input
set target = input string input ip address or remote hosts:
set targetIP = call gethostbyname target
comment header banner
print string = * 60
print string Please wait, scanning remote host targetIP
print string = ... | #!/usr/bin/env python
import socket
import sys
from datetime import datetime
# Ask for input
target = input("input ip address or remote hosts: ")
targetIP = socket.gethostbyname(target)
# header banner
print ("=" * 60)
print ("Please wait, scanning remote host", targetIP)
print ("=" * 60)
# Check the time when scan... | Python | zaydzuhri_stack_edu_python |
function min_res *args
begin
set min_result = min *args
return min_result
end function
function max_res *args
begin
set max_result = max *args
return max_result
end function
function sum_res *args
begin
set sum_result = sum *args
return sum_result
end function
set n = list comprehension integer x for x in split input
p... | def min_res(*args):
min_result = min(*args)
return min_result
def max_res(*args):
max_result = max(*args)
return max_result
def sum_res(*args):
sum_result = sum(*args)
return sum_result
n = [int(x) for x in input().split()]
print(f'The minimum number is {min_res(n)}')
print(f'The maximum ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
from bs4 import BeautifulSoup
import urllib.request
import requests
import sys
set arg = argv at 1
set month = argv at 2
set year = argv at 3
set url = string https://www.psp.cz/eknih/2017ps/audio/ { year } / { month } / { arg } /
set res = get requests url
set html_page = content
set soup... | #!/usr/bin/env python3
from bs4 import BeautifulSoup
import urllib.request
import requests
import sys
arg = sys.argv[1]
month = sys.argv[2]
year = sys.argv[3]
url = f"https://www.psp.cz/eknih/2017ps/audio/{year}/{month}/{arg}/"
res = requests.get(url)
html_page = res.content
soup = BeautifulSoup(html_page, 'html.par... | Python | zaydzuhri_stack_edu_python |
function writeKnowledgeAreaWorksheets wb
begin
global knowledgeAreas
for knowledgeArea in knowledgeAreas
begin
set ws = call add_worksheet
set name = call getText at slice 0 : 31 :
call writeWorksheet ws knowledgeArea
end
end function | def writeKnowledgeAreaWorksheets(wb: xlsxwriter.Workbook) -> None:
global knowledgeAreas
for knowledgeArea in knowledgeAreas:
ws = wb.add_worksheet()
ws.name = knowledgeArea.getText()[0:31]
writeWorksheet(ws, knowledgeArea) | Python | nomic_cornstack_python_v1 |
function _tf_fspecial_gauss size sigma
begin
set tuple x_data y_data = mgrid at tuple slice - size // 2 + 1 : size // 2 + 1 : slice - size // 2 + 1 : size // 2 + 1 :
set x_data = call expand_dims x_data axis=- 1
set x_data = call expand_dims x_data axis=- 1
set y_data = call expand_dims y_data axis=- 1
set y_data = c... | def _tf_fspecial_gauss(size, sigma):
x_data, y_data = np.mgrid[-size // 2 + 1:size // 2 + 1, -size // 2 + 1:size // 2 + 1]
x_data = np.expand_dims(x_data, axis = -1)
x_data = np.expand_dims(x_data, axis = -1)
y_data = np.expand_dims(y_data, axis = -1)
y_data = np.expand_dims(y_data, axis = -1)
x = tf.constant(... | Python | nomic_cornstack_python_v1 |
comment 将列表[0,1,2,3.14,‘x’,None,‘ ’,list(),{5}]中各个元素转为布尔型。
set list = list comprehension boolean item for item in list 0 1 2 3.14 string x none string list set literal 5
print list | #将列表[0,1,2,3.14,‘x’,None,‘ ’,list(),{5}]中各个元素转为布尔型。
list = [bool(item) for item in [0,1,2,3.14,'x',None,'',list(),{5}]]
print(list) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment Higher aim for project:
comment To write a ROS node that reads in an image as a point cloud, filters and
comment segments (using Euclidean clustering) that image into individual items
comment Aims for segmentation.py file:
comment 1) Write a function that will publish the point clou... | #!/usr/bin/env python
### Higher aim for project:
# To write a ROS node that reads in an image as a point cloud, filters and
# segments (using Euclidean clustering) that image into individual items
### Aims for segmentation.py file:
# 1) Write a function that will publish the point cloud data to the
# sensor_stick/po... | Python | zaydzuhri_stack_edu_python |
function add_missing_dependency_rows self df project count weight
begin
try
begin
comment MultiIndex
set levels = levels
end
except any
begin
comment Index
set levels = list index
end
set names = names
set option_cols = values
set df = reset index df
if string testing in project
begin
set df = df at slice 0 : 0 :
end
... | def add_missing_dependency_rows(self, df, project, count, weight):
try:
levels = df.index.levels # MultiIndex
except:
levels = [df.index] # Index
names = df.index.names
option_cols = df.columns.values
df = df.reset_index()
if 'testing' in project:
... | Python | nomic_cornstack_python_v1 |
set input_string = string Hello, World!
set reversed_string = string
for i in range length input_string - 1 - 1 - 1
begin
set reversed_string = reversed_string + input_string at i
end
print reversed_string | input_string = "Hello, World!"
reversed_string = ""
for i in range(len(input_string) - 1, -1, -1):
reversed_string += input_string[i]
print(reversed_string)
| Python | jtatman_500k |
string Unit tests for the structured metamodel component.
import unittest
import inspect
import numpy as np
from numpy.testing import assert_almost_equal
import openmdao.api as om
from openmdao.utils.assert_utils import assert_near_equal , assert_warning , assert_check_partials
from openmdao.utils.general_utils import ... | """
Unit tests for the structured metamodel component.
"""
import unittest
import inspect
import numpy as np
from numpy.testing import assert_almost_equal
import openmdao.api as om
from openmdao.utils.assert_utils import assert_near_equal, assert_warning, assert_check_partials
from openmdao.utils.general_utils import... | Python | jtatman_500k |
for i in range n + 1
begin
if i % 3 == 0 or i % 5 == 0
begin
set a at i = 0
end
else
begin
set a at i = i
end
end
print sum a | for i in range(n+1):
if i%3==0 or i%5==0:
a[i]=0
else:
a[i]=i
print(sum(a)) | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Oct 11 15:31:43 2019 @author: karapet
comment -*- coding: utf-8 -*-
string Created on Mon Oct 7 15:24:16 2019 @author: Balint
import numpy as np
import pandas as pd
set df = read csv string movie_metadata.csv
comment %%
head df
comment %%
call set_option string max_co... | # -*- coding: utf-8 -*-
"""
Created on Fri Oct 11 15:31:43 2019
@author: karapet
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 7 15:24:16 2019
@author: Balint
"""
import numpy as np
import pandas as pd
df = pd.read_csv("movie_metadata.csv")
#%%
df.head()
#%%
pd.set_option("max_columns"... | Python | zaydzuhri_stack_edu_python |
comment list
comment my_list = ["Batgirl", "Batman", "Supergirl", "Superman", "Aquaman"]
comment for superhero in my_list:
comment if superhero.lower() == "supergirl":
comment print("oui, tu as "+ superhero + " comme hero(ïne) dans ta liste")
comment for superhero in my_list:
comment if superhero.lower() != "supergirl"... | # list
#my_list = ["Batgirl", "Batman", "Supergirl", "Superman", "Aquaman"]
#for superhero in my_list:
# if superhero.lower() == "supergirl":
# print("oui, tu as "+ superhero + " comme hero(ïne) dans ta liste")
# for superhero in my_list:
# if superhero.lower() != "supergirl":
# print("non... | Python | zaydzuhri_stack_edu_python |
function dict_to_tf_example data dataset_directory label_map_dict ignore_difficult_instances=false image_subdirectory=string JPEGImages
begin
set img_path = join path data at string folder image_subdirectory data at string filename
set full_path = join path dataset_directory img_path
with call GFile full_path string rb... | def dict_to_tf_example(data,
dataset_directory,
label_map_dict,
ignore_difficult_instances=False,
image_subdirectory='JPEGImages'):
img_path = os.path.join(data['folder'], image_subdirectory, data['filename'])
full_path = os... | Python | nomic_cornstack_python_v1 |
function test_endpoints_of_distribution_exceeded_warning self
begin
set probabilities_for_cdf = array list list 0.05 0.7 0.95
set threshold_points = array list 8 10 60
set plugin = call Plugin ecc_bounds_warning=true
set warning_msg = string The calculated threshold values \[-40 8 10 60 50\] are not in ascending order ... | def test_endpoints_of_distribution_exceeded_warning(self):
probabilities_for_cdf = np.array([[0.05, 0.7, 0.95]])
threshold_points = np.array([8, 10, 60])
plugin = Plugin(ecc_bounds_warning=True)
warning_msg = (
"The calculated threshold values \\[-40 8 10 60 50\\] are "
... | Python | nomic_cornstack_python_v1 |
set a = string Hello, World!
print a at 1
set b = string Hello, World!
print b at slice 2 : 5 :
set a = string Hello, World!
print length a
set a = string Hello
set b = string World
set c = a + b
print c
set a = string Hello
set b = string World
set c = a + string + b
print c | a="Hello, World!"
print(a[1])
b="Hello, World!"
print(b[2:5])
a="Hello, World!"
print(len(a))
a="Hello"
b="World"
c=a+b
print(c)
a="Hello"
b="World"
c=a+" "+b
print(c)
| Python | zaydzuhri_stack_edu_python |
from shapercore.Modules.metaclass.Module_Data import Data
import pandas as pd
import numpy as np
class Expand extends Data
begin
function __init__ self column
begin
set _column = column
end function
function execute self element
begin
try
begin
set frame = call get_dataframe
comment get matrix
set matrix = frame at _co... | from shapercore.Modules.metaclass.Module_Data import Data
import pandas as pd
import numpy as np
class Expand(Data):
def __init__(self, column):
self._column = column
def execute(self, element):
try:
frame = element.get_dataframe()
# get matrix
matrix = fra... | Python | zaydzuhri_stack_edu_python |
function __init__ self tokens type_frequencies=none
begin
comment don't rename stoi and itos since needed for torchtext
comment warning: stoi grows with unknown tokens, don't use for saving or size
set specials = list UNK_TOKEN PAD_TOKEN BOS_TOKEN EOS_TOKEN
set stoi = default dictionary lambda -> DEFAULT_UNK_ID
set it... | def __init__(self, tokens: List[str], type_frequencies=None) -> None:
# don't rename stoi and itos since needed for torchtext
# warning: stoi grows with unknown tokens, don't use for saving or size
self.specials = [UNK_TOKEN, PAD_TOKEN, BOS_TOKEN, EOS_TOKEN]
self.stoi = defaultdict(lam... | Python | nomic_cornstack_python_v1 |
function foo
begin
set count = 0
while count < 100
begin
print string Hello
set count = count + 1
if count == 10
begin
break
end
end
end function | def foo():
count = 0
while count < 100:
print("Hello")
count += 1
if count == 10:
break
| Python | jtatman_500k |
function validators_for_request self request **kwargs
begin
string Takes a request and returns a validator mapping for the request. :param request: A Pyramid request to fetch schemas for :type request: :class:`pyramid.request.Request` :returns: a :class:`pyramid_swagger.load_schema.ValidatorMap` which can be used to va... | def validators_for_request(self, request, **kwargs):
"""Takes a request and returns a validator mapping for the request.
:param request: A Pyramid request to fetch schemas for
:type request: :class:`pyramid.request.Request`
:returns: a :class:`pyramid_swagger.load_schema.ValidatorMap` w... | Python | jtatman_500k |
class Fraction
begin
function __init__ self num denom
begin
set num = num
set denom = denom
end function
function __add__ self other
begin
return call Fraction num * denom + num * denom denom * denom
end function
function __sub__ self other
begin
return call Fraction num * denom - num * denom denom * denom
end function... | class Fraction():
def __init__(self, num, denom):
self.num = num
self.denom = denom
def __add__(self, other):
return Fraction((self.num*other.denom) + (other.num*self.denom), self.denom * other.denom)
def __sub__(self, other):
return Fraction((self.num*other.denom) - (other.num*self.denom), self.denom * ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string Ring buffer collection specialized for scalar values
class ScalarRingBuffer
begin
function __init__ self capacity
begin
if capacity < 1
begin
raise exception string capacity must be at least 1
end
set _capacity = capacity
set _size = 0
set _nextIndex = 0
set _values = list
end func... | #!/usr/bin/env python3
"""
Ring buffer collection specialized for scalar values
"""
class ScalarRingBuffer:
def __init__(self, capacity):
if(capacity < 1):
raise Exception("capacity must be at least 1")
self._capacity = capacity
self._size = 0
self._nextIndex = 0
... | Python | zaydzuhri_stack_edu_python |
function __init__ self *args **kwargs
begin
call __init__ *args keyword kwargs
if not task_id
begin
set task_id = call _create_task_id
end
end function | def __init__(self, *args, **kwargs):
super(EvaluationTask, self).__init__(*args, **kwargs)
if not self.task_id:
self.task_id = self.__class__._create_task_id() | Python | nomic_cornstack_python_v1 |
from matplotlib import pyplot as plt
from numpy import argmax
import numpy as np
from PIL import Image
import glob
function showImage image_data
begin
image show image_data
show
end function
function one_hot_to_categorical one_hot
begin
comment result = argmax(predictions[0])
return argument maximum one_hot
end functio... | from matplotlib import pyplot as plt
from numpy import argmax
import numpy as np
from PIL import Image
import glob
def showImage(image_data):
plt.imshow(image_data)
plt.show()
def one_hot_to_categorical(one_hot):
# result = argmax(predictions[0])
return argmax(one_hot)
def shuffle_wrt_to_each_other(a,... | Python | zaydzuhri_stack_edu_python |
function quantile_binning data=none bins=10 qrange=tuple 0.0 1.0 **kwargs
begin
string Binning schema based on quantile ranges. This binning finds equally spaced quantiles. This should lead to all bins having roughly the same frequencies. Note: weights are not (yet) take into account for calculating quantiles. Paramete... | def quantile_binning(data=None, bins=10, *, qrange=(0.0, 1.0), **kwargs) -> StaticBinning:
"""Binning schema based on quantile ranges.
This binning finds equally spaced quantiles. This should lead to
all bins having roughly the same frequencies.
Note: weights are not (yet) take into account for calcul... | Python | jtatman_500k |
function settings_version self
begin
return get pulumi self string settings_version
end function | def settings_version(self) -> str:
return pulumi.get(self, "settings_version") | Python | nomic_cornstack_python_v1 |
function _get_error_message_from_exception self e
begin
try
begin
if args
begin
if length args > 1
begin
set error_code = args at 0
set error_msg = args at 1
end
else
if length args == 1
begin
set error_code = ERR_CODE_MSG
set error_msg = args at 0
end
end
else
begin
set error_code = ERR_CODE_MSG
set error_msg = ERR_MS... | def _get_error_message_from_exception(self, e):
try:
if e.args:
if len(e.args) > 1:
error_code = e.args[0]
error_msg = e.args[1]
elif len(e.args) == 1:
error_code = ERR_CODE_MSG
error_msg... | Python | nomic_cornstack_python_v1 |
import scipy.constants as cons
import math
print string scipy : pi = %.16f % pi
print string math : pi = %.16f % pi | import scipy.constants as cons
import math
print("scipy : pi = %.16f"% cons.pi)
print("math : pi = %.16f"% math.pi)
| Python | zaydzuhri_stack_edu_python |
function test_unique_name_index self
begin
set actor_name = string Nicolas Cage
from models import Person
set nic_cage = call Person name=actor_name
add DBSession nic_cage
commit DBSession
set nic_dupe = call Person name=actor_name
add DBSession nic_dupe
from sqlalchemy.exc import IntegrityError
with assert raises Inte... | def test_unique_name_index(self):
actor_name = 'Nicolas Cage'
from ..models import Person
nic_cage = Person(name=actor_name)
DBSession.add(nic_cage)
DBSession.commit()
nic_dupe = Person(name=actor_name)
DBSession.add(nic_dupe)
from sqlalchemy.exc import In... | Python | nomic_cornstack_python_v1 |
function get self username
begin
if call is_admin
begin
set properties = call get_private_properties
end
else
begin
set properties = call get_public_properties
end
return call to_dict include=properties
end function | def get(self, username):
if auth.is_admin():
properties = User.get_private_properties()
else:
properties = User.get_public_properties()
return g.user_db.to_dict(include=properties) | Python | nomic_cornstack_python_v1 |
function dequeue self
begin
comment empty queue
if size == 0
begin
return none
end
set item = body at head
set body at head = none
comment just removed last element, so rebalance
if size == 1
begin
set head = 0
comment self.tail = 0
set size = 0
end
else
begin
set head = head + 1 % length body
set size = size - 1
end
c... | def dequeue(self):
if self.size == 0: # empty queue
return None
item = self.body[self.head]
self.body[self.head] = None
if self.size == 1: # just removed last element, so rebalance
self.head = 0
#self.tail = 0
self.si... | Python | nomic_cornstack_python_v1 |
from django.shortcuts import render_to_response
from datetime import datetime , date , timedelta
import socket
function nextpoya request
begin
set ctx = dict
set cur = now
if call gethostname != string poya-3014
begin
comment Offset time in app engine
set cur = cur + time delta hours=5 minutes=30
end
comment ctx['time... | from django.shortcuts import render_to_response
from datetime import datetime, date, timedelta
import socket
def nextpoya(request):
ctx = {}
cur = datetime.now()
if socket.gethostname() != 'poya-3014':
# Offset time in app engine
cur = cur + timedelta(hours=5,minutes=30)
# ctx['time']... | Python | zaydzuhri_stack_edu_python |
import StringIO
import itertools
from ecodejam.input_parser import *
function get_prob_for_vote k option votes
begin
return reduce lambda x y -> x * y generator expression if expression vote == 1 then prob else 1 - prob for tuple prob vote in zip option votes 1.0
end function
function tie_prob_for_option k option
begin... | import StringIO
import itertools
from ecodejam.input_parser import *
def get_prob_for_vote(k, option, votes):
return reduce(lambda x,y: x*y, (prob if vote == 1 else (1-prob) for prob, vote in zip(option, votes)), 1.0)
def tie_prob_for_option(k, option):
total = 0.0
# for votes in itertools.product(*[... | Python | zaydzuhri_stack_edu_python |
comment cell at row * column *, what's the function ?
comment cell at row * column *, what're the changes?
comment given row index, column index, return cell workflow
import glob
import json
import os
import re
from archive_query import Options
import pandas as pd
from dependency import OPDependency
comment from . impo... | # cell at row * column *, what's the function ?
# cell at row * column *, what're the changes?
# given row index, column index, return cell workflow
import glob
import json
import os
import re
from archive_query import Options
import pandas as pd
from dependency import OPDependency
# from . import dependency
def ge... | Python | zaydzuhri_stack_edu_python |
function New *args **kargs
begin
set obj = call __New_orig__
import itkTemplate
call New obj *args keyword kargs
return obj
end function | def New(*args, **kargs):
obj = itkMovingHistogramImageFilterBaseIUC2IUC2Neighborhood.__New_orig__()
import itkTemplate
itkTemplate.New(obj, *args, **kargs)
return obj | Python | nomic_cornstack_python_v1 |
for i in range 0 All
begin
set length = integer input
set ar = split input
set d = integer input
set ans = ar at slice d : : + ar at slice 0 : d :
for x in ans
begin
print x end=string
end
print
end | for i in range(0, All):
length=int(input())
ar=input().split()
d=int(input())
ans=ar[d:]+ar[0:d]
for x in ans:
print(x,end=' ')
print() | Python | zaydzuhri_stack_edu_python |
function dumps self user_info pac_url vpn_bypass_except format=string xml
begin
return call generate_profile_xml user_info pac_url vpn_bypass_except
end function | def dumps(self, user_info, pac_url, vpn_bypass_except, format='xml'):
return self.generate_profile_xml(user_info, pac_url, vpn_bypass_except) | Python | nomic_cornstack_python_v1 |
function invalid text
begin
set receptors = call extract_receptor text
set m = search string \"(.*?)\" split text string at 0
end function | def invalid(text):
receptors = extract_receptor(text)
m = re.search(r"\"(.*?)\"", text.split("\n")[0]) | Python | nomic_cornstack_python_v1 |
function get_sorted_vocab vocab_counter
begin
set sorted_vocab_list = sorted set call elements
set sorted_vocab_list = list comprehension term for term in sorted_vocab_list if term is not none
set sorted_vocab_list = sorted sorted_vocab_list
if PAD_TOKEN not in sorted_vocab_list
begin
insert sorted_vocab_list 0 PAD_TOK... | def get_sorted_vocab(vocab_counter):
sorted_vocab_list = sorted(set(vocab_counter.elements()))
sorted_vocab_list = [term for term in sorted_vocab_list if term is not None]
sorted_vocab_list = sorted(sorted_vocab_list)
if PAD_TOKEN not in sorted_vocab_list:
sorted_vocab_list.insert(0, PAD_TOKEN)
... | Python | nomic_cornstack_python_v1 |
for i in range n
begin
set x = integer input
set a = list map int split input
set g = integer input
end | for i in range(n):
x=int(input())
a=list(map(int,input().split()))
g=int(input())
| Python | zaydzuhri_stack_edu_python |
import random
import sys
import threading
import time
from typing import List , Tuple
import matplotlib.pyplot as plt
import numpy as np
from sortedcontainers import SortedList
from clonal_selection.clonal_selection import ClonalSelection
from jmetal.config import store
from jmetal.core.algorithm import Algorithm
from ... | import random
import sys
import threading
import time
from typing import List, Tuple
import matplotlib.pyplot as plt
import numpy as np
from sortedcontainers import SortedList
from clonal_selection.clonal_selection import ClonalSelection
from jmetal.config import store
from jmetal.core.algorithm import Algorithm
from... | Python | zaydzuhri_stack_edu_python |
from abc import ABCMeta
from functools import partial
from tornadotools import adisp
from brukva import Client
class Storage extends object
begin
string Abstract class for storages.
set __metaclass__ = ABCMeta
end class
class RedisStorage extends Storage
begin
string Store train results in redis database.
set CATEGORY_... | from abc import ABCMeta
from functools import partial
from tornadotools import adisp
from brukva import Client
class Storage(object):
"""Abstract class for storages.
"""
__metaclass__ = ABCMeta
class RedisStorage(Storage):
"""Store train results in redis database.
"""
CATEGORY_KEY_PREFIX = ... | Python | zaydzuhri_stack_edu_python |
function form_response self message
begin
comment Connection with valid username
if string USERNAME in keys message and message at string USERNAME not in keys clients
begin
set username = message at string USERNAME
call broadcast dict string USERS_JOINED list username
set clients at username = self
call send_message di... | def form_response(self, message):
# Connection with valid username
if "USERNAME" in message.keys() and message["USERNAME"] not in Server.\
clients.keys():
self.username = message["USERNAME"]
self.broadcast({"USERS_JOINED": [self.username]})
Server.cli... | Python | nomic_cornstack_python_v1 |
function FlowAccumFromProps props weights=none in_place=false
begin
string Calculates flow accumulation from flow proportions. Args: props (rdarray): An elevation model weights (rdarray): Flow accumulation weights to use. This is the amount of flow generated by each cell. If this is not provided, each cell will generat... | def FlowAccumFromProps(
props,
weights = None,
in_place = False
):
"""Calculates flow accumulation from flow proportions.
Args:
props (rdarray): An elevation model
weights (rdarray): Flow accumulation weights to use. This is the
amount of flow generated ... | Python | jtatman_500k |
class Base
begin
function __init__ self
begin
print self
set massage = string Hello World
end function
function print_massage self
begin
print massage
end function
end class
class Deroved extends Base
begin
pass
end class
if __name__ == string __main__
begin
set base = call Base
call print_massage
set derived = call De... | class Base:
def __init__(self):
print(self)
self.massage = "Hello World"
def print_massage(self):
print(self.massage)
class Deroved(Base):
pass
if __name__ == '__main__':
base = Base()
base.print_massage()
derived = Deroved()
derived.print_massage() | Python | zaydzuhri_stack_edu_python |
class a
begin
set x = 20
end class
comment create object
set obj1 = call a
comment 2nd object
set obj2 = call a
set name = string suresh
comment class
print a
comment object
print call a
comment suresh
print name
print x
set x = 30
comment 20
print x
comment 30
print x
comment using dict attribute , {"name":"suresh","x... | class a():
x = 20
obj1 = a() #create object
obj2 = a() #2nd object
obj1.name = "suresh"
print(a) #class
print(a()) #object
print(obj1.name) #suresh
print(a.x)
obj1.x = 30
print(a.x) #20
print(obj1.x) # 30
print(obj1.__dict__) # using dict attribute , {"name":"suresh","x":30} | Python | zaydzuhri_stack_edu_python |
function Title self
begin
return title
end function | def Title(self):
return self.title | Python | nomic_cornstack_python_v1 |
comment Reverse*
comment https://www.hackerearth.com/problem/algorithm/reverse/
set t = integer call raw_input | # Reverse*
# https://www.hackerearth.com/problem/algorithm/reverse/
t=int(raw_input()) | Python | zaydzuhri_stack_edu_python |
import numpy as np
import csv
import sys
from sklearn.decomposition import PCA
from matplotlib.widgets import CheckButtons
print string ------------------------
set NUM_PCA_COMPONENTS = 30
set INPUT_FILE = none
for arg in argv at slice 1 : :
begin
set ss = split arg string =
if length ss >= 2
begin
if ss at 0 == stri... | import numpy as np
import csv;
import sys;
from sklearn.decomposition import PCA
from matplotlib.widgets import CheckButtons
print("------------------------")
NUM_PCA_COMPONENTS = 30
INPUT_FILE = None
for arg in sys.argv[1:]:
ss = arg.split("=")
if len(ss) >= 2:
if ss[0] == "INPUT":
INPUT... | Python | zaydzuhri_stack_edu_python |
function effective_patterns self context=none
begin
string Get effective patterns for this rebulk object and its children. :param context: :type context: :return: :rtype:
set patterns = list _patterns
for rebulk in _rebulks
begin
if not call disabled context
begin
call extend_safe patterns _patterns
end
end
return patt... | def effective_patterns(self, context=None):
"""
Get effective patterns for this rebulk object and its children.
:param context:
:type context:
:return:
:rtype:
"""
patterns = list(self._patterns)
for rebulk in self._rebulks:
if not rebu... | Python | jtatman_500k |
function get_reviews data reviews
begin
set review_list = list
comment Go over list of users/pois used in user-poi interaction
for key in data
begin
comment Retrieve all words ever used by this user/poi and add it to output
append review_list reviews at key
end
return review_list
end function | def get_reviews(data,reviews):
review_list=[]
# Go over list of users/pois used in user-poi interaction
for key in data:
# Retrieve all words ever used by this user/poi and add it to output
review_list.append(reviews[key])
return review_list | Python | nomic_cornstack_python_v1 |
function fetch_all_pages self query params=none headers=none
begin
set r = get requests query params=params headers=headers
if not ok
begin
raise exception string Error in fetch_all_pages string query : query string r.json() json r
end
set link = get headers string link none
if link is none
begin
return json r
end
if s... | def fetch_all_pages(self,query, params=None, headers=None):
r = requests.get(query, params=params, headers=headers )
if not r.ok:
raise(Exception("Error in fetch_all_pages", "query : ", query, "r.json() ", r.json()))
link = r.headers.get('link', None)
if link is None:
... | Python | nomic_cornstack_python_v1 |
string 플로이드 와샬을 통해 i 지점에서 j 지점으로 가는 최단거리들을 모두 구한후 각 행의 m 이하의 값들을 찾아 계산 한 후 최대값을 찾는다.
import sys
set input = readline
set tuple n m r = map int split input
set items = list map int split input
set graph = list comprehension list for i in range n + 1
set INF = 987654321
set dist = list comprehension list comprehension i... | '''
플로이드 와샬을 통해 i 지점에서 j 지점으로 가는 최단거리들을 모두 구한후
각 행의 m 이하의 값들을 찾아 계산 한 후 최대값을 찾는다.
'''
import sys
input = sys.stdin.readline
n,m,r = map(int,input().split())
items = list(map(int,input().split()))
graph = [[] for i in range(n+1)]
INF = 987654321
dist = [[0 if i==j else INF for i in range(n+1)] for j in range(n+1)]
f... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment Collection of terms that predominantly refer to one gender or the other
class GenderTerms
begin
function __init__ self
begin
set male_terms = none
set female_terms = none
end function
function get_male_terms self
begin
if not male_terms
begin
set male_terms = set list string boyfriend s... | #!/usr/bin/python
#Collection of terms that predominantly refer to one gender or the other
class GenderTerms:
def __init__(self):
self.male_terms = None
self.female_terms = None
def get_male_terms(self):
if not self.male_terms:
self.male_terms = set([
"boyfriend",
"husband",
... | Python | zaydzuhri_stack_edu_python |
function get_rotation_matrix angle
begin
return array list list cos angle - sin angle list sin angle cos angle
end function | def get_rotation_matrix(angle: float) -> np.ndarray:
return np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) | Python | nomic_cornstack_python_v1 |
import binascii
import struct
import sys
import pytest
from shapely import wkt
from shapely.wkb import dumps , loads
from shapely.geometry import Point
from shapely.geos import geos_version
function bin2hex value
begin
return decode upper call b2a_hex value string utf-8
end function
function hex2bin value
begin
return ... | import binascii
import struct
import sys
import pytest
from shapely import wkt
from shapely.wkb import dumps, loads
from shapely.geometry import Point
from shapely.geos import geos_version
def bin2hex(value):
return binascii.b2a_hex(value).upper().decode("utf-8")
def hex2bin(value):
return binascii.a2b_h... | Python | zaydzuhri_stack_edu_python |
comment find nonnegative numbers
set S = set literal - 4 4 - 3 3 - 2 2 - 1 1 0
set result = set comprehension x for x in S if x >= 0 | # find nonnegative numbers
S = {-4, 4, -3, 3, -2, 2, -1, 1, 0}
result = {x for x in S if x >= 0} | Python | zaydzuhri_stack_edu_python |
function _add_accelerations_to_df self route_df a_prof
begin
comment print(route_df.head())
set accelerations = call _calculate_acceleration route_df a_prof
comment Assign acceleration values to new row in route DataFrame.
set route_df = call assign acceleration=accelerations
return route_df
end function | def _add_accelerations_to_df(self, route_df, a_prof):
# print(route_df.head())
accelerations = self._calculate_acceleration(route_df, a_prof)
#Assign acceleration values to new row in route DataFrame.
route_df = route_df.assign(
acceleration=accelerations
)
... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.