code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function insert_postmod_token sentence post_modifier
begin
if post_modifier not in sentence
begin
set msg = string Post-modifier "%s" does not occur in sentence "%s"
set msg = msg % tuple post_modifier sentence
raise call ValueError msg
end
set output = replace sentence post_modifier string <postmod>
return output
end ... | def insert_postmod_token(sentence, post_modifier):
if post_modifier not in sentence:
msg = 'Post-modifier "%s" does not occur in sentence "%s"'
msg = msg % (post_modifier, sentence)
raise ValueError(msg)
output = sentence.replace(post_modifier, '<postmod>')
return output | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
comment Define function. Four variables: one dependent (t)
set x = lambda amp omega t phi -> amp * sin omega * t - phi
comment Set spring constant and mass for our "generator"
set k = 10
set m = 2
set omega = square root k / m
set time_for_two = 4 * pi / omega
set phi_... | import numpy as np
import matplotlib.pyplot as plt
# Define function. Four variables: one dependent (t)
x = lambda amp, omega, t, phi: amp*np.sin(omega*t - phi)
# Set spring constant and mass for our "generator"
k = 10
m = 2
omega = np.sqrt(k/m)
time_for_two = 4*np.pi/omega
phi_deg = 60
amplitude = 5
# Set time doma... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
from random import randint
with open string /usr/share/dict/words string rt as f
begin
set words = list comprehension strip w for w in f
set random_words = list comprehension words at random integer 0 length words for i in range 0 100
end | #!/usr/bin/python
from random import randint
with open("/usr/share/dict/words","rt") as f:
words = [ w.strip() for w in f ]
random_words = [ words[randint(0,len(words))] for i in range(0,100)]
| Python | zaydzuhri_stack_edu_python |
function extendFCPDomain storage_domain host lun override_luns=none
begin
return call extendStorageDomain true storagedomain=storage_domain lun=lun host=host storage_type=ENUMS at string storage_type_fcp override_luns=override_luns
end function | def extendFCPDomain(storage_domain, host, lun, override_luns=None):
return ll_sd.extendStorageDomain(
True, storagedomain=storage_domain, lun=lun, host=host,
storage_type=ENUMS['storage_type_fcp'], override_luns=override_luns) | Python | nomic_cornstack_python_v1 |
function laplace_ode_1d Nparams a=1.0 b=1.0 abar=3.0 N=100
begin
set abarfun = lambda x -> abar * ones call shape x
set KLE = call KLE_exponential_covariance_1d Nparams a b abarfun
set diffusion = lambda x p -> call KLE x p
set x = call laplace_grid_x - b b N
return tuple x call laplace_ode left=- b right=b N=N diffusi... | def laplace_ode_1d(Nparams, a=1., b=1., abar=3., N=100):
abarfun = lambda x: abar*np.ones(np.shape(x))
KLE = KLE_exponential_covariance_1d(Nparams, a, b, abarfun)
diffusion = lambda x, p: KLE(x, p)
x = laplace_grid_x(-b, b, N)
return x, laplace_ode(left=-b, right=b, N=N, diffusion=diffusion) | Python | nomic_cornstack_python_v1 |
for i in range 1 5
begin
for j in range 1 5
begin
if k <= i
begin
print k end=string
end
else
begin
print string end=string
end
set k = k - 1
end
print string
set k = 4
end | for i in range(1,5):
for j in range(1,5):
if k<=i:
print(k,end=" ")
else:
print(" ",end=" ")
k-=1
print("")
k=4
| Python | zaydzuhri_stack_edu_python |
function sol
begin
set tuple startX startY endX endY T V = map int split input
set N = integer input
set girls = list
for _ in range N
begin
set tuple a b = map int split input
append girls tuple a b
end
function dist a b x y
begin
return a - x ^ 2 + b - y ^ 2 ^ 0.5
end function
for tuple a b in girls
begin
if call di... | def sol():
startX, startY, endX, endY, T, V = map(int, input().split())
N = int(input())
girls = []
for _ in range(N):
a, b = map(int, input().split())
girls.append((a, b))
def dist(a, b, x, y):
return ((a - x)**2 + (b - y)**2)**0.5
for a, b in girls:
if dist(s... | Python | zaydzuhri_stack_edu_python |
function extract_last_hidden_state_batched hidden_state lengths bidirectional
begin
set tuple bs seq_len hidden_size = size hidden_state
assert bs == length lengths
assert hidden_size % 2 == 0
set split_point = hidden_size // 2
set length_v = stack lengths dim=0
if bidirectional
begin
set last_idx = call expand bs 1 sp... | def extract_last_hidden_state_batched(hidden_state, lengths, bidirectional):
bs, seq_len, hidden_size = hidden_state.size()
assert bs == len(lengths)
assert hidden_size % 2 == 0
split_point = hidden_size // 2
length_v = torch.stack(lengths, dim=0)
if bidirectional:
last_idx = (length_v ... | Python | nomic_cornstack_python_v1 |
function remove_content_history self page_id version_number
begin
string Remove content history. It works as experimental method :param page_id: :param version_number: version number :return:
set url = format string rest/experimental/content/{id}/version/{versionNumber} id=page_id versionNumber=version_number
delete ur... | def remove_content_history(self, page_id, version_number):
"""
Remove content history. It works as experimental method
:param page_id:
:param version_number: version number
:return:
"""
url = 'rest/experimental/content/{id}/version/{versionNumber}'.format(id=page_... | Python | jtatman_500k |
function xsize self
begin
return call Size_xsize self
end function | def xsize(self):
return _ilwisobjects.Size_xsize(self) | Python | nomic_cornstack_python_v1 |
function machine_learning self
begin
return get pulumi self string machine_learning
end function | def machine_learning(self) -> pulumi.Output[Optional['outputs.AzureIntegrationsMachineLearning']]:
return pulumi.get(self, "machine_learning") | Python | nomic_cornstack_python_v1 |
function delete_tag missing_ok=false
begin
set resource_id = call _resource_argument resource
try
begin
call delete_tag resource_id key
end
except TagNotFoundError
begin
if not missing_ok
begin
raise
end
end
end function | def delete_tag(
self, resource: ResourceInput, key: str, /, missing_ok: bool = False
) -> None:
resource_id = _resource_argument(resource)
try:
self._storage.delete_tag(resource_id, key)
except TagNotFoundError:
if not missing_ok:
raise | Python | nomic_cornstack_python_v1 |
function raise_val n
begin
string resturn the n raise
function inner x
begin
return x ^ n
end function
return inner
end function
set square = call raise_val 2
set cube = call raise_val 3
print call square 10 call cube 6 | def raise_val(n):
'''resturn the n raise'''
def inner(x):
return x**n
return inner
square=raise_val(2)
cube= raise_val(3)
print(square(10),cube(6))
| Python | zaydzuhri_stack_edu_python |
function posts self limit=100 all=false
begin
set tuple source edge = tuple id string feed
return call lazygen Post source edge limit=limit get_all=all
end function | def posts(self, limit=100, all=False):
source, edge = self.id, "feed"
return lazygen(Post, source, edge,
limit=limit, get_all=all) | Python | nomic_cornstack_python_v1 |
while true
begin
set req = get requests string https://api.coindesk.com/v1/bpi/currentprice/USD.json
set dataNew = json req
set timeT = split split dataNew at string time at string updated at 3 string :
set absTime = integer timeT at 0 * 60 + integer timeT at 1
set data at string latest = absTime
append data at string ... | while True:
req = requests.get('https://api.coindesk.com/v1/bpi/currentprice/USD.json')
dataNew = req.json()
timeT = (dataNew['time']['updated'].split())[3].split(':')
absTime = (int(timeT[0]) * 60) + int(timeT[1])
data['latest'] = absTime
data['price'].append(dataNew['bpi']['USD']['rate_float']... | Python | zaydzuhri_stack_edu_python |
function get_sent self line
begin
set sent = list
for word in split line
begin
if word in vocab
begin
append sent word
end
else
begin
append sent unk
end
end
return sent
end function | def get_sent(self, line):
sent = []
for word in line.split():
if word in self.vocab:
sent.append(word)
else:
sent.append(self.unk)
return sent | Python | nomic_cornstack_python_v1 |
function cmp o1 o2
begin
set o1 = string o1
set o2 = string o2
set a = o1 + o2
set b = o2 + o1
if a > b
begin
return 1
end
else
if a == b
begin
return 0
end
else
begin
return - 1
end
end function | def cmp(o1, o2):
o1 = str(o1)
o2 = str(o2)
a = o1 + o2
b = o2 + o1
if a > b:
return 1
elif a == b:
return 0
else:
return -1 | Python | nomic_cornstack_python_v1 |
comment append and extend method
comment list = []
comment list.append(45)
comment print(list)
comment list.append(787)
comment print(list)
comment nums = [1, 2, 3]
comment nums.append(nums[:])
comment print(nums)
comment list1 = [2,3]
comment list1.append(3)
comment list1.append([1,2])
comment list1.append([5,6,7,8])
... | # append and extend method
# list = []
# list.append(45)
# print(list)
# list.append(787)
# print(list)
# nums = [1, 2, 3]
# nums.append(nums[:])
# print(nums)
# list1 = [2,3]
# list1.append(3)
# list1.append([1,2])
# list1.append([5,6,7,8])
# list1.append((12,13))
# print(list1)
# output - [2, 3, 3, [1, 2], [5, 6, ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Dec 24 14:53:29 2018 @author: Rohit_V03
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
set df = read csv string housing.csv
head df 5
from sklearn.model_selection import train_test_split
set tuple X_train X_test y_train y_... | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 24 14:53:29 2018
@author: Rohit_V03
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('housing.csv')
df.head(5)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = trai... | Python | zaydzuhri_stack_edu_python |
from google.cloud import storage
import subprocess
import sys
function formatCmd file config
begin
set cmd = string gsutil cp + string gs:// + config at string bucketName
set cmd = cmd + string / + file
set cmd = cmd + string /tmp
return cmd
end function
function copyFiles config
begin
string We store the Enhanced MNIS... | from google.cloud import storage
import subprocess
import sys
def formatCmd(file, config):
cmd = "gsutil cp "+"gs://"+config["bucketName"]
cmd += "/"+file
cmd += " /tmp"
return cmd
def copyFiles(config):
''' We store the Enhanced MNIST data on GCloud Storage. Copy it to /tmp to be processed '''
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string .. module:: FileFormat :platform: Unix, Windows :synopsis: Represent File Format enumeration. .. moduleauthor:: Nadith Pathirage <chathurdara@gmail.com>
comment Global Imports
from enum import Enum
comment Local Imports
class FileFormat extends Enum
begin
string FORMAT Enumeration d... | # -*- coding: utf-8 -*-
"""
.. module:: FileFormat
:platform: Unix, Windows
:synopsis: Represent File Format enumeration.
.. moduleauthor:: Nadith Pathirage <chathurdara@gmail.com>
"""
# Global Imports
from enum import Enum
# Local Imports
class FileFormat(Enum):
"""FORMAT Enumeration describes the file ... | Python | zaydzuhri_stack_edu_python |
class WS2813_strip
begin
string Class to represent the strip itself
function __init__ self SPI_driver LED_data
begin
comment this is the spi driver object, instantiated
set _SPI_driver = call SPI_driver
comment have this be another object which represents the LED data
set _LED_data = call LED_data 82
end function
funct... | class WS2813_strip:
"""
Class to represent the strip itself
"""
def __init__(self, SPI_driver, LED_data):
self._SPI_driver = SPI_driver() # this is the spi driver object, instantiated
self._LED_data = LED_data(82) # have this be another object which represents the LED data
def rende... | Python | zaydzuhri_stack_edu_python |
with open string input.txt as f
begin
set data = split read f string
end
for j in range length data
begin
set i = 0
set acc = 0
set seen = set
set data_copy = list data
set current_line = data_copy at j
set correct = true
if string jmp in current_line
begin
set current_line = replace current_line string jmp string nop
... | with open("input.txt") as f:
data = f.read().split("\n")
for j in range(len(data)):
i = 0
acc = 0
seen = set()
data_copy = list(data)
current_line = data_copy[j]
correct = True
if "jmp" in current_line:
current_line = current_line.replace("jmp", "nop")
data_copy[j] = cu... | Python | zaydzuhri_stack_edu_python |
import correctingagent.world.rules
from correctingagent.pddl import pddl_functions
from collections import namedtuple
from correctingagent.pddl.pddl_functions import PDDLState
from correctingagent.world import goals
from pythonpddl.pddl import Problem
from correctingagent.util.colour_dict import colour_dict
set Ruledef... | import correctingagent.world.rules
from correctingagent.pddl import pddl_functions
from collections import namedtuple
from correctingagent.pddl.pddl_functions import PDDLState
from correctingagent.world import goals
from pythonpddl.pddl import Problem
from correctingagent.util.colour_dict import colour_dict
Ruledef... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
set nombres = dict
set separador = string * * 40
set validador = false
set archivoTexto2 = open string Reporte.txt string w
function menu
begin
print string 1) Capturar 30 estudiantes
print string 2) Capturar las calificaciones de los 30 estudiantes
print string 3) Consultar las materias con menor ... | import pandas as pd
nombres = {}
separador = ("*" * 40)
validador = False
archivoTexto2 = open("Reporte.txt","w")
def menu():
print("1) Capturar 30 estudiantes")
print("2) Capturar las calificaciones de los 30 estudiantes")
print("3) Consultar las materias con menor rendimiento")
print("4) ... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
set df = read csv string cities/results_philly.csv
set df_global = read csv string cities/global_data.csv
comment df = df.fillna(0)
set df = df at list string year string city string avg_temp
set df_global = df_global at list string year string avg_temp
comment print(... | import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('cities/results_philly.csv')
df_global = pd.read_csv('cities/global_data.csv')
#df = df.fillna(0)
df = df[['year','city','avg_temp']]
df_global = df_global[['year','avg_temp']]
#print(df.head(15))
df['7-year MA'] = df.avg_temp.rolling(window=7)... | Python | zaydzuhri_stack_edu_python |
function pafs_to_onehot pafs min_pitches max_pitches
begin
set vects = list
for tuple k paf in enumerate pafs
begin
append vects call paf_to_onehot paf min_pitch=min_pitches at k max_pitch=max_pitches at k
end
return concatenate vects
end function | def pafs_to_onehot(pafs, min_pitches, max_pitches):
vects = []
for k, paf in enumerate(pafs):
vects.append(paf_to_onehot(paf, min_pitch=min_pitches[k], max_pitch=max_pitches[k]))
return np.concatenate(vects) | Python | nomic_cornstack_python_v1 |
function IsContainer self
begin
set callResult = call _Call string IsContainer
if callResult is none
begin
return none
end
return callResult
end function | def IsContainer(self):
callResult = self._Call("IsContainer", )
if callResult is None:
return None
return callResult | Python | nomic_cornstack_python_v1 |
function _import_lua_dependencies lua lua_globals
begin
import ctypes
call CDLL string liblua5.2.so mode=RTLD_GLOBAL
try
begin
set cjson = eval string require "cjson"
end
except RuntimeError
begin
raise call RuntimeError string cjson not installed
end
end function | def _import_lua_dependencies(lua, lua_globals):
import ctypes
ctypes.CDLL('liblua5.2.so', mode=ctypes.RTLD_GLOBAL)
try:
lua_globals.cjson = lua.eval('require "cjson"')
except RuntimeError:
raise RuntimeError("cjson not installed") | Python | nomic_cornstack_python_v1 |
for xa in range 1 11
begin
for xb in range 22 101
begin
print xa * xb
end
end | for xa in range(1, 11):
for xb in range(22, 101):
print(xa*xb)
| Python | zaydzuhri_stack_edu_python |
comment Problem
comment A circus tower is made of people standing on each others shoulders. However,
comment each person on top must be shorter and lighter than the person below. Given
comment a list of weights and heights, compute the largest number of people in a
comment tower with those people.
comment Work
comment ... | ###
# Problem
###
# A circus tower is made of people standing on each others shoulders. However,
# each person on top must be shorter and lighter than the person below. Given
# a list of weights and heights, compute the largest number of people in a
# tower with those people.
###
# Work
###
# Questions:
# Number of p... | Python | zaydzuhri_stack_edu_python |
function rvps_to_bed regions values track_name out_path IDs=none sep=string
begin
if IDs is none
begin
set IDs = dict
end
set ID_counter = 0
with open out_path string w as op
begin
for chromosome in regions
begin
for idx in array range shape at 0
begin
set region = regions at chromosome at tuple idx slice : :
set v... | def rvps_to_bed(regions,
values,
track_name,
out_path,
IDs = None,
sep = "\t"
):
if IDs is None:
IDs = {}
ID_counter = 0
with open(out_path,'w') as op:
for chromosome in regions:
... | Python | nomic_cornstack_python_v1 |
function __init__ cls name bases dct
begin
comment Initialize the class
call __init__ name bases dct
set BrokerCls = cls
end function | def __init__(cls, name, bases, dct):
# Initialize the class
super(MetaAQBroker, cls).__init__(name, bases, dct)
aq_store.AQStore.BrokerCls = cls | Python | nomic_cornstack_python_v1 |
function test_op_isub_offload_array_float self
begin
set device = devices at 0
set stream = call get_default_stream
set a = array range 1 4711 * 1024 dtype=float
set o = a + 1.3
set old_a = call empty_like a
set old_o = call empty_like o
set old_a at slice : : = a at slice : :
set old_o at slice : : = o at sli... | def test_op_isub_offload_array_float(self):
device = pymic.devices[0]
stream = device.get_default_stream()
a = numpy.arange(1, 4711 * 1024, dtype=float)
o = a + 1.3
old_a = numpy.empty_like(a)
old_o = numpy.empty_like(o)
old_a[:] = a[:]
old_o[:] = o[:]
... | Python | nomic_cornstack_python_v1 |
function xdraw_geodesics geodesics **kwargs
begin
set rg_geodesics = list
for g in iterate geodesics
begin
set sp = g at string start
set ep = g at string end
set srf = g at string srf
set curve = call ShortPath call Point3d *sp call Point3d *ep TOL
append rg_geodesics curve
end
return rg_geodesics
end function | def xdraw_geodesics(geodesics, **kwargs):
rg_geodesics = []
for g in iter(geodesics):
sp = g['start']
ep = g['end']
srf = g['srf']
curve = srf.ShortPath(Point3d(*sp), Point3d(*ep), TOL)
rg_geodesics.append(curve)
return rg_geodesics | Python | nomic_cornstack_python_v1 |
function run_task command **keywords
begin
from anadama2.helpers import format_command
from anadama2.helpers import sh
comment format the command to include the items for this task
set command = call format_command command keyword keywords
comment run the command
set return_code = call call sh command
return return_cod... | def run_task(command, **keywords):
from anadama2.helpers import format_command
from anadama2.helpers import sh
# format the command to include the items for this task
command=format_command(command, **keywords)
# run the command
return_code = sh(command)()
return return_code | Python | nomic_cornstack_python_v1 |
import json
from base64 import b64encode
from http.client import HTTPSConnection
comment This sets up the https connection
set c = call HTTPSConnection string jira.aspiraconnect.com
comment we need to base 64 encode it
comment and then decode it to acsii as python 3 stores it as a byte string
set userAndPass = decode b... | import json
from base64 import b64encode
from http.client import HTTPSConnection
#This sets up the https connection
c = HTTPSConnection("jira.aspiraconnect.com")
#we need to base 64 encode it
#and then decode it to acsii as python 3 stores it as a byte string
userAndPass = b64encode(b"gzhang:Pinwen@18").decode("ascii"... | Python | zaydzuhri_stack_edu_python |
comment input
set l = list string magical unicorns 19 string hello 98.98 string world
comment #output
comment "The list you entered is of mixed type"
comment "String: magical unicorns hello world"
comment "Sum: 117.98"
comment # input
comment l = [2,3,1,7,4,12]
comment #output
comment "The list you entered is of intege... | #input
l = ['magical unicorns',19,'hello',98.98,'world']
# #output
# "The list you entered is of mixed type"
# "String: magical unicorns hello world"
# "Sum: 117.98"
# # input
# l = [2,3,1,7,4,12]
# #output
# "The list you entered is of integer type"
# "Sum: 29"
# # input
# l = ['magical','unicorns']
# #output
# "The... | Python | zaydzuhri_stack_edu_python |
string Basic NN architectures
from typing import List , Optional , Callable , Union , Sequence
import tensorflow as tf
function get_dense input parameters activations kernel_initializer=call variance_scaling scale=2.0 mode=none name=string dense
begin
string Build a simple NN consisting of dense layers. Arguments: inpu... | """
Basic NN architectures
"""
from typing import List, Optional, Callable, Union, Sequence
import tensorflow as tf
def get_dense(
input: tf.Tensor,
parameters: Sequence[Union[int, float]],
activations: List[Optional[Callable[[tf.Tensor], tf.Tensor]]],
kernel_initializer: tf.keras.ini... | Python | zaydzuhri_stack_edu_python |
function created_at self
begin
return get pulumi self string created_at
end function | def created_at(self) -> Optional[str]:
return pulumi.get(self, "created_at") | Python | nomic_cornstack_python_v1 |
function is_Palindrome n
begin
set numString = string n
set strlen = length numString
for x in range 0 strlen / 2
begin
if numString at x != numString at - x + 1
begin
return false
end
end
return true
end function | def is_Palindrome(n):
numString = str(n)
strlen = len(numString)
for x in range(0, strlen/2):
if numString[x] != numString[-(x+1)]:
return False
return True
| Python | zaydzuhri_stack_edu_python |
class Pype
begin
function __init__ self raw
begin
set raw = raw
set transformed = copy raw
set _transforms = list
end function
function add self func params=none
begin
if type func is _Container
begin
set params = params
set func = func
end
append _transforms dict string f func ; string p params
set transformed = call... | class Pype:
def __init__(self, raw):
self.raw = raw
self.transformed = self.raw.copy()
self._transforms = []
def add(self, func, params=None):
if type(func) is _Container:
params = func.params
func = func.func
self._transforms.append({'f': func, '... | Python | zaydzuhri_stack_edu_python |
import socket
import json
from threading import Thread
from tkinter import *
from tkinter import messagebox
import time
set SERVER_HOST = input string Input IP:
set SERVER_PORT = integer input string Input Port:
set client = call socket AF_INET SOCK_STREAM
call connect tuple SERVER_HOST SERVER_PORT
set welcome = decode... | import socket
import json
from threading import Thread
from tkinter import *
from tkinter import messagebox
import time
SERVER_HOST = input("Input IP: ")
SERVER_PORT = int(input("Input Port: "))
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((SERVER_HOST,SERVER_PORT))
welcome = client.rec... | Python | zaydzuhri_stack_edu_python |
from typing import List
import collections
class Solution
begin
function numJewelsInStones self J S
begin
return length list comprehension x for x in S if x in J
end function
function lengthOfLongestSubstring self s
begin
string 无重复字符的最长子串 ================================== 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 !!需用滑动窗口来解决效... | from typing import List
import collections
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
return len([x for x in S if x in J])
def lengthOfLongestSubstring(self, s: str) -> int:
"""
无重复字符的最长子串
==================================
给定一个字符串,请你找出其中不含有重复字符... | Python | zaydzuhri_stack_edu_python |
function test_unload_basic self
begin
assert equal cement 300
assert equal datetime string parse time string 01.09.2017 string %d.%m.%Y
end function | def test_unload_basic(self):
self.assertEqual(self.unload.cement, 300)
self.assertEqual(
self.unload.datetime,
datetime.datetime.strptime('01.09.2017', '%d.%m.%Y'),
) | Python | nomic_cornstack_python_v1 |
comment =====================================================================
comment Script that takes the downloaded tables and analyses the number of
comment sources found in each of the cones. You can also choose an upper and
comment lower threshold for the number of sources in 2MASS and AllWISE
comment regions. Th... | # =====================================================================
# Script that takes the downloaded tables and analyses the number of
# sources found in each of the cones. You can also choose an upper and
# lower threshold for the number of sources in 2MASS and AllWISE
# regions. The program informs about the nu... | Python | zaydzuhri_stack_edu_python |
function display fun
begin
return string Hello + fun
end function
function name
begin
return string Bruno
end function
print call display call name | def display(fun):
return "Hello " + fun
def name():
return "Bruno"
print(display(name()))
| Python | zaydzuhri_stack_edu_python |
function setOffset self channel voltage
begin
write self string SOURCE%d:VOLTAGE:LEVEL:IMMEDIATE:OFFSET %f % tuple channel voltage
end function | def setOffset(self,channel,voltage):
self.write("SOURCE%d:VOLTAGE:LEVEL:IMMEDIATE:OFFSET %f" % (channel,voltage)) | Python | nomic_cornstack_python_v1 |
function download_and_combine_afq_profiles bucket study_s3_prefix=string deriv_name=none out_file=none upload=false session=none **kwargs
begin
if string subjects not in kwargs
begin
set kwargs at string subjects = string all
end
if string anon not in kwargs
begin
set kwargs at string anon = false
end
if deriv_name is... | def download_and_combine_afq_profiles(bucket,
study_s3_prefix="", deriv_name=None,
out_file=None,
upload=False, session=None,
**kwargs):
if "subjects" not in kwargs... | Python | nomic_cornstack_python_v1 |
function _set_frame_index self frame_index
begin
call _update_frame frame_index=integer frame_index
end function | def _set_frame_index(self, frame_index):
self._update_frame(frame_index=int(frame_index)) | Python | nomic_cornstack_python_v1 |
comment Issue to work on: get the menu to actually work now
from moviepy.editor import *
import pygame
function createFont t s=72 c=tuple 255 255 0 b=false i=false
begin
set font = call SysFont string Arial s bold=b italic=i
set text = call render t true c
return text
end function
function initCrawl
begin
set bg = load... | #Issue to work on: get the menu to actually work now
from moviepy.editor import *
import pygame
def createFont(t, s = 72, c = (255, 255, 0), b = False, i = False):
font = pygame.font.SysFont("Arial", s, bold = b, italic = i)
text = font.render(t, True, c)
return text
def initCrawl():
bg = pygame.image.load('Death... | Python | zaydzuhri_stack_edu_python |
string September 2014 @author: Niv Voskoboynik
import base64
import tkinter
import os
from tkinter.filedialog import askopenfilename
from fnmatch import translate
class GUI extends Frame
begin
function __init__ self master
begin
call __init__ self master
set printTextToScreen = call StringVar
set string
call pack
set c... | '''
September 2014
@author: Niv Voskoboynik
'''
import base64
import tkinter
import os
from tkinter.filedialog import askopenfilename
from fnmatch import translate
class GUI(tkinter.Frame):
def __init__(self, master):
tkinter.Frame.__init__(self, master)
self.printTextToScreen = tk... | Python | zaydzuhri_stack_edu_python |
function append_lines file lines encoding=none errors=none
begin
with open file string a encoding=encoding errors=errors as fh
begin
set cnt = write fh join string lines
set cnt = cnt + write fh string
return cnt
end
end function | def append_lines(file, lines, encoding=None, errors=None):
with open(file, 'a', encoding=encoding, errors=errors) as fh:
cnt = fh.write('\n'.join(lines))
cnt += fh.write('\n')
return cnt | Python | nomic_cornstack_python_v1 |
class threadWithReturn extends Thread
begin
function __init__ self *args **kwargs
begin
call __init__ *args keyword kwargs
set _return = none
end function
function run self
begin
if _Thread__target is not none
begin
set _return = call _Thread__target *self._Thread__args keyword _Thread__kwargs
end
end function
function... | class threadWithReturn(Thread):
def __init__(self, *args, **kwargs):
super(threadWithReturn, self).__init__(*args, **kwargs)
self._return = None
def run(self):
if self._Thread__target is not None:
self._return = self._Thread__target(*self._Thread__args, **self._Thread__kwar... | Python | jtatman_500k |
function __len__ self
begin
if df is none
begin
return 0
end
else
if length keys df == 0
begin
return 0
end
else
begin
return length df at keys df at 0
end
end function | def __len__(self):
if self.df is None:
return 0
elif len(self.df.keys()) == 0:
return 0
else:
return len(self.df[self.df.keys()[0]]) | Python | nomic_cornstack_python_v1 |
function id self id
begin
set _id = id
end function | def id(self, id):
self._id = id | Python | nomic_cornstack_python_v1 |
function _add_link self src_mac dst_mac sw_1 port_1 sw_2 port_2 graph
begin
set src_learned_switches = learned_macs at src_mac at MAC_LEARNING_SWITCH
set dst_learned_switches = learned_macs at dst_mac at MAC_LEARNING_SWITCH
set src_learned_port = get get src_learned_switches sw_1 dict MAC_LEARNING_PORT string
set dst_l... | def _add_link(self, src_mac, dst_mac, sw_1, port_1, sw_2, port_2, graph):
src_learned_switches = self.learned_macs[src_mac][MAC_LEARNING_SWITCH]
dst_learned_switches = self.learned_macs[dst_mac][MAC_LEARNING_SWITCH]
src_learned_port = src_learned_switches.get(sw_1, {}).get(MAC_LEARNING_PORT, "")... | Python | nomic_cornstack_python_v1 |
import json
import urllib3
function post_request name description price qty url
begin
string Function that send post request to crud project Arguments: name {[str]} -- [name of product] description {[str]} -- [description of product] price {[int]} -- [price of product] qty {[int]} -- [quantity of product] url {[str]} -... | import json
import urllib3
def post_request(name, description, price, qty , url):
"""Function that send post request to crud project
Arguments:
name {[str]} -- [name of product]
description {[str]} -- [description of product]
price {[int]} -- [price of product]
qty {[int]} ... | Python | zaydzuhri_stack_edu_python |
function voices self
begin
return call request method=string GET url=string /v1/voices accept_json=true
end function | def voices(self):
return self.request(method='GET', url='/v1/voices', accept_json=True) | Python | nomic_cornstack_python_v1 |
function visit_video_node_html translator node
begin
comment start the video block
set attr : List at str = list comprehension string { k } =" { node at k } " for k in SUPPORTED_OPTIONS if node at k
comment klass need to be special cased
if node at string klass
begin
set attr = attr + list string class=" { node at stri... | def visit_video_node_html(translator: SphinxTranslator, node: video_node) -> None:
# start the video block
attr: List[str] = [f'{k}="{node[k]}"' for k in SUPPORTED_OPTIONS if node[k]]
if node["klass"]: # klass need to be special cased
attr += [f"class=\"{node['klass']}\""]
html: str = f"<video ... | Python | nomic_cornstack_python_v1 |
function _init self kw
begin
pass
end function | def _init (self, kw):
pass | Python | nomic_cornstack_python_v1 |
function allocate_monitoring_cores db
begin
comment needed for populations
import pyNN.spiNNaker as p
comment using db as simulator.db_run
call set_db db
set probes = call get_probes
comment will only get the ethernet probes
set probes = list comprehension i for i in probes if i at string save_to == string eth
comment ... | def allocate_monitoring_cores(db):
import pyNN.spiNNaker as p # needed for populations
p.simulator.set_db(db) # using db as simulator.db_run
probes = db.get_probes()
probes = [ i for i in probes if i['save_to'] == 'eth' ] # will only get the ethernet probes
# creati... | Python | nomic_cornstack_python_v1 |
comment uwd - URL Watch Dog
comment To run this, install the BeautifulSoup
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
comment Ignore SSL certificate errors
set ctx = call create_default_context
set check_hostname = false
set verify_mode = CERT_NONE
comment resource = input('Enter URL: '... | # uwd - URL Watch Dog
#
# To run this, install the BeautifulSoup
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
#resource = input('Enter URL: ')
res... | Python | zaydzuhri_stack_edu_python |
import rtmidi
import time
class Midi
begin
set COLOR = 69
function __enter__ self
begin
set midiOut = call MidiOut
for port_no in range call get_port_count
begin
set port_name = call get_port_name port_no
if find port_name string Launchpad Mini MIDI 1 > - 1
begin
set midiPort = call open_port port_no
end
end
end functi... | import rtmidi
import time
class Midi:
COLOR = 69
def __enter__(self):
self.midiOut = rtmidi.MidiOut()
for port_no in range(self.midiOut.get_port_count()):
port_name = self.midiOut.get_port_name(port_no)
if port_name.find('Launchpad Mini MIDI 1') > -1:
sel... | Python | zaydzuhri_stack_edu_python |
function out_pixel_info year0=2018
begin
set info = call loadtxt string prepare_files/station_info/out_pixel_%d.txt % year0 delimiter=string ,
return info
end function | def out_pixel_info(year0=2018):
info = np.loadtxt('prepare_files/station_info/out_pixel_%d.txt' % year0, delimiter=',')
return info | Python | nomic_cornstack_python_v1 |
string Created on 2019年3月4日 @author: 04yyl
import requests
import json
from requests.auth import HTTPBasicAuth
import pandas as pd
from pymongo import MongoClient
import datetime
from cfg import logger
class trade extends object
begin
function __init__ self UserID=string xuhshen api=none server=string http://192.168.0.... | '''
Created on 2019年3月4日
@author: 04yyl
'''
import requests
import json
from requests.auth import HTTPBasicAuth
import pandas as pd
from pymongo import MongoClient
import datetime
from cfg import logger
class trade(object):
def __init__(self,UserID="xuhshen",api=None,server="http://192.168.0.100:5000",mock=True)... | Python | zaydzuhri_stack_edu_python |
import unittest
from project.card.trap_card import TrapCard
class TestTrapCard extends TestCase
begin
function setUp self
begin
set trap = call TrapCard string dragon
end function
function test_init self
begin
assert equal name string dragon
assert equal health_points 5
assert equal damage_points 120
end function
funct... | import unittest
from project.card.trap_card import TrapCard
class TestTrapCard(unittest.TestCase):
def setUp(self):
self.trap = TrapCard('dragon')
def test_init(self):
self.assertEqual(self.trap.name, 'dragon')
self.assertEqual(self.trap.health_points, 5)
self.assertEqual(sel... | Python | zaydzuhri_stack_edu_python |
function solve self
begin
set tuple initial_state initial_cost = call initial_state
set initial_heuristic = call heuristic initial_state
if initial_heuristic + initial_cost > max_cost
begin
return none
end
set expanded = set
set frontier : List at Node = list
call heappush frontier call Node 0 initial_state initial_co... | def solve(self) -> Optional[List[AgentPath]]:
initial_state, initial_cost = self.problem.initial_state()
initial_heuristic = self.problem.heuristic(initial_state)
if initial_heuristic + initial_cost > self.max_cost:
return None
expanded = set()
frontier: List[Node] ... | Python | nomic_cornstack_python_v1 |
function deleteTree path
begin
function handle_readonly_filedir_errors func_called path exc
begin
string try to make this more like rm -rf
set error_type = exc at 1
set full_perms = S_IRWXU ? S_IRWXG ? S_IRWXO
set parent = directory name path path
call chmod parent full_perms
call chmod path full_perms
if func_called =... | def deleteTree(path):
def handle_readonly_filedir_errors(func_called, path, exc):
"try to make this more like rm -rf"
error_type = exc[1]
full_perms = stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO
parent = os.path.dirname(path)
os.chmod(parent, full_perms)
os.chmod(path... | Python | nomic_cornstack_python_v1 |
function _set_use_cspf self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=YANGBool is_leaf=true yang_name=string use-cspf parent=self path_helper=_path_helper extmethods=_extmethods register_paths=true namespace=string http://openconfig.ne... | def _set_use_cspf(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="use-cspf", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/mpls', defin... | Python | nomic_cornstack_python_v1 |
comment create a list of days here
print list comprehension integer x / 86400 for x in seconds | # create a list of days here
print([int(x / 86400) for x in seconds])
| Python | zaydzuhri_stack_edu_python |
function max_sum_without_adjacent arr
begin
set maxSum = 0
set prevSum = 0
for num in arr
begin
set temp = max num + prevSum maxSum
set prevSum = maxSum
set maxSum = temp
end
return maxSum
end function | def max_sum_without_adjacent(arr):
maxSum = 0
prevSum = 0
for num in arr:
temp = max(num + prevSum, maxSum)
prevSum = maxSum
maxSum = temp
return maxSum
| Python | jtatman_500k |
function itkAreaClosingImageFilterIUC3IUC3_cast *args
begin
return call itkAreaClosingImageFilterIUC3IUC3_cast *args
end function | def itkAreaClosingImageFilterIUC3IUC3_cast(*args):
return _itkAreaClosingImageFilterPython.itkAreaClosingImageFilterIUC3IUC3_cast(*args) | Python | nomic_cornstack_python_v1 |
string Question is taken from leetcode (1750. Minimum Length of String After Deleting Similar Ends) One can see the question using the link https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/ Leetcode holds credit for this problem and this video is for educational purpose
string Question... | """
Question is taken from leetcode (1750. Minimum Length of String After Deleting Similar Ends)
One can see the question using the link https://leetcode.com/problems/minimum-length-of-string-after-deleting-similar-ends/
Leetcode holds credit for this problem and this video is for educational purpose
"""
"""
Question ... | Python | zaydzuhri_stack_edu_python |
comment import the necessary packages
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
import numpy as np
import argparse
from glob import glob
import cv2
comment construct the argument parser and parse the argumen... | # import the necessary packages
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
import numpy as np
import argparse
from glob import glob
import cv2
# construct the argument parser and parse the arguments
#ap = a... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from pymongo import MongoClient
from bson.objectid import ObjectId
class mongodbSearch extends object
begin
comment 重写初始化方法,为调用对象新增属性
function __init__ self
begin
comment 实例化一个接连
set client = call MongoClient
comment 连接数据库
set db = client at string python
end function
function get_one self... | # -*- coding: utf-8 -*-
from pymongo import MongoClient
from bson.objectid import ObjectId
class mongodbSearch(object):
# 重写初始化方法,为调用对象新增属性
def __init__(self):
# 实例化一个接连
self.client = MongoClient()
# 连接数据库
self.db = self.client['python']
def get_one(self):
... | Python | zaydzuhri_stack_edu_python |
set nums = tuple 1 2 3 4 5
set tuple n1 n2 *others = nums
print n1
print n2
print others | nums=(1,2,3,4,5)
n1,n2,*others = nums
print(n1)
print(n2)
print(others) | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set numbers = list string +[] string +!![] string !+[]+!![] string !+[]+!![]+!![] string !+[]+!![]+!![]+!![] string !+[]+!![]+!![]+!![]+!![] string !+[]+!![]+!![]+!![]+!![]+!![] string !+[]+!![]+!![]+!![]+!![]+!![]+!![] string !+[]+!![]+!![]+!![]+!![]+!![]+!![]+!![] string !+[]+!![]+!![]+!!... | def __init__(self):
self.numbers = [
"+[]",
"+!![]",
"!+[]+!![]",
"!+[]+!![]+!![]",
"!+[]+!![]+!![]+!![]",
"!+[]+!![]+!![]+!![]+!![]",
"!+[]+!![]+!![]+!![]+!![]+!![]",
... | Python | nomic_cornstack_python_v1 |
import string
import re
import nltk
import logging
import gensim
from gensim.models import TfidfModel
comment Removing stopwords
from nltk.corpus import stopwords
comment specific tokenizer
from nltk import TreebankWordTokenizer
from nltk.stem import PorterStemmer
from config import LOGGER_NAME , REMOVE_STRINGS_LEN
set... | import string
import re
import nltk
import logging
import gensim
from gensim.models import TfidfModel
from nltk.corpus import stopwords # Removing stopwords
from nltk import TreebankWordTokenizer # specific tokenizer
from nltk.stem import PorterStemmer
from config import LOGGER_NAME, REMOVE_STRINGS_LEN
log = loggin... | Python | zaydzuhri_stack_edu_python |
function maxvit_t weights=none progress=true **kwargs
begin
set weights = call verify weights
return call _maxvit stem_channels=64 block_channels=list 64 128 256 512 block_layers=list 2 2 5 2 head_dim=32 stochastic_depth_prob=0.2 partition_size=7 weights=weights progress=progress keyword kwargs
end function | def maxvit_t(*, weights: Optional[MaxVit_T_Weights] = None, progress: bool = True, **kwargs: Any) -> MaxVit:
weights = MaxVit_T_Weights.verify(weights)
return _maxvit(
stem_channels=64,
block_channels=[64, 128, 256, 512],
block_layers=[2, 2, 5, 2],
head_dim=32,
stochasti... | Python | nomic_cornstack_python_v1 |
function momentum prices n=10
begin
set df_momentum = call DataFrame index=index
comment get price[t-N]
set df_momentum at string pricet = prices
comment get price[t]
set df_momentum at string pricet_n = call shift n
comment get price difference comparing to n days ago
set df_momentum at string price_diff = diff prices... | def momentum(prices, n=10):
df_momentum = pd.DataFrame(index=prices.index)
# get price[t-N]
df_momentum['pricet'] = prices
# get price[t]
df_momentum['pricet_n'] = prices.shift(n)
# get price difference comparing to n days ago
df_momentum['price_diff'] = prices.diff(n)
# Calculate moment... | Python | nomic_cornstack_python_v1 |
import math
comment for sorting and creating data pts
from random import randint
comment for computing polar angle
from math import atan2
comment for plotting the hull and points
from matplotlib import pyplot as plt
import math
import numpy as np
import time
class ConvexHull
begin
function __init__ self
begin
set HullA... | import math
from random import randint # for sorting and creating data pts
from math import atan2 # for computing polar angle
from matplotlib import pyplot as plt # for plotting the hull and points
import math
import numpy as np
import time
class Con... | Python | zaydzuhri_stack_edu_python |
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix import label
from kivy.graphics import *
from kivy.uix.scrollview import ScrollView
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.core.window import Window
from mic_v... | from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix import label
from kivy.graphics import *
from kivy.uix.scrollview import ScrollView
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.core.window import Window
from mic_v... | Python | zaydzuhri_stack_edu_python |
import RPi.GPIO as GPIO
from time import sleep
import paho.mqtt.client as mqtt
set MQTT_SERVER = string 192.168.1.5
set MQTT_PATH = string msgChannel04
call setmode BCM
setup GPIO 24 OUT
setup GPIO 23 OUT
setup GPIO 25 OUT
setup GPIO 9 OUT
setup GPIO 10 OUT
setup GPIO 11 OUT
set Motor1 = call PWM 25 50
start Motor1 0
s... | import RPi.GPIO as GPIO
from time import sleep
import paho.mqtt.client as mqtt
MQTT_SERVER = "192.168.1.5"
MQTT_PATH = "msgChannel04"
GPIO.setmode(GPIO.BCM)
GPIO.setup(24,GPIO.OUT)
GPIO.setup(23,GPIO.OUT)
GPIO.setup(25,GPIO.OUT)
GPIO.setup(9,GPIO.OUT)
GPIO.setup(10,GPIO.OUT)
GPIO.setup(11,GPIO.OUT)
Motor1 = GP... | Python | zaydzuhri_stack_edu_python |
function simulate times=100
begin
set conveyor = call Conveyor
set item = random
for _ in range times
begin
run
end
return length list comprehension i for i in outputs if i == P
end function | def simulate(times=100):
conveyor = Conveyor()
conveyor.slots[0].item = Item.random()
for _ in range(times):
conveyor.run()
return len([i for i in conveyor.outputs if i == Item.P]) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Wed Jan 11 10:18:22 2017 @author: yjl20
comment importation pacakges
from sklearn import tree , metrics
comment from sklearn.preprocessing import OneHotEncoder
from sklearn.feature_extraction import DictVectorizer
import pandas as pd
comment importation dataset
set us_cen... | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 11 10:18:22 2017
@author: yjl20
"""
#importation pacakges
from sklearn import tree , metrics
#from sklearn.preprocessing import OneHotEncoder
from sklearn.feature_extraction import DictVectorizer
import pandas as pd
#importation dataset
us_census_dat... | Python | zaydzuhri_stack_edu_python |
function get_result self to=5
begin
try
begin
return get _res_q true to
end
except Empty
begin
return none
end
end function | def get_result(self, to=5):
try:
return self._res_q.get(True, to)
except queue.Empty:
return None | Python | nomic_cornstack_python_v1 |
from collections import defaultdict , deque
from bisect import bisect_left
import re
set filename = string part_2.txt
set input = list
with open filename encoding=string utf-8 as f
begin
for line in f
begin
append input list comprehension c for c in list strip line string if c != string
end
end
from operator import mu... | from collections import defaultdict, deque
from bisect import bisect_left
import re
filename = 'part_2.txt'
input = []
with open(filename, encoding="utf-8") as f:
for line in f:
input.append([c for c in list(line.strip('\n')) if c != ' '])
from operator import mul
from functools import reduce
def evaluat... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import colors as c
import random as r
print clear + magenta + string Welcome to the magic eight ball!
print magenta + string Please type your question below:
set answers = list string yes string no string maybe string definately string my soarces say no string without a doubt string you re... | #!/usr/bin/env python3
import colors as c
import random as r
print(c.clear + c.magenta + 'Welcome to the magic eight ball!')
print(c.magenta + 'Please type your question below:')
answers = ['yes',
'no' ,
'maybe' ,
'definately' ,
'my soarces say no' ,
'without a doubt' ,
'you really dont want to know' ,
':|' ,
':@ N... | Python | zaydzuhri_stack_edu_python |
import os
import csv
import glob
string This script "trims" all raw traces in /data/raw/DPAv2/public_db It deletes the DPAv2 traces header (lines starting by #), and it saves the result in /data/processed/DPAv2/public_db. This script is already multiplatform compatible; tested with the following OSs: * Windows 10 -----... | import os
import csv
import glob
""" This script "trims" all raw traces in /data/raw/DPAv2/public_db
It deletes the DPAv2 traces header (lines starting by #), and it saves
the result in /data/processed/DPAv2/public_db.
This script is already multiplatform compatible; tested with the following
OSs:
* Windows 10
... | Python | zaydzuhri_stack_edu_python |
import itertools
import numpy as np
from sklearn import metrics
import sptensor
function getAUC model feat Y train test
begin
set trainY = Y at train
fit model feat at tuple train slice : : trainY
set modelPred = call predict_proba feat at tuple test slice : :
set tuple fpr tpr thresholds = call roc_curve Y at tes... | import itertools
import numpy as np
from sklearn import metrics
import sptensor
def getAUC(model, feat, Y, train, test):
trainY = Y[train]
model.fit(feat[train, :], trainY)
modelPred = model.predict_proba(feat[test,:])
fpr, tpr, thresholds = metrics.roc_curve(Y[test], modelPred[:, 1], pos_label=1)
... | Python | zaydzuhri_stack_edu_python |
import argparse
import numpy as np
import tensorflow as tf
from skimage.util import random_noise
from watermark import watermarking
from train import training
function data_loader args
begin
if dataset == string cifar10
begin
set tuple tuple train_images train_labels tuple test_images test_labels = call load_data
end
e... | import argparse
import numpy as np
import tensorflow as tf
from skimage.util import random_noise
from watermark import watermarking
from train import training
def data_loader(args):
if args.dataset=="cifar10":
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.cifar10.load... | Python | zaydzuhri_stack_edu_python |
function iterAttributeNames self valuesOnly=false referencesOnly=false changedOnly=false
begin
if not referencesOnly
begin
set values = itsValues
for name in call iterkeys
begin
if not changedOnly or call _isDirty name
begin
yield name
end
end
end
if not valuesOnly
begin
set refs = itsRefs
for name in call iterkeys
beg... | def iterAttributeNames(self, valuesOnly=False, referencesOnly=False,
changedOnly=False):
if not referencesOnly:
values = self.itsValues
for name in values._dict.iterkeys():
if not changedOnly or values._isDirty(name):
yield ... | Python | nomic_cornstack_python_v1 |
function hosts
begin
set devices = keys inventory
return call jsonify dict string hosts sorted devices
end function | def hosts():
devices = app.inventory.keys()
return jsonify({"hosts": sorted(devices)}) | Python | nomic_cornstack_python_v1 |
function test_binarytree_pre_order_on_given given_list capsys
begin
set expected = list 20 18 12 11 14 19 40 31 22 33
call pre_order
set tuple out err = call readouterr
set actual = list comprehension integer i for i in split out string if i != string
assert expected == actual
end function | def test_binarytree_pre_order_on_given(given_list, capsys):
expected = [20, 18, 12, 11, 14, 19, 40, 31, 22, 33]
given_list.pre_order()
out, err = capsys.readouterr()
actual = [int(i) for i in out.split('\n') if i != '']
assert expected == actual | Python | nomic_cornstack_python_v1 |
comment This script tries to solve the ODE's in Dennis's paper. It uses the following
comment cookbook example as a guide:
comment https://scipy-cookbook.readthedocs.io/items/CoupledSpringMassSystem.html
comment Useful StackOverflow:
comment https://stackoverflow.com/questions/65344347/coupled-system-of-4-differential-... | # This script tries to solve the ODE's in Dennis's paper. It uses the following
# cookbook example as a guide:
# https://scipy-cookbook.readthedocs.io/items/CoupledSpringMassSystem.html
#
# Useful StackOverflow:
# https://stackoverflow.com/questions/65344347/coupled-system-of-4-differential-equations-python
from scipy... | Python | zaydzuhri_stack_edu_python |
function on_message nick message channel
begin
set message = call force_unicode message
set nick_re = compile string ^%s[:,\s]\s* % nick
if match message is not none
begin
set message = sub string message
set request = call IRCRequest message bot nick channel
return call callback request
end
end function | def on_message(nick, message, channel):
message = thebot.utils.force_unicode(message)
nick_re = re.compile(u'^%s[:,\s]\s*' % conn.nick)
if nick_re.match(message) is not None:
message = nick_re.sub(u'', message)
request = IRCRequest(message, self.bot, ... | Python | nomic_cornstack_python_v1 |
set N = list input
sort N reverse=true
print join string N | N = list(input())
N.sort(reverse=True)
print(''.join(N)) | Python | zaydzuhri_stack_edu_python |
function get_classifier self label
begin
with _label_to_classifier_lock
begin
return _label_to_classifier at label
end
end function | def get_classifier(self, label):
with self._label_to_classifier_lock:
return self._label_to_classifier[label] | Python | nomic_cornstack_python_v1 |
comment https://www.hackerrank.com/challenges/interchange-two-numbers
string a=raw_input() b=raw_input() a,b = b,a print (a,b)
set tuple a b = tuple call raw_input call raw_input | # https://www.hackerrank.com/challenges/interchange-two-numbers
"""
a=raw_input()
b=raw_input()
a,b = b,a
print (a,b)
"""
(a,b)=(raw_input(), raw_input()) | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.