code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function problem_52
begin
for number in call xrange 1 123456789
begin
set sorted_num = join string sorted string number
if length list comprehension value for value in call xrange 2 7 if join string sorted string value * number == sorted_num == 5
begin
return number
end
end
end function | def problem_52():
for number in xrange(1, 123456789):
sorted_num = ''.join(sorted(str(number)))
if len([value for value in xrange(2, 7)
if ''.join(sorted(str((value * number)))) == sorted_num]) == 5:
return number | Python | nomic_cornstack_python_v1 |
import streamlit as st
import cv2
import numpy as np
import path_planning
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
function draw_path img pathway thickness=2
begin
comment For-Loop with path, start with the first point, and join sequential points with line function
set tuple start_x sta... | import streamlit as st
import cv2
import numpy as np
import path_planning
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
def draw_path(img, pathway, thickness=2):
# For-Loop with path, start with the first point, and join sequential points with line function
start_x, start_y = pathw... | Python | zaydzuhri_stack_edu_python |
string From Adrienne's Medium post [0]: The pieces: * `deleted_at`: this means that all models inheriting from the SoftDeletionModel will have this attribute available to be set. By default it will be null. I recommend a date instead of a boolean so that you can create a background job that hard-deletes any objects tha... | """
From Adrienne's Medium post [0]:
The pieces:
* `deleted_at`: this means that all models inheriting from the SoftDeletionModel will have this attribute available to be set.
By default it will be null. I recommend a date instead of a boolean so that you can create a background job that
... | Python | zaydzuhri_stack_edu_python |
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import mingus.extra.lilypond as LilyPond
import numpy as np
from mingus.containers import Bar , Track
from transcriber.notes import notes_dict
from transcriber.settings import CHUNK_SIZE , LOUDNESS_THRESHOLD , MINIMUM_FREQUENCY
set prev_loudness = 0
set f... | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import mingus.extra.lilypond as LilyPond
import numpy as np
from mingus.containers import Bar, Track
from transcriber.notes import notes_dict
from transcriber.settings import CHUNK_SIZE, LOUDNESS_THRESHOLD, MINIMUM_FREQUENCY
prev_loudness = 0
fig = Non... | Python | zaydzuhri_stack_edu_python |
function getCmd snmpDispatcher authData transportTarget *varBinds **options
begin
function cbFun *args **kwargs
begin
set response at slice : : = args
end function
set options at string cbFun = cbFun
set tuple errorIndication errorStatus errorIndex = tuple none 0 0
set response = list
while true
begin
if varBinds
b... | def getCmd(snmpDispatcher, authData, transportTarget,
*varBinds, **options):
def cbFun(*args, **kwargs):
response[:] = args
options['cbFun'] = cbFun
errorIndication, errorStatus, errorIndex = None, 0, 0
response = []
while True:
if varBinds:
cmdgen.getCmd(s... | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
comment Author: Lu Liwen
comment Modified Time: 2019-11-21
string Laplacian Eigenmap(特征映射降维) 步骤: knn建图 rbf核函数计算边权重 构造拉普拉斯矩阵 广义特征值计算 修改: 1. 先使用knn计算k近邻,再用rbf处理边的权重 2. line57 不同数据集的特征根选择不同!
from numpy import *
from lib import GraphCalculate as Graph
from lib import BasicFunction as Basic
comm... | # -*- coding:utf-8 -*-
# Author: Lu Liwen
# Modified Time: 2019-11-21
"""
Laplacian Eigenmap(特征映射降维)
步骤:
knn建图
rbf核函数计算边权重
构造拉普拉斯矩阵
广义特征值计算
修改:
1. 先使用knn计算k近邻,再用rbf处理边的权重
2. line57 不同数据集的特征根选择不同!
"""
from numpy import *
from lib import GraphCalculate as Graph
from lib import BasicFunction as Basic
... | Python | zaydzuhri_stack_edu_python |
async function fire_event self event **kwargs
begin
set namespace = call _get_namespace keyword kwargs
if string namespace in kwargs
begin
del kwargs at string namespace
end
await call fire_event namespace event keyword kwargs
end function | async def fire_event(self, event: str, **kwargs: Optional[Any]) -> None:
namespace = self._get_namespace(**kwargs)
if "namespace" in kwargs:
del kwargs["namespace"]
await self.AD.events.fire_event(namespace, event, **kwargs) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Thu Sep 23 15:18:08 2021 @author: huannn
set a = string This
set b = string is
set c = string a Python practice
print c
print c at 0
print c at slice 0 : 5 :
print c at slice 2 : :
print c * 2
print string a+b+c= { a + string + b + string ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 23 15:18:08 2021
@author: huannn
"""
a="This"
b="is"
c="a Python practice"
print(c)
print(c[0])
print(c[0:5])
print(c[2:])
print(c*2)
print(f"a+b+c={a+' '+b+' '+c}") | Python | zaydzuhri_stack_edu_python |
function write_trainer self
begin
with open string HW_00_MSJ_Trained.py string w+ encoding=string utf-8 as train_file
begin
write train_file call t_imports
write train_file call t_personal_info
write train_file call t_creation_time
write train_file call t_curr_time
write train_file call t_csv_row_col_cnt
end
end functi... | def write_trainer(self):
with open("HW_00_MSJ_Trained.py", "w+", encoding="utf-8") as train_file:
train_file.write(self.t_imports())
train_file.write(self.t_personal_info())
train_file.write(self.t_creation_time())
train_file.write(self.t_curr_time())
... | Python | nomic_cornstack_python_v1 |
if fi >= si and fi >= ti
begin
print fi
end
else
if si >= fi and si >= ti
begin
print si
end
else
begin
print ti
end | if fi>=si and fi>=ti:
print(fi)
elif si>=fi and si>=ti:
print(si)
else:
print(ti)
| Python | zaydzuhri_stack_edu_python |
function test_does_not_match self
begin
set test_cases = list string ... string . string :fda string @ string #
for sig in test_cases
begin
call check_is_not_match sig
end
end function | def test_does_not_match(self):
test_cases = [
'...',
'.',
':fda',
'@',
'#',
]
for sig in test_cases:
self.check_is_not_match(sig) | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python3
function ui_input
begin
return input string Enter phrase :
end function
function count_vowel phrase
begin
set phrase = lower phrase
set vowel = list string a string o string u string i string e string y
set number = 0
for _ in vowel
begin
set number = number + count phrase _
end
return number... | #! /usr/bin/python3
def ui_input():
return (input("Enter phrase : "))
def count_vowel(phrase):
phrase = phrase.lower()
vowel = ['a','o','u','i','e','y',]
number = 0
for _ in vowel:
number += phrase.count(_)
return number
def ui_output(number):
print("There are " + str(number) + ... | Python | zaydzuhri_stack_edu_python |
function default_field_types self
begin
set fields = default_field_types
update fields dict string mjd nan ; string lst nan * call Unit string hourangle ; string sin_a nan ; string cos_a nan ; string dof 1.0 ; string dependents 0.0 ; string relative_weight 1.0 ; string sign 1 ; string transmission 1.0 ; string temp_c f... | def default_field_types(self):
fields = super().default_field_types
fields.update({
'mjd': np.nan,
'lst': np.nan * units.Unit('hourangle'),
'sin_a': np.nan,
'cos_a': np.nan,
'dof': 1.0,
'dependents': 0.0,
'relative_weigh... | Python | nomic_cornstack_python_v1 |
function forward self x
begin
set x = relu call fc_1 x
set x = relu call fc_2 x
return tuple call critic_output x call actor_output x
end function | def forward(self, x):
x = F.relu(self.fc_1(x))
x = F.relu(self.fc_2(x))
return self.critic_output(x), self.actor_output(x) | Python | nomic_cornstack_python_v1 |
import smtplib , os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import imaplib
comment Read Mail
function read
begin
call system string cls
set mailserver = call IMAP4_SSL string imap.aol.com 993
set username = string uname
set password = string pwd
call login username password
set... | import smtplib, os
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import imaplib
#Read Mail
def read():
os.system("cls")
mailserver = imaplib.IMAP4_SSL('imap.aol.com',993)
username = 'uname'
password = 'pwd'
mailserver.login(username, password)
status, count ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
string Author:Daniel Xu Date:2020/12/07
import unittest
from test_function.city_functions import get_city_country
class CityTestCase extends TestCase
begin
string 测试get_city_country函数
function test_city_country self
begin
set city_info = call get_city_country string santiago string chile
as... | # -*- coding:utf-8 -*-
"""
Author:Daniel Xu
Date:2020/12/07
"""
import unittest
from test_function.city_functions import get_city_country
class CityTestCase(unittest.TestCase):
"""测试get_city_country函数"""
def test_city_country(self):
city_info = get_city_country('santiago', 'chile')
self.asser... | Python | zaydzuhri_stack_edu_python |
function wait_for msg f=none *a timeout=1 sleep=none **kw
begin
if not is instance sleep list
begin
set sleep = if expression sleep is none then list timeout / 10.0 else list sleep
end
set t0 = now
while true
begin
set res = f dist *a keyword kw
comment print(res)
if res
begin
comment in errcode, value format?
if is in... | def wait_for(msg, f=None, *a, timeout=1, sleep=None, **kw):
if not isinstance(sleep, list):
sleep = [timeout / 10.0] if sleep is None else [sleep]
t0 = now()
while True:
res = f(*a, **kw)
# print(res)
if res:
# in errcode, value format?
if isinstance(r... | Python | nomic_cornstack_python_v1 |
comment 展开嵌套的序列 将一个多层嵌套的序列展开成一个单层列表
from collections import Iterable
function flatten items ignore_types=tuple str bytes
begin
for x in items
begin
if is instance x Iterable and not is instance x ignore_types
begin
yield from flatten x
end
else
begin
yield x
end
end
end function
set items = list 1 2 list 3 4 list 5 6 7... | # 展开嵌套的序列 将一个多层嵌套的序列展开成一个单层列表
from collections import Iterable
def flatten(items,ignore_types=(str,bytes)):
for x in items:
if isinstance(x,Iterable) and not isinstance(x,ignore_types):
yield from flatten(x)
else:
yield x
items = [1,2,[3,4,[5,6],7],8]
for x in flatten(it... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function topKFrequent self nums k
begin
string :type nums: List[int] :type k: int :rtype: List[int]
set elems = dict
for num in nums
begin
if num not in elems
begin
set elems at num = 1
end
else
begin
set elems at num = elems at num + 1
end
end
set elems = sorted elems key=lambda nu... | class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
elems = {}
for num in nums:
if num not in elems:
elems[num] = 1
else:
elems[num] += 1
... | Python | zaydzuhri_stack_edu_python |
function login login_url username=none password=none
begin
set cookies = call HTTPCookieProcessor
set opener = call build_opener cookies
call install_opener opener
open login_url
try
begin
set token = list comprehension value for x in cookiejar if name == string csrftoken at 0
end
except IndexError
begin
return tuple n... | def login(login_url, username=None, password=None):
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)
urllib2.install_opener(opener)
opener.open(login_url)
try:
token = [x.value for x in cookies.cookiejar if x.name == 'csrftoken'][0]
except IndexError:
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
from collections import Counter
set counts = dictionary
set exe_count = 0
set first = true
with open string instruction.tsv string r as fptr
begin
for line in fptr
begin
if first
begin
set first = false
end
else
begin
set splt = split strip line string
set addr = lower splt at 0
set total = int... | #!/usr/bin/python
from collections import Counter
counts = dict()
exe_count = 0
first = True
with open("instruction.tsv", "r") as fptr:
for line in fptr:
if first:
first = False
else:
splt = line.strip().split('\t')
addr = splt[0].lower()
total = int(splt[1])
reads = Counter()
writes = Counter... | Python | zaydzuhri_stack_edu_python |
set n1 = decimal input string digite o primeiro numero:
set n2 = decimal input string digite o segundo numero:
set soma = n1 + n2
print format string as soma de {} e {} é igual a {} n1 n2 soma | n1 = float(input("digite o primeiro numero: "))
n2 = float(input("digite o segundo numero: "))
soma = n1 + n2
print('as soma de {} e {} é igual a {}'. format(n1, n2, soma)) | Python | zaydzuhri_stack_edu_python |
import os , cv2 , logging
import numpy as np
import keyNet.datasets.dataset_utils as tools
from tqdm import tqdm
from torch.utils.data import Dataset
from keyNet.aux.tools import check_directory
class pytorch_dataset extends Dataset
begin
function __init__ self data mode=string train
begin
set data = data
comment Restr... | import os, cv2, logging
import numpy as np
import keyNet.datasets.dataset_utils as tools
from tqdm import tqdm
from torch.utils.data import Dataset
from keyNet.aux.tools import check_directory
class pytorch_dataset(Dataset):
def __init__(self, data, mode='train'):
self.data =data
## Restrict the n... | Python | zaydzuhri_stack_edu_python |
function activate obj
begin
from activedirectory.core.creds import Creds
if is instance obj Creds
begin
call _activate_config
call _activate_ccache
end
set instance = obj
return obj
end function | def activate(obj):
from activedirectory.core.creds import Creds
if isinstance(obj, Creds):
obj._activate_config()
obj._activate_ccache()
type(obj).instance = obj
return obj | Python | nomic_cornstack_python_v1 |
function main
begin
set n = integer input
set w_lst = list map int split input
set difference_lst = list
for i in range 1 n
begin
set s1 = 0
set s2 = 0
for j in range i
begin
set s1 = s1 + w_lst at j
end
for j in range i n
begin
set s2 = s2 + w_lst at j
end
append difference_lst absolute s1 - s2
end
set minimum = min ... | def main():
n = int(input())
w_lst = list(map(int, input().split()))
difference_lst = []
for i in range(1, n):
s1 = 0
s2 = 0
for j in range(i):
s1 += w_lst[j]
for j in range(i, n):
s2 += w_lst[j]
difference_lst.append(abs(s1 - s2))
... | Python | zaydzuhri_stack_edu_python |
function setup_scripts self
begin
return get pulumi self string setup_scripts
end function | def setup_scripts(self) -> Optional['outputs.SetupScriptsResponse']:
return pulumi.get(self, "setup_scripts") | Python | nomic_cornstack_python_v1 |
function imshow image nsig=3 ax=none **kwargs
begin
set mean = mean np image
set std = standard deviation np image
set defaults = dict string origin string lower ; string interpolation string nearest ; string cmap gray ; string vmin mean - nsig * std ; string vmax mean + nsig * std ; string aspect string equal
update d... | def imshow(image, nsig=3, ax=None, **kwargs):
mean = np.mean(image)
std = np.std(image)
defaults = {'origin': 'lower', 'interpolation': 'nearest', 'cmap': plt.cm.gray,
'vmin': mean - nsig * std, 'vmax': mean + nsig * std,
'aspect': 'equal'
}
defaults.upda... | Python | nomic_cornstack_python_v1 |
function chat_sent self data
begin
return true
end function | def chat_sent(self, data):
return True | Python | nomic_cornstack_python_v1 |
function generatePredictions method hlas peptides cpus=1 verbose=false
begin
if verbose
begin
string Create console handler and set level to debug
call basicConfig level=INFO format=string %(levelname)s:%(asctime)s:%(message)s
info string HLA prediction initialized for %d HLA allele(s) using method %s on %d CPU(s) leng... | def generatePredictions(method, hlas, peptides, cpus=1, verbose=False):
if verbose:
"""Create console handler and set level to debug"""
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(asctime)s:%(message)s')
logging.info('HLA prediction initialized for %d HLA allele(s) using ... | Python | nomic_cornstack_python_v1 |
import os
import unittest
from ghapi.all import GhApi
import utils_.utils_ as utils
set create_table = string CREATE TABLE githubUsers ( idx INTEGER PRIMARY KEY, Username TEXT, githubId INTEGER, imageUrl TEXT, userType TEXT, linkToGitHub TEXT )
class TestStringMethods extends TestCase
begin
function test_connect_to_une... | import os
import unittest
from ghapi.all import GhApi
import utils_.utils_ as utils
create_table = 'CREATE TABLE githubUsers (\
idx INTEGER PRIMARY KEY,\
Username TEXT,\
githubId INTEGER,\
imageUrl TEXT,\
userType TEXT,\
linkToGitHub TEXT\
)'
class TestStringMethods(unittest.TestCase):
def test_conne... | Python | zaydzuhri_stack_edu_python |
if numero >= 0
begin
print string O numero %d é positivo. % numero
end
else
if numero < 0
begin
print string O numero %d é negativo. % numero
end | if numero >= 0:
print("O numero %d é positivo." % numero)
elif numero < 0:
print("O numero %d é negativo." % numero)
| Python | zaydzuhri_stack_edu_python |
comment Aggregation and Pruning
comment Performing aggregation
comment Select the column headers for sign items
set sign_headers = list comprehension i for i in columns if find lower i string sign >= 0
comment Select columns of sign items
set sign_columns = onehot at sign_headers
comment Perform aggregation of sign ite... | # Aggregation and Pruning
# Performing aggregation
# Select the column headers for sign items
sign_headers = [i for i in onehot.columns if i.lower().find('sign')>=0]
# Select columns of sign items
sign_columns = onehot[sign_headers]
# Perform aggregation of sign items into sign category
signs = sign_columns.sum(axis ... | Python | zaydzuhri_stack_edu_python |
function GetRootAsBossPhaseExcel cls buf offset=0
begin
return call GetRootAs buf offset
end function | def GetRootAsBossPhaseExcel(cls, buf, offset=0):
return cls.GetRootAs(buf, offset) | Python | nomic_cornstack_python_v1 |
function do_it self
begin
set has_scene_open = call _check_scene_open
if has_scene_open
begin
call _ask_for_template_use
end
else
begin
call _create_from_template
end
end function | def do_it(self):
has_scene_open = self._check_scene_open()
if has_scene_open:
self._ask_for_template_use()
else:
self._create_from_template() | Python | nomic_cornstack_python_v1 |
for row in matrix
begin
for colm in row
begin
print colm
end
end | for row in matrix:
for colm in row:
print(colm)
| Python | zaydzuhri_stack_edu_python |
string Not much of a difference at first sight, but the benefits are pretty substantial * No bookkeeping. You don't have to create an empty list, append to it, and return it. One more variable gone. * Hardly consumes memory. No matter how large the input file is, the iterator version does not need to buffer the entire ... | """
Not much of a difference at first sight, but the benefits are pretty substantial
* No bookkeeping.
You don't have to create an empty list, append to it, and return it.
One more variable gone.
* Hardly consumes memory.
No matter how large the input file is,
the iterator version does not need to buffe... | Python | zaydzuhri_stack_edu_python |
import threading
import tkinter as tk
import socket
import sys
import constants
from struct import *
import select
from constants import ETH_LENGTH
import matplotlib.pyplot as plt
from pandas import DataFrame
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from collections import defaultdict
import rand... | import threading
import tkinter as tk
import socket
import sys
import constants
from struct import *
import select
from constants import ETH_LENGTH
import matplotlib.pyplot as plt
from pandas import DataFrame
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from collections import defaultdict
import rand... | Python | zaydzuhri_stack_edu_python |
string 517 super washing machine
class Solution extends object
begin
function super_washing_machine self machines
begin
set n = length machines
if sum machines % n != 0
begin
return - 1
end
set tuple count res = tuple 0 0
set avg = sum machines // n
for load in machines
begin
comment load- avg is the gain/lose
set coun... | """
517 super washing machine
"""
class Solution(object):
def super_washing_machine(self, machines):
n = len(machines)
if sum(machines) % n != 0: return -1
count, res = 0, 0
avg = sum(machines) // n
for load in machines:
count += load - avg # load- avg is the gain/lose
res = max(res, max(load - avg, ... | Python | zaydzuhri_stack_edu_python |
function act self action_index
begin
if id == string Pong-v0 or id == string Breakout-v0
begin
set action_index = action_index + 1
end
set tuple x_t1 r_t terminal info = step env action_index
set x_t1 = call get_preprocessed_frame x_t1
set previous_frames = array state_buffer
set s_t1 = call empty tuple agent_history_l... | def act(self, action_index):
if (self.env.spec.id == 'Pong-v0' or self.env.spec.id == 'Breakout-v0'):
action_index += 1
x_t1, r_t, terminal, info = self.env.step(action_index)
x_t1 = self.get_preprocessed_frame(x_t1)
previous_frames = np.array(self.state_buffer)
s_... | Python | nomic_cornstack_python_v1 |
comment DFS
comment Runtime: 260 ms, faster than 5.46% of Python3 online submissions for Employee Importance.
comment Memory Usage: 17.1 MB, less than 8.33% of Python3 online submissions for Employee Importance.
string # Employee info class Employee: def __init__(self, id: int, importance: int, subordinates: List[int])... | # DFS
# Runtime: 260 ms, faster than 5.46% of Python3 online submissions for Employee Importance.
# Memory Usage: 17.1 MB, less than 8.33% of Python3 online submissions for Employee Importance.
"""
# Employee info
class Employee:
def __init__(self, id: int, importance: int, subordinates: List[int]):
... | Python | zaydzuhri_stack_edu_python |
function max_k_value
begin
comment Step 2: Set the values for A, B, and C
comment smallest possible value for a non-zero digit
set A = 1
comment smallest possible digit
set B = 0
comment largest possible digit
set C = 9
comment Step 3: Calculate the two-digit number
set two_digit_number = 10 * A + B
comment Step 4: Cal... | def max_k_value():
# Step 2: Set the values for A, B, and C
A = 1 # smallest possible value for a non-zero digit
B = 0 # smallest possible digit
C = 9 # largest possible digit
# Step 3: Calculate the two-digit number
two_digit_number = 10 * A + B
# Step 4: Calculate the three-digit numb... | Python | dbands_pythonMath |
function firstGap self
begin
return call firstGap self
end function | def firstGap(self):
return self.Alphabet.firstGap(self) | Python | nomic_cornstack_python_v1 |
function loadConfigTemplates self
begin
comment Log the parameters.
debug __name__ + string .loadConfigTemplates(): called.
end function
comment Check to see if we have the cache of templates. If so,
comment load the cache from disk, otherwise get it from WebSphere
comment and then write it to disk. | def loadConfigTemplates(self):
################################################################
# Log the parameters.
################################################################
self.debug( __name__ + ".loadConfigTemplates(): called.\n" )
################################################################
... | Python | nomic_cornstack_python_v1 |
function __virtual__
begin
if call is_windows
begin
return __virtualname__
end
return tuple false string Module win_disk: module only works on Windows systems
end function | def __virtual__():
if salt.utils.platform.is_windows():
return __virtualname__
return (False, "Module win_disk: module only works on Windows systems") | Python | nomic_cornstack_python_v1 |
set universe_age = 14000000000
print universe_age
set bicycles = list string trek string cannondale string redline string specialized
print title bicycles at 0
print bicycles at 1
print bicycles at 3
print bicycles at - 1
set message = string My first bicycle was a { title bicycles at 0 } .
print message
set motorcycle... | universe_age = 14_000_000_000
print(universe_age)
bicycles = ["trek", "cannondale", "redline", "specialized"]
print(bicycles[0].title())
print(bicycles[1])
print(bicycles[3])
print(bicycles[-1])
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
motorcycles = ["honda", "yamaha", "suzuki"]
pr... | Python | zaydzuhri_stack_edu_python |
function install_module_on_juju_unit unit source destination=string . model=none install_virtualenv=true run_user=none
begin
call install_module_in_venv source destination call make_juju_scp_fn unit model=model call make_juju_ssh_fn unit model=model install_virtualenv=install_virtualenv run_user=run_user
end function | def install_module_on_juju_unit(
unit, source, destination=".", model=None, install_virtualenv=True,
run_user=None):
install_module_in_venv(
source,
destination,
make_juju_scp_fn(unit, model=model),
make_juju_ssh_fn(unit, model=model),
install_virtualenv=insta... | Python | nomic_cornstack_python_v1 |
function archive_list request
begin
set archive_list = call order_by string project__client
set archive_filter = call ArchiveFilter GET queryset=archive_list
return call render request string reporting/archives.html dict string filter archive_filter
end function | def archive_list(request):
archive_list = Archive.objects.select_related('project__client').all().\
order_by('project__client')
archive_filter = ArchiveFilter(request.GET, queryset=archive_list)
return render(request, 'reporting/archives.html',
{'filter': archive_filter}) | Python | nomic_cornstack_python_v1 |
function _norm_dist x y
begin
return absolute norm x - norm y / norm x - y
end function | def _norm_dist(x, y):
return torch.abs(torch.norm(x) - torch.norm(y)) / torch.norm(x - y) | Python | nomic_cornstack_python_v1 |
print string * * 40
print string 내 이름은 + string Tom 이다.
set first = string 내 이름은
set second = string Tom 이다.
set string = first + second
print string
set A = string 안
set B = string 녕
print A + B + string + first + second
print string * * 40 | print("*" * 40)
print("내 이름은" + " Tom 이다.")
first = "내 이름은"
second = " Tom 이다."
string = first + second
print(string)
A = "안"
B = "녕"
print(A + B + " " + first + second)
print("*" * 40)
| Python | zaydzuhri_stack_edu_python |
import numpy as np
import torch
import torch.nn as nn
class Binop
begin
function __init__ self model
begin
set count_targets = 0
for m in call modules
begin
if is instance m Conv2d or is instance m Linear
begin
set count_targets = count_targets + 1
end
end
set bin_range = call tolist
set num_of_params = length bin_rang... | import numpy as np
import torch
import torch.nn as nn
class Binop:
def __init__(self,model):
count_targets = 0
for m in model.modules():
if isinstance(m,nn.Conv2d) or isinstance(m,nn.Linear):
count_targets += 1
self.bin_range = np.linspace(0,count_targets-1,count... | Python | zaydzuhri_stack_edu_python |
function aborting self
begin
call aborting
call _stop_logic
end function | def aborting(self):
super(FixClient, self).aborting()
self._stop_logic() | Python | nomic_cornstack_python_v1 |
function matrix df path=none title=string d3heatmap description=string Heatmap description width=500 height=500 fontsize=10 cmap=string interpolateInferno scale=false vmin=none vmax=none showfig=true stroke=string red overwrite=true verbose=3
begin
if cmap in list string schemeCategory10 string schemeAccent string sche... | def matrix(df, path=None, title='d3heatmap', description='Heatmap description', width=500, height=500, fontsize=10, cmap='interpolateInferno', scale=False, vmin=None, vmax=None, showfig=True, stroke='red', overwrite=True, verbose=3):
if cmap in ['schemeCategory10', 'schemeAccent', 'schemeDark2', 'schemePaired', 'sc... | Python | nomic_cornstack_python_v1 |
function _add_id_to_keys self pk conn=none
begin
string _add_id_to_keys - Adds primary key to table internal
if conn is none
begin
set conn = call _get_connection
end
call sadd call _get_ids_key pk
end function | def _add_id_to_keys(self, pk, conn=None):
'''
_add_id_to_keys - Adds primary key to table
internal
'''
if conn is None:
conn = self._get_connection()
conn.sadd(self._get_ids_key(), pk) | Python | jtatman_500k |
comment !coding=utf8
import io
import numpy as np
import pandas as pd
comment 返回rfile中域名的特征向量KMeans聚类结果
comment 每行格式:[域名, KMeans聚类簇编号]
function getFeatureVector rfile
begin
set fv = list
with open rfile string r as f
begin
for line in read lines f
begin
append fv eval line
end
end
return fv
end function
comment 返回rfil... | #!coding=utf8
import io
import numpy as np
import pandas as pd
# 返回rfile中域名的特征向量KMeans聚类结果
# 每行格式:[域名, KMeans聚类簇编号]
def getFeatureVector(rfile):
fv = []
with io.open(rfile, "r") as f:
for line in f.readlines():
fv.append(eval(line))
return fv
# 返回rfile中域名之间编辑距离的DBScan聚类结果
# 每行格式:[域名, DBScan聚类簇编号]
def getLev... | Python | zaydzuhri_stack_edu_python |
for line in fh
begin
if starts with line string X-DSPAM-Confidence:
begin
set r = r + 1
set pos = find line string :
set number = line at slice pos + 1 : :
set num = strip number
set n = decimal num
set s = s + n
end
end
print string Average spam confidence: s / r | for line in fh:
if line.startswith("X-DSPAM-Confidence:") :
r=r+1
pos=line.find(':')
number=line[pos+1:]
num=number.strip()
n=float(num)
s=s+n
print('Average spam confidence:',s/r)
| Python | zaydzuhri_stack_edu_python |
import numpy
import math
import constants
from decorators import lazyproperty
class Atom extends object
begin
function __init__ self species index position label=none
begin
set _species = species
set _index = integer index
set _position = array position
if label is not none
begin
set _label = label
end
else
begin
set _... | import numpy
import math
import constants
from decorators import lazyproperty
class Atom(object):
def __init__(self, species, index, position, label=None):
self._species = species
self._index = int(index)
self._position = numpy.array(position)
if label is not None:
self._label = label
e... | Python | zaydzuhri_stack_edu_python |
for i in range T
begin
set n = integer input
set k = 3 * n * n + 1 / 2 - n
set k = k % 1000007
print integer k
end | for i in range(T):
n=int(input())
k = 3 * ((n * (n + 1))/2) - n;
k = k % 1000007;
print(int(k))
| Python | zaydzuhri_stack_edu_python |
comment main libraries
import numpy as np
import pandas as pd
set max_columns = none
set width = none
set movies = copy read csv string exportedData/moviesExp.csv
set ratings = copy read csv string exportedData/ratingsExp.csv
set tags = copy read csv string exportedData/tagsExp.csv
set movies = call DataFrame dict stri... | #main libraries
import numpy as np
import pandas as pd
pd.options.display.max_columns = None
pd.options.display.width=None
movies = pd.read_csv("exportedData/moviesExp.csv").copy()
ratings = pd.read_csv("exportedData/ratingsExp.csv").copy()
tags = pd.read_csv("exportedData/tagsExp.csv").copy()
movies = pd.D... | Python | zaydzuhri_stack_edu_python |
function _create_examples self lines set_type
begin
set examples = list
for tuple i line in enumerate lines
begin
set guid = string %s-%s % tuple set_type i
if set_type == string augm
begin
if type line is not str
begin
set text_a = line at 0 at 0
end
else
begin
set text_a = line at 0
end
set label = line at 1
end
els... | def _create_examples(self, lines, set_type):
examples = []
for (i, line) in enumerate(lines):
guid = "%s-%s" % (set_type, i)
if set_type == "augm":
if type(line) is not str:
text_a = line[0][0]
else:
text_a =... | Python | nomic_cornstack_python_v1 |
function build_tag_uri app date resource identifier
begin
set tuple host path = url parse cfg at string blog_url at slice 1 : 3 :
if string : in host
begin
set host = split host string : 1 at 0
end
set path = strip path string /
if path
begin
set path = string , + path
end
if not is instance identifier basestring
begi... | def build_tag_uri(app, date, resource, identifier):
host, path = urlparse(app.cfg['blog_url'])[1:3]
if ':' in host:
host = host.split(':', 1)[0]
path = path.strip('/')
if path:
path = ',' + path
if not isinstance(identifier, basestring):
identifier = str(identifier)
retu... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import cv2
import knn
import os
import os.path
import numpy as np
set cap = call VideoCapture 0
set tuple ret frame = read cap
set prediction = string n.a.
function color_histogram_of_test_image test_src_image
begin
comment load gambar dari frame
set image = test_src_image
set chans = split cv2... | #!/usr/bin/python
import cv2
import knn
import os
import os.path
import numpy as np
cap = cv2.VideoCapture(0)
(ret, frame) = cap.read()
prediction = 'n.a.'
def color_histogram_of_test_image(test_src_image):
# load gambar dari frame
image = test_src_image
chans = cv2.split(image)
colors = ('b', 'g'... | Python | zaydzuhri_stack_edu_python |
for tuple x y z in zip a b c
begin
print x y z
end
print list zip range 3 string ABC
print list zip range 3 string ABC list 0.0 1.1 2.2 3.3
from itertools import zip_longest
print list call zip_longest range 3 string ABC list 0.0 1.1 2.2 3.3
print list call zip_longest range 3 string ABC list 0.0 1.1 2.2 3.3 fillvalue=... | for x, y, z in zip(a, b, c):
print(x, y ,z)
print(list(zip(range(3), 'ABC')))
print(list(zip(range(3), 'ABC', [0.0, 1.1, 2.2, 3.3])))
from itertools import zip_longest
print(list(zip_longest(range(3), 'ABC', [0.0, 1.1, 2.2, 3.3])))
print(list(zip_longest(range(3), 'ABC', [0.0, 1.1, 2.2, 3.3], fillvalue=-1))) | Python | zaydzuhri_stack_edu_python |
comment 测试异常捕获处理
while true
begin
try
begin
set num = integer input string please you input:
if num == 123
begin
raise call ValueError string value
end
end
except ValueError
begin
print string value type error!
break
end
end | #测试异常捕获处理
while True:
try:
num = int(input("please you input:"))
if num == 123:
raise ValueError("value ")
except ValueError:
print("value type error!")
break | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
comment author : zhangdawang
comment data: 2017-5-18
comment difficulty degree:
comment problem: 290_Word_Pattern
comment time_complecity:
comment space_complecity:
comment beats:
class Solution extends object
begin
function wordPattern self pattern str
begin
set s... | #!/usr/bin/python
# -*- coding: utf-8 -*-
#author : zhangdawang
#data: 2017-5-18
#difficulty degree:
#problem: 290_Word_Pattern
#time_complecity:
#space_complecity:
#beats:
class Solution(object):
def wordPattern(self, pattern, str):
s = str.split(" ")
ls, lt = len(s), len(pattern)
if ... | Python | zaydzuhri_stack_edu_python |
function resample proj_def data_def data fillValue resampleRad
begin
info string Resampling the data to target projection grid
set data_con = call ImageContainerNearest data data_def radius_of_influence=resampleRad fill_value=fillValue nprocs=2
set image_con = call resample proj_def
set resampled_data = image_data
retu... | def resample(proj_def, data_def, data, fillValue, resampleRad):
log.info("Resampling the data to target projection grid")
data_con = image.ImageContainerNearest(data, data_def,
radius_of_influence=resampleRad,
fill_valu... | Python | nomic_cornstack_python_v1 |
function convert_data_type data
begin
if data == string
begin
return data
end
else
begin
return decimal data
end
end function | def convert_data_type(data: str) -> Union[str, float]:
if data == '':
return data
else:
return float(data) | Python | nomic_cornstack_python_v1 |
function predict_note_file
begin
set df_test = read csv get files string file
set X = iloc at tuple slice : : slice : - 1 :
set prediction = predict classifier X
return string The prediction values for the csv is + string list prediction
end function | def predict_note_file():
df_test = pd.read_csv(request.files.get("file"))
X = df_test.iloc[:, :-1]
prediction = classifier.predict(X)
return "The prediction values for the csv is" + str(list((prediction))) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
import numpy as np
import scipy as scipy
import matplotlib.pyplot as plt
import scipy.constants as const
from scipy.signal import find_peaks
import uncertainties.unumpy as unp
from uncertainties.unumpy import nominal_values as noms , std_devs as stds
cal... | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
import scipy as scipy
import matplotlib.pyplot as plt
import scipy.constants as const
from scipy.signal import find_peaks
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
plt.rc('font',... | Python | zaydzuhri_stack_edu_python |
comment this is dummy in pyjs
import pyjd
from pyjamas.ui.Button import Button
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Label import Label
from pyjamas.ui.Grid import Grid
from pyjamas.ui.HTML import HTML
from pyjamas.ui.AbsolutePanel import AbsolutePanel
from pyjamas.Timer import Timer
from pyjamas.u... | import pyjd # this is dummy in pyjs
from pyjamas.ui.Button import Button
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Label import Label
from pyjamas.ui.Grid import Grid
from pyjamas.ui.HTML import HTML
from pyjamas.ui.AbsolutePanel import AbsolutePanel
from pyjamas.Timer import Timer
from pyjamas.ui.CSS... | Python | zaydzuhri_stack_edu_python |
function click_managehh_button self title
begin
set locator = format eda_lex_locators at string manage_hh_page at string button title
call click
end function | def click_managehh_button(self, title):
locator = eda_lex_locators["manage_hh_page"]["button"].format(title)
self.selenium.get_webelement(locator).click() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment Duan Yi
comment 2013.7.26
import os , sys
function get_param
begin
set param = tuple
end function | #!/usr/bin/env python
# Duan Yi
# 2013.7.26
import os,sys
def get_param():
param = () | Python | zaydzuhri_stack_edu_python |
string Flowblade Movie Editor is a nonlinear video editor. Copyright 2012 Janne Liljeblad. This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>. Flowblade Movie Editor is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by... | """
Flowblade Movie Editor is a nonlinear video editor.
Copyright 2012 Janne Liljeblad.
This file is part of Flowblade Movie Editor <http://code.google.com/p/flowblade>.
Flowblade Movie Editor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public Lice... | Python | zaydzuhri_stack_edu_python |
class Kwadrat
begin
function __init__ self bok
begin
set bok = bok
end function
function sketch self x y
begin
set x = x
set y = y
call rect x y bok bok
end function
end class
class PasiastyKwadrat extends Kwadrat
begin
function sketchPasiasty self x y paski
begin
call sketch self x y
set space = bok / paski
set _xLini... | class Kwadrat():
def __init__(self, bok):
self.bok = bok
def sketch(self, x, y):
self.x = x
self.y = y
rect(self.x, self.y, self.bok, self.bok)
class PasiastyKwadrat(Kwadrat):
def sketchPasiasty(self, x, y, paski):
Kwadrat.sketch(self, x, y)
... | Python | zaydzuhri_stack_edu_python |
function get_column_sizes self
begin
set column_sizes = list 0 * length column_names
set all_rows = rows + list column_names
for row in all_rows
begin
for tuple index col in enumerate row
begin
set column_sizes at index = max column_sizes at index length string col
end
end
return column_sizes
end function | def get_column_sizes(self):
column_sizes = [0] * len(self.column_names)
all_rows = self.rows + [self.column_names]
for row in all_rows:
for index, col in enumerate(row):
column_sizes[index] = max(column_sizes[index], len(str(col)))
return column_sizes | Python | nomic_cornstack_python_v1 |
function writing cls path data_or_source data_template=none version=2 compression=0 nbits=none
begin
set self = call __new__ cls
if is instance data_or_source ndarray
begin
set _set_data = call asfortranarray data_or_source
set array = call asfortranarray data_or_source
end
else
if is instance data_or_source tuple str ... | def writing(cls, path, data_or_source, data_template=None, *,
version=2, compression=0, nbits=None):
self = object.__new__(cls)
if isinstance(data_or_source, np.ndarray):
self._set_data = array = np.asfortranarray(data_or_source)
elif isinstance(data_or_source, (str, ... | Python | nomic_cornstack_python_v1 |
function _save_pickle path data
begin
from joblib import dump
return dump data path
end function | def _save_pickle(path, data):
from joblib import dump
return dump(data, path) | Python | nomic_cornstack_python_v1 |
string Input a file id and a parent id Create a copy and modify its parent id Return it id
from get_creds import *
function copy_file file_id parent_id file_name
begin
set body = dict string name file_name
set body at string parents = list parent_id
set copy_id = execute copy call files fileId=file_id body=body
return ... | """
Input a file id and a parent id
Create a copy and modify its parent id
Return it id
"""
from get_creds import *
def copy_file(file_id, parent_id, file_name):
body = {'name': file_name}
body['parents'] = [parent_id]
copy_id = DRIVE.files().copy(fileId=file_id, body=body).execute()
retur... | Python | zaydzuhri_stack_edu_python |
comment !/usr/local/bin/python3
import psycopg2
import psycopg2.extras
import json
from utils import *
import re
set connection = call connect string dbname=theoaracle user=sebastian
set cursor = call cursor cursor_factory=DictCursor
comment New Stuff
execute cursor string select name, boattype, weight, gender, race, l... | #!/usr/local/bin/python3
import psycopg2
import psycopg2.extras
import json
from utils import *
import re
connection = psycopg2.connect("dbname=theoaracle user=sebastian")
cursor = connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
# New Stuff
cursor.execute('''select name, boattype, weight, gender, race,... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python
import io
import random
import numpy
import tensorflow as tf
import sys
from PIL import Image , ImageOps
from ai import BernardAi
from network import *
from train import split_data_set
function create_training_set path
begin
string Transforme le fichier de données en dictionnaire de données data_se... | #!/bin/python
import io
import random
import numpy
import tensorflow as tf
import sys
from PIL import Image, ImageOps
from ai import BernardAi
from network import *
from train import split_data_set
def create_training_set(path):
"""
Transforme le fichier de données en dictionnaire de données
data_set[... | Python | zaydzuhri_stack_edu_python |
import yfinance as yf
import streamlit as st
import pandas as pd
write st string # Stock Price Web App Shown are the stock **closing** price of Tesla for the past decade
set tickerSymbol = string TSLA
set tickerData = call Ticker tickerSymbol
set tickerOf = call history period=string 1d start=string 2010-12-31 end=stri... | import yfinance as yf
import streamlit as st
import pandas as pd
st.write("""
# Stock Price Web App
Shown are the stock **closing** price of Tesla for the past decade
""")
tickerSymbol = "TSLA"
tickerData = yf.Ticker(tickerSymbol)
tickerOf = tickerData.history(period="1d", start="2010-12-31", end="2021-1-1")
st.li... | Python | zaydzuhri_stack_edu_python |
function get_manhole_factory namespace **passwords
begin
string Get a Manhole Factory
set realm = call TerminalRealm
set protocolFactory = lambda _ -> call EnhancedColoredManhole namespace
set p = call Portal realm
call registerChecker call InMemoryUsernamePasswordDatabaseDontUse keyword passwords
return call ConchFact... | def get_manhole_factory(namespace, **passwords):
"""Get a Manhole Factory
"""
realm = manhole_ssh.TerminalRealm()
realm.chainedProtocolFactory.protocolFactory = (
lambda _: EnhancedColoredManhole(namespace)
)
p = portal.Portal(realm)
p.registerChecker(
checkers.InMemoryUser... | Python | jtatman_500k |
comment Author:Aliex ZJ
comment !/usr/bin/env python3
comment -*- coding:utf-8 -*-
comment 获取街道代码函数---多线程实现
from threading import Thread
import time
from lxml import etree
from queue import Queue
from Yadea.national_province_city.Prases.urlUtils import getUrl
function getTown url_list
begin
comment 队列
set queue_town = ... | # Author:Aliex ZJ
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# 获取街道代码函数---多线程实现
from threading import Thread
import time
from lxml import etree
from queue import Queue
from Yadea.national_province_city.Prases.urlUtils import getUrl
def getTown(url_list):
queue_town = Queue() #队列
thread_num = 20 #进程数
... | Python | zaydzuhri_stack_edu_python |
function get_preferences wallet_id for_login=false network=none
begin
if network not in tuple none string mainnet string testnet string regtest
begin
raise exception string Invalid network parameter setting
end
if for_login and network is none
begin
raise exception string network parameter required if for_login is set
... | def get_preferences(wallet_id, for_login=False, network=None):
if network not in (None, 'mainnet', 'testnet', 'regtest'):
raise Exception("Invalid network parameter setting")
if for_login and network is None:
raise Exception("network parameter required if for_login is set")
result = config.... | Python | nomic_cornstack_python_v1 |
string Created on Mar 7, 2017 @author: Robert
import pygame , os
comment @UndefinedVariable
call init
set screen = call set_mode tuple 500 500
set CLOCK = call Clock
set DONE = false
set imageDict = dict string image1 call convert ; string image2 call convert
set image = call convert
while not DONE
begin
for event in g... | '''
Created on Mar 7, 2017
@author: Robert
'''
import pygame, os
pygame.init() # @UndefinedVariable
screen = pygame.display.set_mode((500,500))
CLOCK = pygame.time.Clock()
DONE = False
imageDict = {
'image1': pygame.image.load(os.path.realpath('')+'\\dir_image\\ball.png').convert(),
'image2': pygame.ima... | Python | zaydzuhri_stack_edu_python |
from scripts.mapgen.map import Map
from scripts.mapgen.draw import Draw
from scripts.mapgen.floor_generator import floor_generator
from time import time
set generate = 10
set start = time
for i in range generate
begin
set test = map string test + string i + 1 100 60
set floor_center = test at string center
call add_roo... | from scripts.mapgen.map import Map
from scripts.mapgen.draw import Draw
from scripts.mapgen.floor_generator import floor_generator
from time import time
generate = 10
start = time()
for i in range(generate):
test = Map('test' + str(i + 1), 100, 60)
floor_center = test['center']
test.add_room(floor_center,... | Python | zaydzuhri_stack_edu_python |
string Unit Test for Assignment A3 This module implements several test cases for a3. It is complete. You should look though this file for places to add tests. Magd Bayoumi mb2363 Junghwan (Peter) Oh jo299 October 2, 2017
import cornell
import a3
function test_complement
begin
string Test function complement
call assert... | """
Unit Test for Assignment A3
This module implements several test cases for a3. It is complete. You should look
though this file for places to add tests.
Magd Bayoumi mb2363
Junghwan (Peter) Oh jo299
October 2, 2017
"""
import cornell
import a3
def test_complement():
"""
Test function complement
... | Python | zaydzuhri_stack_edu_python |
function parse_config_file filename
begin
set config = dict string TREES dict ; string ALIASES dict
try
begin
set config = call _load_python_file filename config
end
except SyntaxError as e
begin
raise exception string Syntax error in config file: %s Line %i offset %i % tuple filename lineno offset
end
return diction... | def parse_config_file(filename):
config = {
'TREES': {},
'ALIASES': {},
}
try:
config = _load_python_file(filename, config)
except SyntaxError as e:
raise Exception('Syntax error in config file: %s\n'
'Line %i offset %i\n'
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
from sklearn import datasets , svm
from sklearn.metrics.pairwise import rbf_kernel
comment Data
set d = 2
set N = 200
set tuple X y = call make_moons n_samples=N noise=0.1 random_state=1
set I = call argsort
set tuple X y = tuple X at I y at ... | import numpy as np
import numpy.random as npr
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.metrics.pairwise import rbf_kernel
## Data
d = 2
N = 200
X, y = datasets.make_moons(n_samples=N, noise=.1, random_state=1)
I = y.argsort()
X, y = X[I], y[I]
## Kernels
sigma2 = 0.5
gamma = ... | Python | zaydzuhri_stack_edu_python |
function set_config variable value
begin
if _TRAFFICCTL
begin
set cmd = call _traffic_ctl string config string set variable value
end
else
begin
set cmd = call _traffic_line string -s variable string -v value
end
debug string Setting %s to %s variable value
return call _subprocess cmd
end function | def set_config(variable, value):
if _TRAFFICCTL:
cmd = _traffic_ctl("config", "set", variable, value)
else:
cmd = _traffic_line("-s", variable, "-v", value)
log.debug("Setting %s to %s", variable, value)
return _subprocess(cmd) | Python | nomic_cornstack_python_v1 |
function show_port_forwarding self floatingip_id port_forwarding_id **fields
begin
set uri = string /floatingips/%s/port_forwardings/%s % tuple floatingip_id port_forwarding_id
return call show_resource uri keyword fields
end function | def show_port_forwarding(
self, floatingip_id, port_forwarding_id, **fields):
uri = '/floatingips/%s/port_forwardings/%s' % (
floatingip_id, port_forwarding_id)
return self.show_resource(uri, **fields) | Python | nomic_cornstack_python_v1 |
import sys
class Solution extends object
begin
function restoreIpAddresses self s
begin
string :type s: str :rtype: List[str]
set count = 0
call dfs s list count
return count
end function
function dfs self s path count
begin
if length s > 4 - length path * 3
begin
return
end
if not s and length path == 4
begin
set cou... | import sys
class Solution(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
self.count = 0
self.dfs(s, [], self.count)
return self.count
def dfs(self, s, path, count):
if len(s) > (4 - len(path)) * 3:
ret... | Python | zaydzuhri_stack_edu_python |
function _parse_has_year self doc
begin
if string xml in keys doc
begin
set doc = call fromstring doc at string xml
set article = find find find doc string PubmedArticle string MedlineCitation string Article
return boolean find article string ArticleDate and find article string ArticleDate is not none and text
end
else... | def _parse_has_year(self, doc):
if 'xml' in doc.keys():
doc = ET.fromstring(doc['xml'])
article = doc.find('PubmedArticle').find('MedlineCitation').find('Article')
return bool(article.find('ArticleDate') and article.find('ArticleDate') is not None and article.find('ArticleDat... | Python | nomic_cornstack_python_v1 |
function optimize_bcj_classical verb=true
begin
set time = classical_time_bcj
set objective = time
set mycons = constraints_bcj_classical
set start = list - 0.2 * 3 + list 0.2 * 10
set bounds = list tuple - 1 0 * 3 + list tuple 0 1 * 10
set result = minimize time start bounds=bounds tol=1e-10 constraints=mycons options... | def optimize_bcj_classical(verb=True):
time = classical_time_bcj
objective = time
mycons = constraints_bcj_classical
start = [(-0.2)]*3 + [(0.2)]*10
bounds = [(-1,0)]*3 + [(0,1)]*10
result = opt.minimize(time, start,
bounds= bounds, tol=1e-10,
constraints=myc... | Python | nomic_cornstack_python_v1 |
function relu_forward x
begin
set out = none
comment TODO: Implement the ReLU forward pass. #
set out = call maximum 0 x
comment END OF YOUR CODE #
set cache = x
return tuple out cache
end function | def relu_forward(x):
out = None
#############################################################################
# TODO: Implement the ReLU forward pass. #
#############################################################################
out = np.maximum(0,x)
#################... | Python | nomic_cornstack_python_v1 |
import os
print string Process %s start... % call getpid
set fork_PID = call fork
if fork_PID == 0
begin
print string 当前进程: %s, 父进程: %s, fork_PID: %s % tuple call getpid call getppid fork_PID
end
else
begin
print string 当期进程: %s, 创建了子进程: %s % tuple call getpid fork_PID
end | import os
print('Process %s start...' % os.getpid())
fork_PID = os.fork()
if fork_PID == 0:
print('当前进程: %s, 父进程: %s, fork_PID: %s' % (os.getpid(), os.getppid(), fork_PID))
else:
print('当期进程: %s, 创建了子进程: %s' % (os.getpid(), fork_PID))
| Python | zaydzuhri_stack_edu_python |
from turtle import Turtle
import random
class Food extends Turtle
begin
function __init__ self
begin
call __init__
call pu
call shape string circle
call color string aqua
call speed string fastest
call shapesize 0.5 0.5
set x = random integer - 280 280
set y = random integer - 280 280
call goto x y
end function
end cla... | from turtle import Turtle
import random
class Food(Turtle):
def __init__(self):
super().__init__()
self.pu()
self.shape("circle")
self.color("aqua")
self.speed("fastest")
self.shapesize(0.5, 0.5)
x = random.randint(-280, 280)
y = random.randint(-280... | Python | zaydzuhri_stack_edu_python |
string This is not meant to be used directly as an object, but serves as a abstract parent object for various state-search-problem representations. Your search algorithms will use StateNode objects, making them generalizable for all kinds of problems.
class StateNode
begin
string A 'static' method that reads data from ... | """
This is not meant to be used directly
as an object, but serves as a abstract parent object for various
state-search-problem representations.
Your search algorithms will use StateNode objects, making them generalizable
for all kinds of problems.
"""
class StateNode:
"""
A 'static' method that reads data fr... | Python | zaydzuhri_stack_edu_python |
function deletedata self uid
begin
return call deleteemail uid
end function | def deletedata(self, uid):
return self.deleteemail(uid) | Python | nomic_cornstack_python_v1 |
function determineClasses self particles
begin
call printMsg string sorting refineparticledata into classes
set t0 = time
set classes = dict
set class_stats = dict
set quality = zeros length particles
for partnum in range length particles
begin
set quality at partnum = particles at partnum at string quality_factor
se... | def determineClasses(self, particles):
apDisplay.printMsg("sorting refineparticledata into classes")
t0 = time.time()
classes={}
class_stats={}
quality=numpy.zeros(len(particles))
for partnum in range(len(particles)):
quality[partnum] = particles[partnum]['quality_factor']
key = ("%.3f_%.3f"%(particle... | Python | nomic_cornstack_python_v1 |
function enrich_frontend_data area=none **data
begin
try
begin
set data at string area = area
end
except KeyError
begin
pass
end
update data DASHBOARD_DATA
return data
end function | def enrich_frontend_data(area=None, **data):
try:
data["area"] = area
except KeyError:
pass
data.update(DASHBOARD_DATA)
return data | 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.