code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import sys
import os
import cv2 , time
import numpy as np
import pickle
import matplotlib.pyplot as plt
function plotCMC mat matches gpath=string gallery/
begin
set labels = read lines open gpath + string labels.txt string r
set labels = list comprehension strip lbl for lbl in labels
set labarr = call asarray labels
co... | import sys
import os
import cv2, time
import numpy as np
import pickle
import matplotlib.pyplot as plt
def plotCMC(mat, matches, gpath='gallery/'):
labels = open(gpath + 'labels.txt', 'r').readlines()
labels = [lbl.strip() for lbl in labels]
labarr = np.asarray(labels)
# print(labarr.shape)
R = np.... | Python | zaydzuhri_stack_edu_python |
function load_site_objects verbosity
begin
if not call is_installed string django.contrib.sites
begin
return
end
set site_info = get attribute defs string SITE_OBJECTS_INFO_DICT
if site_info
begin
for pk in sorted keys site_info
begin
set tuple site created = call get_or_create pk=pk
if site
begin
set name = site_info ... | def load_site_objects(verbosity):
if not apps.is_installed('django.contrib.sites'):
return
site_info = getattr(defs, 'SITE_OBJECTS_INFO_DICT')
if site_info:
for pk in sorted(site_info.keys()):
site, created = Site.objects.get_or_create(pk=pk)
if site:
... | Python | nomic_cornstack_python_v1 |
function combine_lists list1 list2
begin
set result = list
for i in list1
begin
for j in list2
begin
append result list i j
end
end
return result
end function | def combine_lists(list1,list2):
result = []
for i in list1:
for j in list2:
result.append([i,j])
return result
| Python | flytech_python_25k |
function chebyshev_dist x1 x2
begin
return max absolute x1 - x2 - 1
end function | def chebyshev_dist(x1, x2):
return jnp.max(jnp.abs(x1 - x2), -1) | Python | nomic_cornstack_python_v1 |
function _process_nick_command self client_socket nick
begin
if not match nick
begin
return call _send_error client_socket INVALID_NICK_FORMAT
end
set client_state = connections at client_socket
set current_nick = client_state at string username
if nick == current_nick
begin
return call _send_error client_socket USERNA... | def _process_nick_command(self, client_socket, nick):
if not NICK_RE.match(nick):
return self._send_error(client_socket, INVALID_NICK_FORMAT)
client_state = self.connections[client_socket]
current_nick = client_state['username']
if nick == current_nick:
return se... | Python | nomic_cornstack_python_v1 |
function create_featurestore self
begin
comment Generate a "stub function" on-the-fly which will actually make
comment the request.
comment gRPC handles serialization and deserialization, so we just need
comment to pass in the functions for each.
if string create_featurestore not in _stubs
begin
set _stubs at string cr... | def create_featurestore(
self,
) -> Callable[
[featurestore_service.CreateFeaturestoreRequest],
Awaitable[operations_pb2.Operation],
]:
# Generate a "stub function" on-the-fly which will actually make
# the request.
# gRPC handles serialization and deserialization... | Python | nomic_cornstack_python_v1 |
function trim s
begin
if s == string
begin
comment 首先判断str s 是否为''
return s
end
comment 如果有Str前空格
while s at 0 == string
begin
comment 删除空格 直到没有空格
set s = s at slice 1 : :
comment 判断是否全是空格 是的话就返回s 然后Break 不然会出现 IndexError: string index out of range 因为还要判断Str后面是否存在空格
if s == string
begin
return s
break
end
end
comm... | def trim(s):
if s == '':
return s # 首先判断str s 是否为''
while s[0] == ' ': # 如果有Str前空格
s = s[1:] # 删除空格 直到没有空格
if s == '': # 判断是否全是空格 是的话就返回s 然后Break 不然会出现 IndexError: string index out of range 因为还要判断Str后面是否存在空格
return s
break
while s[-1] == ' ': # 同上 删除Str后空... | Python | zaydzuhri_stack_edu_python |
function train self sentences
begin
set dictionary = call Dictionary sentences
set ft = call Word2Vec sentences workers=cpu count min_count=5 size=300 seed=12345
set index = call WordEmbeddingSimilarityIndex wv
set matrix = call SparseTermSimilarityMatrix index dictionary
set dictionary = dictionary
set ft = ft
set mat... | def train(self, sentences):
dictionary = Dictionary(sentences)
ft = Word2Vec(sentences, workers=cpu_count(), min_count=5, size=300, seed=12345)
index = WordEmbeddingSimilarityIndex(ft.wv)
matrix = SparseTermSimilarityMatrix(index, dictionary)
self.dictionary = dictionary
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Jun 11 21:38:14 2019 @author: Lakshmendra Singh
function Fact num
begin
if num == 0
begin
return 1
end
else
begin
return num * call Fact num - 1
end
end function
print call Fact 6 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 11 21:38:14 2019
@author: Lakshmendra Singh
"""
def Fact(num):
if num == 0:
return 1
else:
return num*Fact(num-1)
print(Fact(6))
| Python | zaydzuhri_stack_edu_python |
import requests
class Class extends object
begin
function __init__ self host port
begin
set __host = host
set __port = port
set __calling_method_name = none
end function
function __call__ self *args **kwargs
begin
set data = dictionary
set data at string method = __calling_method_name
set data at string args = list arg... | import requests
class Class(object):
def __init__(self, host, port):
self.__host = host
self.__port = port
self.__calling_method_name = None
def __call__(self, *args, **kwargs):
data = dict()
data["method"] = self.__calling_method_name
data["args"] = list(args... | Python | zaydzuhri_stack_edu_python |
function count_word_frequencies string
begin
set word_freq = dict
set string = lower string
set word = string
for char in string
begin
if is alpha char
begin
set word = word + char
end
else
if word
begin
set word_freq at word = get word_freq word 0 + 1
set word = string
end
end
if word
begin
set word_freq at word = ... | def count_word_frequencies(string):
word_freq = {}
string = string.lower()
word = ""
for char in string:
if char.isalpha():
word += char
else:
if word:
word_freq[word] = word_freq.get(word, 0) + 1
word = ""
if word:
w... | Python | jtatman_500k |
comment -*- coding:utf-8 -*-
print string 欢迎使用Python3进行编程学习!
comment 输入名字
print string 请输入你的名字:
set name = input
print string 你好: + name
comment 输入年龄
set age = input string 请输入你的年龄:
comment 输出完整内容
print name + string ,你明年就 + string integer age + 1 + string 岁了,要加油哦! | #-*- coding:utf-8 -*-
print('欢迎使用Python3进行编程学习!')
#输入名字
print('请输入你的名字:')
name = input()
print('你好:'+name)
#输入年龄
age = input('请输入你的年龄:')
#输出完整内容
print(name + ',你明年就' + str(int(age)+1) + '岁了,要加油哦!')
| Python | zaydzuhri_stack_edu_python |
function config self data=none
begin
if data
begin
return call request string /config dictionary config=data
end
return call request string /config at string config
end function | def config(self, data=None):
if data:
return self.request('/config', dict(config=data))
return self.request('/config', )['config'] | Python | nomic_cornstack_python_v1 |
function handle cls exc context
begin
comment check for specific handlers for the exc class
set handler_function_name = format string handle_{} lower __name__
if has attribute cls handler_function_name
begin
return call get attribute cls handler_function_name exc context
end
for base_class in __bases__
begin
set handle... | def handle(cls, exc, context):
# check for specific handlers for the exc class
handler_function_name = "handle_{}".format(exc.__class__.__name__.lower())
if hasattr(cls, handler_function_name):
return getattr(cls, handler_function_name)(exc, context)
for base_class in exc.... | Python | nomic_cornstack_python_v1 |
function eval self n=none
begin
pass
end function | def eval(self, n=None):
pass | Python | nomic_cornstack_python_v1 |
function test_set_cpu_and_mem self
begin
set input_file_memory = none
set submit_script_memory = none
set server = string server2
call set_cpu_and_mem
assert equal cpu_cores 8
end function | def test_set_cpu_and_mem(self):
self.job_8.input_file_memory = None
self.job_8.submit_script_memory = None
self.job_8.server = 'server2'
self.job_8.set_cpu_and_mem()
self.assertEqual(self.job_8.cpu_cores, 8) | Python | nomic_cornstack_python_v1 |
function freeze_cls self
begin
set temp = list
for param in parameters Classifier
begin
set requires_grad = false
end
comment Verify
for param in parameters Classifier
begin
set _ = requires_grad == false
append temp _
end
assert false not in temp msg string Error! Not all of Classifier layers are frozen!
print string... | def freeze_cls(self):
temp = []
for param in self.Classifier.parameters():
param.requires_grad = False
#Verify
for param in self.Classifier.parameters():
_ = param.requires_grad == False
temp.append(_)
assert False not in temp, "Error! Not ... | Python | nomic_cornstack_python_v1 |
function download self file_url
begin
set url = base_url + format string /storage-service/cloud-storage/s3/file/download?url={0} file_url
set headers = dict string ApiKey api_key
set response = get requests url=url headers=headers
return response
end function | def download(self, file_url):
url = self.base_url + "/storage-service/cloud-storage/s3/file/download?url={0}".format(file_url)
headers = {"ApiKey": self.api_key}
response = requests.get(url=url, headers=headers)
return response | Python | nomic_cornstack_python_v1 |
function edit_description self task new_description
begin
raise call ValueError string cannot edit description in 'In Progress' status
end function | def edit_description(self, task, new_description):
raise ValueError("cannot edit description in 'In Progress' status") | Python | nomic_cornstack_python_v1 |
function main sender_private_key receiver_public_key document message_filename sender
begin
debug format string Trying to encode document {} into TAP message with sender private key {} and receiver public key {} document sender_private_key receiver_public_key
set transaction_id = string uuid 1 at slice : 8 :
try
begi... | def main(sender_private_key, receiver_public_key, document, message_filename, sender):
logger.debug("Trying to encode document {} into TAP message with sender private key {} and receiver public key {}".format(
document,
sender_private_key,
receiver_public_key
))
transaction_id = str(... | Python | nomic_cornstack_python_v1 |
function assembler_paquet0 self info_appareil
begin
set type_message = type_message
set classe_message = call map_type_message type_message
set paquet = call classe_message data info_appareil
set tuple senseurs ack_NA = call assembler
try
begin
set __iv = iv
set __iv_confirme = true
end
except AttributeError
begin
comm... | def assembler_paquet0(self, info_appareil: dict):
type_message = self.__paquet0.type_message
classe_message = TypesMessages.map_type_message(type_message)
paquet = classe_message(self.__paquet0.data, info_appareil)
senseurs, ack_NA = paquet.assembler()
try:
self.__i... | Python | nomic_cornstack_python_v1 |
comment class Process(object):
comment def __init__(self, pid)
comment self.pid = pid
comment 继承Process
comment from multiprocessing import Process
comment class MyClass(Process):
comment def __init__(self, value):
comment self.value = value
comment super(MyClass, self).__init__()
comment def run(self):
comment return ... | # class Process(object):
# def __init__(self, pid)
# self.pid = pid
#继承Process
# from multiprocessing import Process
# class MyClass(Process):
# def __init__(self, value):
# self.value = value
# super(MyClass, self).__init__()
# def run(self):
# return self.value
# p = MyClass(20... | Python | zaydzuhri_stack_edu_python |
function _drawSensors d locations sensorSize=10
begin
for loc in locations
begin
call ellipse tuple integer loc at 0 - sensorSize / 2 integer loc at 1 - sensorSize / 2 integer loc at 0 + sensorSize / 2 integer loc at 1 + sensorSize / 2 fill=tuple 50 50 155 outline=tuple 50 50 155
call text tuple integer loc at 0 + sens... | def _drawSensors(d, locations, sensorSize = 10):
for loc in locations:
d.ellipse((int(loc[0]) - sensorSize/2, int(loc[1]) - sensorSize/2, \
int(loc[0]) + sensorSize/2, int(loc[1]) + sensorSize/2), \
fill = (50, 50, 155), outline = (50, 50, 155))
d.text((int(... | Python | nomic_cornstack_python_v1 |
function get_base_queryset self
begin
return call select_related string category string parent string parent__parent
end function | def get_base_queryset(self):
return JST.objects.filter(active=True).select_related(
"category", "parent", "parent__parent"
) | Python | nomic_cornstack_python_v1 |
import tarfile
import sys
import os
import hashlib
import numpy as np
from numpy import array
import torch
from torch.utils.data import TensorDataset , DataLoader
import torch.nn as nn
from torch import optim
from torch.autograd import Variable
from torch.nn import functional as F
comment Task 1: Load the data
comment ... | import tarfile
import sys
import os
import hashlib
import numpy as np
from numpy import array
import torch
from torch.utils.data import TensorDataset, DataLoader
import torch.nn as nn
from torch import optim
from torch.autograd import Variable
from torch.nn import functional as F
# Task 1: Load the data
# For this ta... | Python | zaydzuhri_stack_edu_python |
import webbrowser
from bs4 import BeautifulSoup
set xml_doc = string <xml><people><person><name>John Doe</name><age>30</age></person><person><name>Jane Smith</name><age>25</age></person></people></xml>
set soup = call BeautifulSoup xml_doc string xml
set html = string <html> <head> <title>People</title> </head> <body> ... | import webbrowser
from bs4 import BeautifulSoup
xml_doc = "<xml><people><person><name>John Doe</name><age>30</age></person><person><name>Jane Smith</name><age>25</age></person></people></xml>"
soup = BeautifulSoup(xml_doc, 'xml')
html = """
<html>
<head>
<title>People</title>
</head>
<body>
<h1>People</h1>
<... | Python | flytech_python_25k |
function GLU_conv input_layer output_dim kernel_size=none
begin
if kernel_size is none
begin
set kernel_size = list 3 call as_list at 2
end
set batch_size = call as_list at 0
comment set the output dim * 2 as output channel..
set pads = zeros list 3 2 dtype=int32
set pads at tuple 1 0 = kernel_size at 0 - 1
set input_l... | def GLU_conv(input_layer, output_dim, kernel_size=None):
if kernel_size is None:
kernel_size = [3, input_layer.get_shape().as_list()[2]]
batch_size = input_layer.get_shape().as_list()[0]
# set the output dim * 2 as output channel..
pads = np.zeros([3, 2], dtype=np.int32)
pads[1, 0] = kernel... | Python | nomic_cornstack_python_v1 |
function line_strip line
begin
for comment_flag in list string ; string # string !!
begin
set line = split line comment_flag at 0
end
set line = strip line
return replace line string , string
end function | def line_strip(line):
for comment_flag in [";", "#", "!!"]:
line = line.split(comment_flag)[0]
line = line.strip()
return line.replace(",", " ") | Python | nomic_cornstack_python_v1 |
set string = string Mississippi
comment Step 1: Convert the string into a set
set unique_chars = set string
comment Step 2: Convert the set back into a list
set unique_chars_list = list unique_chars
comment Step 3: Sort the list in ascending order based on ASCII values
set sorted_chars_list = sorted unique_chars_list
c... | string = "Mississippi"
# Step 1: Convert the string into a set
unique_chars = set(string)
# Step 2: Convert the set back into a list
unique_chars_list = list(unique_chars)
# Step 3: Sort the list in ascending order based on ASCII values
sorted_chars_list = sorted(unique_chars_list)
# Step 4: Convert the sorted list... | Python | greatdarklord_python_dataset |
import random
import pylab
import matplotlib.animation as animation
import copy
class Predator_Prey extends object
begin
function __init__ self n0_shark n0_fish breed_age_shark breed_age_fish starve_time_shark gridlen=100
begin
comment list of time
set t = list 0
comment list of number of shark
set n_shark = list n0_sh... | import random
import pylab
import matplotlib.animation as animation
import copy
class Predator_Prey(object):
def __init__(self, n0_shark, n0_fish, breed_age_shark, breed_age_fish, starve_time_shark, gridlen=100):
self.t=[0] #list of time
self.n_shark=[n0_shark] #list of number of shark
se... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sun Feb 21 4:18 2021 Author: Lucas Edmisten Date: 3/7/2021 Assignment: Final Part 6 DSC530
from __future__ import print_function , division
import matplotlib.pyplot as plt | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 21 4:18 2021
Author: Lucas Edmisten
Date: 3/7/2021
Assignment: Final Part 6 DSC530
"""
from __future__ import print_function, division
import matplotlib.pyplot as plt | Python | zaydzuhri_stack_edu_python |
function _add_data_line self data col value ts
begin
string Append the data point to the dictionary of "data" :param data: The dictionary containing all data :param col: The sub-metric name e.g. 'host1_port1.host2_port2.SendQ' :param value: integer :param ts: timestamp :return: None
if col in column_csv_map
begin
set o... | def _add_data_line(self, data, col, value, ts):
"""
Append the data point to the dictionary of "data"
:param data: The dictionary containing all data
:param col: The sub-metric name e.g. 'host1_port1.host2_port2.SendQ'
:param value: integer
:param ts: timestamp
:return: None
"""
if c... | Python | jtatman_500k |
function forward self x
begin
set x = reshape x shape at 0 shape at 1 1 1
set x = input x
set x = call bn x
set x = relu x
for i in range length DV - 1 - 1 - 1
begin
set x = call x
if i != 0
begin
set x = call x
set x = relu x
end
end
for tuple col t in enumerate col_type
begin
set i = integer col / shape
set j = col %... | def forward(self, x):
x = x.reshape(x.shape[0], x.shape[1], 1 , 1)
x = self.input(x)
x = self.bn(x)
x = F.relu(x)
for i in range(len(self.DV)-1, -1, -1):
x = self.DV[i](x)
if i != 0:
x = self.BN[i](x)
x = F.relu(x)
... | Python | nomic_cornstack_python_v1 |
function addroutes app roleauthenticator
begin
decorator call route string /ping
decorator call restrict list string admin
function ping
begin
return string up
end function
decorator call route string /shutdown
decorator call restrict list string admin
function shutdown
begin
call get environ string werkzeug.server.shu... | def addroutes(app, roleauthenticator):
@app.route("/ping")
@roleauthenticator.restrict(["admin"])
def ping():
return "up"
@app.route("/shutdown")
@roleauthenticator.restrict(["admin"])
def shutdown():
request.environ.get('werkzeug.server.shutdown')() | Python | nomic_cornstack_python_v1 |
class Accumulator
begin
function __init__ self inputs
begin
set inputs = inputs
set position = 0
set accumulator = 0
set visited = set
end function
function nop self steps
begin
set position = position + 1
end function
function acc self steps
begin
set accumulator = accumulator + steps
set position = position + 1
end f... | class Accumulator():
def __init__(self, inputs):
self.inputs = inputs
self.position = 0
self.accumulator = 0
self.visited = set()
def nop(self, steps):
self.position += 1
def acc(self, steps):
self.accumulator += steps
self.position += 1
def jm... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from threading import Timer
class RepeatedTimer
begin
function __init__ self interval function
begin
set timer = none
set interval = interval
set function = function
set is_running = false
start self
end function
function run self
begin
set is_running = false
start self
call function
end f... | # -*- coding: utf-8 -*-
from threading import Timer
class RepeatedTimer:
def __init__(self, interval, function):
self.timer = None
self.interval = interval
self.function = function
self.is_running = False
self.start()
def run(self):
self.is_running = F... | Python | zaydzuhri_stack_edu_python |
comment used in print_csm_info
function check_dupl_sources self
begin
string Extracts duplicated sources, i.e. sources with the same source_id in different source groups. Raise an exception if there are sources with the same ID which are not duplicated. :returns: a list of list of sources, ordered by source_id
set dd =... | def check_dupl_sources(self): # used in print_csm_info
"""
Extracts duplicated sources, i.e. sources with the same source_id in
different source groups. Raise an exception if there are sources with
the same ID which are not duplicated.
:returns: a list of list of sources, order... | Python | jtatman_500k |
function get_o self
begin
return o
end function | def get_o(self):
return self.o | Python | nomic_cornstack_python_v1 |
function _compute_raw_image_norm self
begin
set xypos = tuple _nx / 2.0 _ny / 2.0
comment TODO: generalize "radius" (ellipse?) is oversampling is
comment different along x/y axes
set radius = _norm_radius * oversampling at 0
set aper = call CircularAperture xypos r=radius
set tuple flux _ = call do_photometry _data met... | def _compute_raw_image_norm(self):
xypos = (self._nx / 2.0, self._ny / 2.0)
# TODO: generalize "radius" (ellipse?) is oversampling is
# different along x/y axes
radius = self._norm_radius * self.oversampling[0]
aper = CircularAperture(xypos, r=radius)
flux, _ = aper.do_ph... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
set x = list
set y3 = list
set y8 = list
set x1 = list
set y1 = list
append y1 1.1
append y1 0.85
append y1 0.5
append y1 0.2
append y1 0.15
append y1 0.1
append x1 0.1
append x1 0.2
append x1 0.4
append x1 1
append x1 1.05
append ... | import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLine2D
x = []
y3 = []
y8 = []
x1 = []
y1 = []
y1.append(1.1)
y1.append(0.85)
y1.append(0.5)
y1.append(0.2)
y1.append(0.15)
y1.append(0.1)
x1.append(0.1)
x1.append(0.2)
x1.append(0.4)
x1.append(1)
x1.append(1.05)
x1.append(1.3)
x.append(10)
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import sys
from itertools import combinations_with_replacement , product
function input
begin
return right strip read line stdin
end function
function main
begin
set tuple D G = map int split input
set problem = list
for i in range 1 D + 1
begin
set tuple p c = map int split input
append ... | #!/usr/bin/env python3
import sys
from itertools import combinations_with_replacement,product
def input(): return sys.stdin.readline().rstrip()
def main():
D,G=map(int, input().split())
problem=[]
for i in range(1,D+1):
p,c=map(int, input().split())
problem.append([i,p,c])
ans=10000000... | Python | zaydzuhri_stack_edu_python |
function mean_absolute_error w X y
begin
comment TODO 1: Fill in your code here #
set N = length X
set err = sum absolute dot w T - y
set err = err / N
return err
end function | def mean_absolute_error(w, X, y):
#####################################################
# TODO 1: Fill in your code here #
#####################################################
N = len(X)
err = np.sum(abs(np.dot(w,X.T) - y))
err = err / N
return err | Python | nomic_cornstack_python_v1 |
from random import shuffle
from typing import List , Dict
import itertools
from shared.enums import Sentiment
class Ranking
begin
function __init__ self
begin
set sentiment_samples = dictionary
set _list = none
set _data = none
end function
function set_data self data
begin
set _data = data
end function
function get_da... | from random import shuffle
from typing import List, Dict
import itertools
from shared.enums import Sentiment
class Ranking:
def __init__(self):
self.sentiment_samples = dict()
self._list = None
self._data = None
def set_data(self, data):
self._data = data
def get_data(se... | Python | zaydzuhri_stack_edu_python |
import random
import sys
import os
import matplotlib
import numpy as np
import pylab as pl
from tkinter import *
import serial
import numpy
import matplotlib.pyplot as plt
from drawnow import *
comment tempX = []
comment tempY = []
comment 115200-baud rate, creating our serial object for the incoming data
set data = ca... | import random
import sys
import os
import matplotlib
import numpy as np
import pylab as pl
from tkinter import*
import serial
import numpy
import matplotlib.pyplot as plt
from drawnow import *
#tempX = []
#tempY = []
data=serial.Serial('com4', 115200) # 115200-baud rate, creating our serial object for the incoming da... | Python | zaydzuhri_stack_edu_python |
function get_current
begin
set start = time
set systemctl_show = decode check output SYSTEMCTL_SHOW
set processes_stats = list
set private_ip = call get_private_ip
for match in call finditer systemctl_show
begin
set systemd_name = call group string name
set pid = integer call group string pid
set service = call find_s... | def get_current():
start = time.time()
systemctl_show = subprocess.check_output(SYSTEMCTL_SHOW).decode()
processes_stats = []
private_ip = appscale_info.get_private_ip()
for match in SYSTEMCTL_SHOW_PATTERN.finditer(systemctl_show):
systemd_name = match.group('name')
pid = int(match.group... | Python | nomic_cornstack_python_v1 |
function isStable self
begin
return tau == inf
end function | def isStable(self):
return self.tau == inf | Python | nomic_cornstack_python_v1 |
function chunkwise xs N_l N_c N_r padding=true
begin
set tuple bs xmax idim = size xs
set n_chunks = if expression padding then ceil xmax / N_c else xmax // N_l + N_c + N_r
set xs_tmp = call new_zeros bs n_chunks N_l + N_c + N_r idim
if padding
begin
set xs = call cat list call new_zeros bs N_l idim xs call new_zeros b... | def chunkwise(xs, N_l, N_c, N_r, padding=True):
bs, xmax, idim = xs.size()
n_chunks = math.ceil(xmax / N_c) if padding else xmax // (N_l + N_c + N_r)
xs_tmp = xs.new_zeros(bs, n_chunks, N_l + N_c + N_r, idim)
if padding:
xs = torch.cat([xs.new_zeros(bs, N_l, idim), xs, xs.new_zeros(bs, N_r, idim... | Python | nomic_cornstack_python_v1 |
function weight_on_planets
begin
set weight = decimal input string What do you weigh on earth?
set mweight = 0.38 * weight
set jweight = 2.34 * weight
print format string On Mars you would weigh {0} pounds. On Jupiter you would weigh {1} pounds. mweight jweight
end function
if __name__ == string __main__
begin
call wei... | def weight_on_planets():
weight = float(input("What do you weigh on earth? "))
mweight = .38 * weight
jweight = 2.34 * weight
print("\nOn Mars you would weigh {0} pounds.\nOn Jupiter you would weigh {1} pounds.".format(mweight, jweight))
if __name__ == '__main__':
weight_on_planets()
| Python | zaydzuhri_stack_edu_python |
function get_meta_information
begin
set meta_information = call get_meta_information
set meta_information at string description = string Cartpole with full configuration space
return meta_information
end function | def get_meta_information() -> Dict:
meta_information = CartpoleBase.get_meta_information()
meta_information['description'] = 'Cartpole with full configuration space'
return meta_information | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
import requests
import pandas as pd
import re
from time import sleep
comment In[2]:
from datetime import datetime
set retrievalDate = today
set retrievalDate = replace retrievalDate minute=0 second=0 microsecond=0
comment In[3]:
comment get data from NWS... | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import requests
import pandas as pd
import re
from time import sleep
# In[2]:
from datetime import datetime
retrievalDate = datetime.today()
retrievalDate = retrievalDate.replace(minute=0, second=0, microsecond=0)
# In[3]:
# get data from NWS API
url = 'https:/... | Python | zaydzuhri_stack_edu_python |
import base64
comment Define user and password for Basic auth scheme
set myPersistentAuth = string gmijares@lapsusdev.com:ThisIsASecurePassword
set authInBytes = encode myPersistentAuth string ascii
set base64Bytes = base64 encode authInBytes
comment Get the Base64 string representation of our defined Auth
set base64Au... | import base64
# Define user and password for Basic auth scheme
myPersistentAuth = 'gmijares@lapsusdev.com:ThisIsASecurePassword'
authInBytes = myPersistentAuth.encode('ascii')
base64Bytes = base64.b64encode(authInBytes)
# Get the Base64 string representation of our defined Auth
base64Auth = base64Bytes.decode('ascii... | Python | zaydzuhri_stack_edu_python |
function test_nmap_get_sensordef self
begin
set test_sensordef = dict string kind call get_kind ; string name string NMAP ; string description string Checks the availability of systems. ; string help string Checks the availability of systems on a network and logs this to a separate logfile on the miniprobe. ; string ta... | def test_nmap_get_sensordef(self):
test_sensordef = {
"kind": self.test_nmap.get_kind(),
"name": "NMAP",
"description": "Checks the availability of systems.",
"help": "Checks the availability of systems on a network and logs this to a separate "
... | Python | nomic_cornstack_python_v1 |
function read_handle self handle
begin
return call read_by_handle handle at 0
end function | def read_handle(self, handle):
return self.requester.read_by_handle(handle)[0] | Python | nomic_cornstack_python_v1 |
import serial
import time
import sys
from cmd import Cmd
from PIL import ImageGrab , ImageStat
from itertools import *
from struct import pack
comment ------------------------------------------------------------------------------
comment Configuration
comment ------------------------------------------------------------... | import serial
import time
import sys
from cmd import Cmd
from PIL import ImageGrab, ImageStat
from itertools import *
from struct import pack
#------------------------------------------------------------------------------
# Configuration
#------------------------------------------------------------------------------
... | Python | zaydzuhri_stack_edu_python |
function click_and_wait driver element find_elements_by
begin
try
begin
if find_elements_by == 0
begin
set button = call find_element_by_css_selector element
end
else
begin
set button = call find_element_by_class_name element
end
call execute_script string arguments[0].click() button
end
comment If the specified button... | def click_and_wait(driver, element, find_elements_by):
try:
if find_elements_by == 0:
button = driver.find_element_by_css_selector(element)
else:
button = driver.find_element_by_class_name(element)
driver.execute_script("arguments[0].click()", button... | Python | nomic_cornstack_python_v1 |
function updateMovies self
begin
set title = input string Title:
if call searchMovie title is not none
begin
call searchMovie title
set newTitle = input string New title:
set newDescription = input string New description:
set newType = input string New type:
set newYear = input string New year:
call updateMovie title n... | def updateMovies(self):
title = input("Title:")
if self.__comand1.searchMovie(title) is not None:
self.__comand1.searchMovie(title)
newTitle = input("New title:")
newDescription = input("New description:")
newType = input("New type:")
newYear =... | Python | nomic_cornstack_python_v1 |
function writeImageFile self x y z f
begin
set cur = call cursor
execute cur string insert into tiles (z, x, y,s,image) values (?,?,?,?,?) tuple z x y 0 call Binary read f
commit db
end function | def writeImageFile(self, x, y, z, f) :
cur = self.db.cursor()
cur.execute('insert into tiles (z, x, y,s,image) \
values (?,?,?,?,?)',
(z, x, y, 0, sqlite3.Binary(f.read())))
self.db.commit() | Python | nomic_cornstack_python_v1 |
function fmt_mode_str self st_mode
begin
comment Type
set ftype_alias = dictionary REG=string - FIFO=string p UID=string s GID=string s VTX=string t
set mode_str = string -
for ftype in list string DIR string CHR string BLK string FIFO string LNK string SOCK
begin
set func = get attribute stat string S_IS%s % ftype
if ... | def fmt_mode_str(self, st_mode):
# Type
ftype_alias = dict(REG='-', FIFO='p', UID='s', GID='s', VTX='t')
mode_str = '-'
for ftype in ['DIR', 'CHR', 'BLK', 'FIFO', 'LNK', 'SOCK',]:
func = getattr(stat, 'S_IS%s' % ftype)
if func(st_mode):
mode_str = ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment ## Analyze A/B Test Results
comment ## Table of Contents
comment - [Introduction](#intro)
comment - [Part I - Probability](#probability)
comment - [Part II - A/B Test](#ab_test)
comment - [Part III - Regression](#regression)
comment <a id='intro'></a>
comment #... | #!/usr/bin/env python
# coding: utf-8
# ## Analyze A/B Test Results
#
#
# ## Table of Contents
# - [Introduction](#intro)
# - [Part I - Probability](#probability)
# - [Part II - A/B Test](#ab_test)
# - [Part III - Regression](#regression)
#
#
# <a id='intro'></a>
# ### Introduction
#
# A/B tests are very commonly... | Python | zaydzuhri_stack_edu_python |
function annotate self resultRow
begin
for tuple srcKey destKey in call iteritems
begin
set annotations at destKey = resultRow at srcKey
end
end function | def annotate(self, resultRow):
for srcKey, destKey in self.propDests.iteritems():
self.column.annotations[destKey] = resultRow[srcKey] | Python | nomic_cornstack_python_v1 |
function _seeker self pos=10 rew=true
begin
raise NotImplementedError
end function | def _seeker(self, pos=10, rew=True):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
import numpy as np
import cmath
from constants import *
from helper_functions_2Qubits import *
from TwoQubits import *
from TwoQubitGates import *
from SingleQudit import *
from SingleQuditGates import *
import random
function ideal_QFT_circuit input_pauli_basis
begin
string input: input_pauli_basis : coef. matrix in P... | import numpy as np
import cmath
from constants import *
from helper_functions_2Qubits import *
from TwoQubits import *
from TwoQubitGates import *
from SingleQudit import *
from SingleQuditGates import *
import random
def ideal_QFT_circuit(input_pauli_basis):
"""
input:
input_pauli_basis : coef. matrix in ... | Python | zaydzuhri_stack_edu_python |
comment -------------------------------------------------------------------------------
comment Name: module1
comment Purpose:
comment Author: Schuyler
comment Created: 31/05/2015
comment Copyright: (c) Schuyler 2015
comment Licence: <your licence>
comment ---------------------------------------------------------------... | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Schuyler
#
# Created: 31/05/2015
# Copyright: (c) Schuyler 2015
# Licence: <your licence>
#-------------------------------------------------------------------------------
import... | Python | zaydzuhri_stack_edu_python |
for i in range length n
begin
append x n at i
end
set k = length x // 2
print x at slice : k :
print x at slice k : : | for i in range(len(n)):
x.append(n[i])
k=len(x)//2
print(x[:k])
print(x[k:])
| Python | zaydzuhri_stack_edu_python |
function error message endl=true
begin
call pretty message color=RED endl=endl out_file=stderr
end function | def error(message: str, endl: bool = True) -> None:
pretty(message, color=Color.RED, endl=endl, out_file=sys.stderr) | Python | nomic_cornstack_python_v1 |
function make_multi_domain_set directory class_to_idx domain_to_idx extensions=none is_valid_file=none
begin
set instances = list
set directory = expand user path directory
set both_none = extensions is none and is_valid_file is none
set both_something = extensions is not none and is_valid_file is not none
if both_non... | def make_multi_domain_set(
directory: str,
class_to_idx: Dict[str, int],
domain_to_idx: Dict[str, int],
extensions: Optional[Tuple[str, ...]] = None,
is_valid_file: Optional[Callable[[str], bool]] = None,
) -> List[Tuple[str, int, int]]:
instances = []
directory = os.path.expanduser(director... | Python | nomic_cornstack_python_v1 |
class LogSystem
begin
function __init__ self
begin
set logs = dict
set time_granularity = dict string Year 0 ; string Month 1 ; string Day 2 ; string Hour 3 ; string Minute 4 ; string Second 5
set size_map = list 4 7 10 13 16 19
end function
function put self id timestamp
begin
set logs at timestamp = id
end function
... | class LogSystem:
def __init__(self):
self.logs = {}
self.time_granularity = {
"Year": 0, "Month": 1, "Day": 2, "Hour": 3, "Minute": 4, "Second": 5
}
self.size_map = [4, 7, 10, 13, 16, 19]
def put(self, id: int, timestamp: str) -> None:
self.logs[timestamp] =... | Python | jtatman_500k |
function _wrap_div self inner
begin
for tup in inner
begin
if tup at 0
begin
yield tup
end
end
end function | def _wrap_div(self, inner):
for tup in inner:
if tup[0]:
yield tup | Python | nomic_cornstack_python_v1 |
import sqlite3
from CreateDatabase import load_database
class EditDatabase
begin
string The first two passed values are the name of the attribute that you want to change and the value you want to change it to. The last two attribute are to identify the record that these values belong to with the attribute name first an... | import sqlite3
from CreateDatabase import load_database
class EditDatabase:
"""
The first two passed values are the name of the attribute that you want to change and the value you want to
change it to.
The last two attribute are to identify the record that these values belong to with the attribu... | Python | zaydzuhri_stack_edu_python |
function wait_for_stateful_block_init context mri timeout=DEFAULT_TIMEOUT
begin
string Wait until a Block backed by a StatefulController has initialized Args: context (Context): The context to use to make the child block mri (str): The mri of the child block timeout (float): The maximum time to wait
call when_matches l... | def wait_for_stateful_block_init(context, mri, timeout=DEFAULT_TIMEOUT):
"""Wait until a Block backed by a StatefulController has initialized
Args:
context (Context): The context to use to make the child block
mri (str): The mri of the child block
timeout (float): The maximum time to wa... | Python | jtatman_500k |
function differences arr
begin
set ret = list
set i = 0
comment ugh
for dc in arr
begin
if length ret == 0
begin
append ret dc
end
else
begin
append ret dc - arr at i
set i = i + 1
end
end
return ret
end function | def differences(arr: List[int]):
ret = []
i = 0
for dc in arr: # ugh
if len(ret) == 0:
ret.append(dc)
else:
ret.append(dc - arr[i])
i += 1
return ret | Python | nomic_cornstack_python_v1 |
function fast_dropout_tanh_layer x W b p alpha=1
begin
set mu2_x = call square mean T x 0
set si2_x = mean T call square x 0 - mu2_x
set s2 = dot alpha * p * 1 - p * mu2_x + p * si2_x call square W
set mu = p * dot x W + b
set pre = 2 * mu / square root 1 + 0.125 * pi * 4 * s2
set h = 2 * sigmoid pre - 1
return h
end f... | def fast_dropout_tanh_layer(x, W, b, p, alpha=1):
mu2_x = T.square(T.mean(x, 0))
si2_x = T.mean(T.square(x), 0) - mu2_x
s2 = T.dot(alpha * p * (1-p) * mu2_x + p * si2_x, T.square(W))
mu = p * T.dot(x, W) + b
pre = (2 * mu) / T.sqrt(1 + 0.125 * np.pi * (4 * s2))
h = 2 * T.nnet.sigmoid(pre) - 1
return h | Python | nomic_cornstack_python_v1 |
function lacppartnersystempriority self
begin
try
begin
return _lacppartnersystempriority
end
except Exception as e
begin
raise e
end
end function | def lacppartnersystempriority(self) :
try :
return self._lacppartnersystempriority
except Exception as e:
raise e | Python | nomic_cornstack_python_v1 |
function start self
begin
start call LoopingCall presence 10.0
end function | def start(self):
task.LoopingCall(self.presence).start(10.0) | Python | nomic_cornstack_python_v1 |
function quick groups colour period
begin
comment The cycle period cannot be longer than 1.2s (60/50)
comment or shorter than 0.5s
if groups == list 1
begin
if period is not none
begin
raise call ValueError string Quick Flash cycle periods must be longer than 0.5 seconds
end
return list tuple colour 250 tuple string Of... | def quick(groups, colour, period):
# The cycle period cannot be longer than 1.2s (60/50)
# or shorter than 0.5s
if groups == [1]:
if period is not None:
raise ValueError(
"Quick Flash cycle periods must be longer than 0.5 seconds"
)
return [
... | Python | nomic_cornstack_python_v1 |
comment !/home/mansuman/venv/bin/python
import sys
from pathlib import Path
import argparse
import pandas as pd
from nsepy import get_history
import logging
from datetime import date
from datetime import datetime as dt
from datetime import timedelta
import sqlite3
string NSE Cache implementation BEGIN
class NSEDB
begin... | #!/home/mansuman/venv/bin/python
import sys
from pathlib import Path
import argparse
import pandas as pd
from nsepy import get_history
import logging
from datetime import date
from datetime import datetime as dt
from datetime import timedelta
import sqlite3
"""
NSE Cache implementation BEGIN
"""
class NSEDB:
inst... | Python | zaydzuhri_stack_edu_python |
function make_discriminator
begin
set discriminator_model = sequential name=string discriminator
for i in range num_layers
begin
add discriminator_model call rnn_cell module_name hidden_dim return_sequences=true input_shape=tuple seq_len hidden_dim
end
add discriminator_model dense 1 activation=none
return discriminato... | def make_discriminator ():
discriminator_model = tf.keras.Sequential(name='discriminator')
for i in range(num_layers):
discriminator_model.add(rnn_cell(module_name, hidden_dim, return_sequences=True, input_shape=(seq_len, hidden_dim)))
discriminator_model.add(tf.keras.layers.Den... | Python | nomic_cornstack_python_v1 |
function test_sample_next_vertices
begin
set g = call Graph data
set current_vertices = array list 2 2 2 2
for idx in range 10
begin
set next_vertex_indices = call sample_next_vertices current_vertices degs
for elem in next_vertex_indices
begin
assert elem == 0 ? elem == 1
end
assert shape == shape
end
end function | def test_sample_next_vertices():
g = Graph(data)
current_vertices = np.array([2, 2, 2, 2])
for idx in range(10):
next_vertex_indices = g.sample_next_vertices(current_vertices, degs)
for elem in next_vertex_indices:
assert (elem == 0) | (elem == 1)
assert next_vertex_indic... | Python | nomic_cornstack_python_v1 |
function req_delete_taskid self
begin
if call helper_action_get_request_is_wrong string req_delete_taskid
begin
append error_msg_queue_list string Note deletion not performed.
return
end
if call helper_sessactionauth_is_wrong
begin
append error_msg_queue_list string Note deletion not performed - wrong session?
return
e... | def req_delete_taskid(self):
if self.helper_action_get_request_is_wrong("req_delete_taskid"):
self.error_msg_queue_list.append("Note deletion not performed.")
return
if self.helper_sessactionauth_is_wrong():
self.error_msg_queue_list.append("Note deletion not perform... | Python | nomic_cornstack_python_v1 |
function test_fma_invalid_param_intarray_intarray_intarray_intarray_596 self
begin
comment This version is expected to pass.
call fma floatarrayx floatarrayy floatarrayz floatarrayout
comment This is the actual test.
with assert raises TypeError
begin
call fma intarrayx intarrayy intarrayz intarrayout
end
end function | def test_fma_invalid_param_intarray_intarray_intarray_intarray_596(self):
# This version is expected to pass.
arrayfunc.fma(self.floatarrayx, self.floatarrayy, self.floatarrayz, self.floatarrayout)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.fma(self.intarrayx, self.intarrayy, se... | Python | nomic_cornstack_python_v1 |
import Tkinter as tk
from Tkinter import *
from PIL import Image , ImageTk
import os
function load_tk_image
begin
set img = open string lenna.jpg
set img_tk = call PhotoImage img
return img_tk
end function
function get_screenshot
begin
call system string import -window root screen_capture.png
set img = open string scre... | import Tkinter as tk
from Tkinter import *
from PIL import Image, ImageTk
import os
def load_tk_image():
img = Image.open("lenna.jpg")
img_tk = ImageTk.PhotoImage(img)
return img_tk
def get_screenshot():
os.system("import -window root screen_capture.png")
img = Image.open("screen_capture.png")
#img_tk = ImageTk... | Python | zaydzuhri_stack_edu_python |
import requests
function get_weather city
begin
set api_key = string f0f6c5a0f3d6e47ba8621ccad5a5367f
set base_url = string http://api.openweathermap.org/data/2.5/weather?
set final_url = base_url + string appid= + api_key + string &q= + city + string &units=metric
set weather_data = json get requests final_url
return ... | import requests
def get_weather(city):
api_key = "f0f6c5a0f3d6e47ba8621ccad5a5367f"
base_url = "http://api.openweathermap.org/data/2.5/weather?"
final_url = base_url + "appid=" + api_key + "&q=" + city + "&units=metric"
weather_data = requests.get(final_url).json()
return weather_data
... | Python | zaydzuhri_stack_edu_python |
import urllib2 , sys , re
from bs4 import BeautifulSoup as BS
from getMovies import getMagnet
import sys
function rottenList listURL
begin
comment Get the link of the list
set listURL = argv at 1
set hdr = dict string User-Agent string Mozilla/5.0
set req = call Request listURL headers=hdr
comment Get html doc
set html... | import urllib2, sys, re
from bs4 import BeautifulSoup as BS
from getMovies import getMagnet
import sys
def rottenList(listURL):
# Get the link of the list
listURL = sys.argv[1]
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(listURL,headers=hdr)
# Get html doc
html = urllib2.urlopen(... | Python | zaydzuhri_stack_edu_python |
function relevant_part self original pos sep=string
begin
string calculates the subword in a `sep`-splitted list of substrings of `original` that `pos` is ia.n
set start = reverse find original sep 0 pos + 1
set end = find original sep pos - 1
if end == - 1
begin
set end = length original
end
return tuple original at s... | def relevant_part(self, original, pos, sep=' '):
"""
calculates the subword in a `sep`-splitted list of substrings of
`original` that `pos` is ia.n
"""
start = original.rfind(sep, 0, pos) + 1
end = original.find(sep, pos - 1)
if end == -1:
end = len(or... | Python | jtatman_500k |
function primes n
begin
comment https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
if n < 6
begin
if n == 1
begin
return array list
end
else
if n == 2
begin
return array list 2
end
else
if n == 3
begin
return array list 2 3
end
else
if n == 4
begin
return array ... | def primes(n):
# https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python/3035188#3035188
if n < 6:
if n == 1:
return np.array([])
elif n == 2:
return np.array([2])
elif n == 3:
return np.array([2,3])
elif n ... | Python | nomic_cornstack_python_v1 |
string This program finds the HDI of a probability density function that is specified mathematically in python
from scipy.optimize import fmin
from scipy.stats import *
function HDIofICDF dist_name credMass=0.95 **args
begin
comment freeze distribution with given arguments
set distri = call dist_name keyword args
comme... | """
This program finds the HDI of a probability density function that is specified
mathematically in python
"""
from scipy.optimize import fmin
from scipy.stats import *
def HDIofICDF(dist_name, credMass=0.95, **args):
# freeze distribution with given arguments
distri = dist_name(**args)
# Initial guess... | Python | zaydzuhri_stack_edu_python |
function readPL sample_scrap_dir
begin
set scrap_contents = list directory sample_scrap_dir
comment Check for desired filetype, if not move to junk folder
for item in scrap_contents
begin
if is file path sample_scrap_dir + item == true and ends with lower item string .txt == false
begin
move sample_scrap_dir + item sam... | def readPL(sample_scrap_dir):
scrap_contents = os.listdir(sample_scrap_dir)
# Check for desired filetype, if not move to junk folder
for item in scrap_contents:
if (
os.path.isfile(sample_scrap_dir + item) == True and
item.lower().endswith(".txt") == False
):
... | Python | nomic_cornstack_python_v1 |
function pitch self
begin
return _pitch
end function | def pitch(self):
return self._pitch | Python | nomic_cornstack_python_v1 |
function test_prediction_key_required self
begin
set _config at string Prediction key = string
with call assertRaisesRegex ValueError string Please provide the prediction key
begin
call generate example=_example model=_model dataset=_dataset config=_config
end
end function | def test_prediction_key_required(self):
self._config['Prediction key'] = ''
with self.assertRaisesRegex(ValueError,
'Please provide the prediction key'):
self._gen.generate(
example=self._example,
model=self._model,
dataset=self._dataset,
... | Python | nomic_cornstack_python_v1 |
function test_delay_add_file_job_failure svc_client_cache it_remote_repo_url_temp_branch view_user_data
begin
from renku.ui.service.serializers.datasets import DatasetAddRequest
set tuple it_remote_repo_url branch = it_remote_repo_url_temp_branch
set tuple _ _ cache = svc_client_cache
set view_user_data at string user_... | def test_delay_add_file_job_failure(svc_client_cache, it_remote_repo_url_temp_branch, view_user_data):
from renku.ui.service.serializers.datasets import DatasetAddRequest
it_remote_repo_url, branch = it_remote_repo_url_temp_branch
_, _, cache = svc_client_cache
view_user_data["user_id"] = uuid.uuid4()... | Python | nomic_cornstack_python_v1 |
import ast
function detect_python_version script
begin
comment Parse the script into an abstract syntax tree (AST)
try
begin
set tree = parse ast script
end
except SyntaxError
begin
return string Syntax error: Invalid Python script
end
comment Extract all import statements from the script
set import_nodes = list compre... | import ast
def detect_python_version(script):
# Parse the script into an abstract syntax tree (AST)
try:
tree = ast.parse(script)
except SyntaxError:
return "Syntax error: Invalid Python script"
# Extract all import statements from the script
import_nodes = [node for node in ast.wa... | Python | jtatman_500k |
function send_image_list self img2d_list run=0 subrun=0 event=0
begin
set planes = keys img2d_list
sort planes
set rse = tuple run subrun event
info format string sending images with rse={} rse
set imgout_v = dict
set nsize_uncompressed = 0
set nsize_compressed = 0
set received_compressed = 0
set received_uncompressed... | def send_image_list(self,img2d_list, run=0, subrun=0, event=0):
planes = img2d_list.keys()
planes.sort()
rse = (run,subrun,event)
self._log.info("sending images with rse={}".format(rse))
imgout_v = {}
nsize_uncompressed = 0
nsize_compressed = 0
received_c... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
string input data class has methods to clean irregularly formatted data from starting data set inpatientCharges.csv
class inputData extends object
begin
function __init__ self fileName
begin
set fileName = fileName
set stateDict = dict string AL 0 ;... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
'''
input data class has methods to clean irregularly formatted data from starting data set inpatientCharges.csv
'''
class inputData(object):
def __init__(self, fileName):
self.fileName = fileName
self.stateDict = {'AL': 0, 'A... | Python | zaydzuhri_stack_edu_python |
function list_tasks q=none
begin
set to = dict string p dict ; string v dict
for tuple k v in items to
begin
set pin = pin_ids at k
set state = strip check output list string gpio string read pin
set to at k at string state = if expression state == string 0 then string on else string off
set to at k at string on_id =... | def list_tasks(q = None):
to = {"p":{}, "v":{}}
for k, v in to.items():
pin = HeaterController.pin_ids[k]
state = subprocess.check_output(["gpio", 'read', pin]).strip()
to[k]["state"] = "on" if state=="0" else "off"
to[k]["on_id"] = ""
to[k]["... | Python | nomic_cornstack_python_v1 |
comment 执行到大于100的地方停止
comment sum=0
comment for num in range(1,101):
comment if sum>=100:
comment break
comment else:
comment sum += num
comment pass
comment print('执行到%i总和大于100,总和为%i'%(num,sum))
comment for写99乘法表
comment for hang in range(1,10):
comment for lie in range(1,10):
comment if hang<=lie:
comment print('%d*%... | # 执行到大于100的地方停止
# sum=0
# for num in range(1,101):
# if sum>=100:
# break
# else:
# sum += num
# pass
# print('执行到%i总和大于100,总和为%i'%(num,sum))
# for写99乘法表
# for hang in range(1,10):
# for lie in range(1,10):
# if hang<=lie:
# print('%d*%d=%d'%(hang... | Python | zaydzuhri_stack_edu_python |
function select_detail_substitute self user_answer_choice_id_substitute
begin
set cursor = call cursor MySQLCursorPrepared
execute cursor format string SELECT name_food, nutriscore, description, store, link FROM Food WHERE id = (SELECT id_substitute_chooses FROM Favorite WHERE id = {}) integer user_answer_choice_id_sub... | def select_detail_substitute(self, user_answer_choice_id_substitute):
self.cursor = self.data_base.cursor(MySQLCursorPrepared)
self.cursor.execute("""SELECT name_food, nutriscore, description, store, link
FROM Food
WHERE id =
... | Python | nomic_cornstack_python_v1 |
function reload_data_into_buckets self
begin
set doc_loading_spec = call get_crud_template_from_package data_spec_name
set doc_loading_task = call run_scenario_from_spec task cluster buckets doc_loading_spec mutation_num=0 batch_size=batch_size
if result is false
begin
call fail string Initial reloading failed
end
set ... | def reload_data_into_buckets(self):
doc_loading_spec = \
self.bucket_util.get_crud_template_from_package(
self.data_spec_name)
doc_loading_task = \
self.bucket_util.run_scenario_from_spec(
self.task,
self.cluster,
se... | Python | nomic_cornstack_python_v1 |
comment SAFE TEAM
comment distributed under license: CC BY-NC-SA 4.0 (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode)
import argparse
import os
import sys
from subprocess import call
class Downloader
begin
function __init__ self
begin
set apt_url = string https://drive.google.com/file/d/1t4_FS0_8DIPAyG5guG... | # SAFE TEAM
# distributed under license: CC BY-NC-SA 4.0 (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode)
import argparse
import os
import sys
from subprocess import call
class Downloader:
def __init__(self):
self.apt_url = "https://drive.google.com/file/d/1t4_FS0_8DIPAyG5guGbK6... | Python | zaydzuhri_stack_edu_python |
function __init__ self response content
begin
set _status_code = status
set _header = response
set _body = call _decode_content response content
end function | def __init__(self, response, content):
self._status_code = response.status
self._header = response
self._body = self._decode_content(response, content) | Python | nomic_cornstack_python_v1 |
function printVer self
begin
if epoch != string 0
begin
set ver = string %s:%s-%s % tuple epoch version release
end
else
begin
set ver = string %s-%s % tuple version release
end
return ver
end function | def printVer(self):
if self.epoch != '0':
ver = '%s:%s-%s' % (self.epoch, self.version, self.release)
else:
ver = '%s-%s' % (self.version, self.release)
return ver | 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.