code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function setDescription self description
begin
call TiePointGrid_setDescription _obj description
return
end function | def setDescription(self, description):
TiePointGrid_setDescription(self._obj, description)
return | Python | nomic_cornstack_python_v1 |
string @project: Scientific-and-Engineering-Computing @author: sam @file: main.py @ide: PyCharm @time: 2018-11-30 01:41:19 @blog: https://jiahaoplus.com
from linear_equations import *
from time import time
function get_equation_set_2 n
begin
string Get equation 2 :param n: int :return: matrix A, b
set A = call eye n
se... | """
@project: Scientific-and-Engineering-Computing
@author: sam
@file: main.py
@ide: PyCharm
@time: 2018-11-30 01:41:19
@blog: https://jiahaoplus.com
"""
from linear_equations import *
from time import time
def get_equation_set_2(n):
"""Get equation 2
:param n: int
:return: matrix A, b
"""
A = eye... | Python | zaydzuhri_stack_edu_python |
class Node extends object
begin
function __init__ self data next=none
begin
set data = data
set next = next
end function
end class
function print_list_reversingly1 head
begin
string 用栈实现 时间O(n), 空间O(1) :param head: Node
if head is none
begin
return
end
set stack = list
set node = head
while node is not none
begin
appe... | class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def print_list_reversingly1(head):
"""
用栈实现
时间O(n), 空间O(1)
:param head: Node
"""
if head is None:
return
stack = []
node = head
while node is not None:
st... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment Created by: ludi
comment Created on: 2020/1/8
import numpy as np
from layer import Layer , xavier_uniform , Tensor
class Conv2d extends Layer
begin
function __init__ self in_channels out_channels k_size=tuple 3 3 stride=tuple 1 1 padding=none requires_g... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by: ludi
# Created on: 2020/1/8
import numpy as np
from .layer import Layer, xavier_uniform, Tensor
class Conv2d(Layer):
def __init__(self, in_channels, out_channels, k_size=(3, 3), stride=(1, 1), padding=None, requires_grad=True):
super().__init__... | Python | zaydzuhri_stack_edu_python |
for i in range length numbers - 1 - 1 - 1
begin
print numbers at i
end | for i in range(len(numbers)-1, -1, -1):
print(numbers[i])
| Python | flytech_python_25k |
comment String Rotation: Assume you have a method isSubstring which checks if one word
comment is a substring of another. Given two strings s1 and s2, write code to check if
comment s2 is a rotation of s1 using only one call to isSubstring
import sys
function isSubstring s1 s2
begin
return s1 in s2
end function
comment... | # String Rotation: Assume you have a method isSubstring which checks if one word
# is a substring of another. Given two strings s1 and s2, write code to check if
# s2 is a rotation of s1 using only one call to isSubstring
import sys
def isSubstring(s1, s2):
return s1 in s2
# Attempt 1: I was pretty proud of this... | Python | zaydzuhri_stack_edu_python |
function run_tests_from_module module verbosity=1
begin
set suite = call TestSuite
set loader = defaultTestLoader
call addTest call loadTestsFromModule module
run suite
end function | def run_tests_from_module(module, verbosity=1):
suite = unittest.TestSuite()
loader = unittest.defaultTestLoader
suite.addTest(loader.loadTestsFromModule(module))
unittest.TextTestRunner(verbosity=verbosity).run(suite) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment The script has been used to translate the annotations files given by the robot to more
comment standard formats like the [Imagenet](http://www.image-net.org/)'s or the
comment [KITTI](http://www.cvlibs.net/datasets/kitti/)'s.
comment author: Elisa Maiettini
comment date: 06/03/2017
impo... | #!/usr/bin/python
#
# The script has been used to translate the annotations files given by the robot to more
# standard formats like the [Imagenet](http://www.image-net.org/)'s or the
# [KITTI](http://www.cvlibs.net/datasets/kitti/)'s.
#
# author: Elisa Maiettini
# date: 06/03/2017
#
import os
import translate_annotat... | Python | zaydzuhri_stack_edu_python |
function put self key item
begin
if key and item
begin
set cache_data at key = item
end
end function | def put(self, key, item):
if key and item:
self.cache_data[key] = item | Python | nomic_cornstack_python_v1 |
string 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。 返回被除数 dividend 除以除数 divisor 得到的商。 示例 1: 输入: dividend = 10, divisor = 3 输出: 3 示例 2: 输入: dividend = 7, divisor = -3 输出: -2 说明: 被除数和除数均为 32 位有符号整数。 除数不为 0。 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。
class Solution1
begin
function... | """
给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。
返回被除数 dividend 除以除数 divisor 得到的商。
示例 1:
输入: dividend = 10, divisor = 3
输出: 3
示例 2:
输入: dividend = 7, divisor = -3
输出: -2
说明:
被除数和除数均为 32 位有符号整数。
除数不为 0。
假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−231, 231 − 1]。本题中,如果除法结果溢出,则返回 231 − 1。
"""
class Solution1:
... | Python | zaydzuhri_stack_edu_python |
function from_dict cls dikt
begin
return call deserialize_model dikt cls
end function | def from_dict(cls, dikt):
return util.deserialize_model(dikt, cls) | Python | nomic_cornstack_python_v1 |
function _add_selection self nick sel
begin
if not call has_key call name
begin
set __selections_ at call name = dict
end
end function | def _add_selection ( self , nick , sel ) :
if not self.__selections_.has_key ( self.name() ) :
self.__selections_[ self.name() ] = {}
| Python | nomic_cornstack_python_v1 |
function get_container_version
begin
string Return the version of the docker container running the present server, or '' if not in a container
set root_dir = directory name path real path path argv at 0
set version_file = join path root_dir string VERSION
if exists path version_file
begin
with open version_file as f
be... | def get_container_version():
"""Return the version of the docker container running the present server,
or '' if not in a container"""
root_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
version_file = os.path.join(root_dir, 'VERSION')
if os.path.exists(version_file):
with open(version_... | Python | jtatman_500k |
function isNewton self
begin
return call Unit_isNewton self
end function | def isNewton(self):
return _libsbml.Unit_isNewton(self) | Python | nomic_cornstack_python_v1 |
function next_min_winner_ballots self sample_size
begin
return call find_kmin false
end function | def next_min_winner_ballots(self, sample_size) -> int:
return self.find_kmin(False) | Python | nomic_cornstack_python_v1 |
from funcparserlib.lexer import make_tokenizer
from funcparserlib.parser import some , many , skip , maybe
from model import Task , Rule
function tokenize str
begin
set specs = list tuple string With tuple string WITH tuple string In tuple string IN tuple string Set tuple string SET tuple string Equals tuple string = t... | from funcparserlib.lexer import make_tokenizer
from funcparserlib.parser import some, many, skip, maybe
from model import Task, Rule
def tokenize(str):
specs = [
('With', (r'WITH',)),
('In', (r'IN',)),
('Set', (r'SET',)),
('Equals', (r'=',)),
('Space', (r'[ \t\... | Python | zaydzuhri_stack_edu_python |
function iteration ins_in_out matrix
begin
set tuple size _ = shape
set slices : list
if not size % 2
begin
set slices = call slicing matrix 2 2
end
else
if not size % 3
begin
set slices = call slicing matrix 3 3
end
set trans_slices = generator expression generator expression ins_in_out at tuple map tuple mat for mat ... | def iteration(ins_in_out: list, matrix):
size, _ = matrix.shape
slices: list
if not size % 2:
slices = slicing(matrix, 2, 2)
elif not size % 3:
slices = slicing(matrix, 3, 3)
trans_slices = ((ins_in_out[tuple(map(tuple, mat))]
for mat in mat_slice) for ma... | Python | nomic_cornstack_python_v1 |
function passthrough self passthrough
begin
set _passthrough = passthrough
end function | def passthrough(self, passthrough):
self._passthrough = passthrough | Python | nomic_cornstack_python_v1 |
import os
import csv
import numpy as np
import matplotlib.pylab as plt
import ExampleClass
set dirName = string /Users/sauveur_c/git/Random Data
set fileName = string sampleData.dat
with open join path dirName fileName string r as csvfile
begin
set dataReader = reader csvfile delimiter=string ,
set data = list
for row ... | import os
import csv
import numpy as np
import matplotlib.pylab as plt
import ExampleClass
dirName = '/Users/sauveur_c/git/Random Data'
fileName = 'sampleData.dat'
with open(os.path.join(dirName,fileName), 'r') as csvfile:
dataReader = csv.reader(csvfile, delimiter = ',')
data = list()
for row in dataRea... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
import requests
function find_jumia search
begin
for n in search
begin
set word = replace search string string +
end
set url = string https://www.jumia.com.ng/catalog/?q= + word
set article = get requests url
set jumia = call BeautifulSoup text string html.parser
set item_name = list
set... | from bs4 import BeautifulSoup
import requests
def find_jumia(search):
for n in search:
word = search.replace(' ', '+')
url = "https://www.jumia.com.ng/catalog/?q=" + word
article = requests.get(url)
jumia = BeautifulSoup(article.text, "html.parser")
item_name = []
item_price = []
... | Python | zaydzuhri_stack_edu_python |
function test_post_metric client action
begin
set tuple u u2 s url = call prepare_users_and_snip client
post url dict string action action
assert get attribute get objects snip=s action == 1
post url dict string action action
assert get attribute get objects snip=s action == 1
call login email=email password=DEF_PASS
p... | def test_post_metric(client, action):
u, u2, s, url = prepare_users_and_snip(client)
client.post(url, {'action': action})
assert getattr(PostMetrics.objects.get(snip=s), action) == 1
client.post(url, {'action': action})
assert getattr(PostMetrics.objects.get(snip=s), action) == 1
client.login(e... | Python | nomic_cornstack_python_v1 |
function MassageContentForRenderView self content
begin
set new_content = call MassageImageContentForRenderView content
set new_content = call MassageMediaContentForRenderView new_content
set new_content = call MassageLinkResourceContentForRenderView new_content
return new_content
end function | def MassageContentForRenderView(self, content):
new_content = self.MassageImageContentForRenderView(content)
new_content = self.MassageMediaContentForRenderView(new_content)
new_content = self.MassageLinkResourceContentForRenderView(new_content)
return new_content | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment coding:utf-8
string @author: zyc @contact: yaochen.zhao@colasoft.com.cn @software: PyCharm @file: 09_selenium_wait.py @time: 2018/9/12 15:49
from selenium import webdriver
comment 隐式等待,没找到节点时将等一段时间再查找DOM
comment browser = webdriver.Chrome()
comment browser.implicitly_wait(10)
comment ur... | #!/usr/bin/python
# coding:utf-8
"""
@author: zyc
@contact: yaochen.zhao@colasoft.com.cn
@software: PyCharm
@file: 09_selenium_wait.py
@time: 2018/9/12 15:49
"""
from selenium import webdriver
# 隐式等待,没找到节点时将等一段时间再查找DOM
# browser = webdriver.Chrome()
# browser.implicitly_wait(10)
# url = 'https://www.zhihu.com/explore... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set m = 1000
set bucket = list none * 1000
end function | def __init__(self):
self.m = 1000
self.bucket = [None] * 1000 | Python | nomic_cornstack_python_v1 |
comment Functions and files
comment ===============================================================================
comment from sys import argv
comment 2
comment 3 script, input_file = argv
comment 4
comment 5 def print_all(f):
comment 6 print f.read()
comment 7
comment 8 def rewind(f):
comment 9 f.seek(0)
comment 10
... | #Functions and files
#===============================================================================
# from sys import argv
# 2
# 3 script, input_file = argv
# 4
# 5 def print_all(f):
# 6 print f.read()
# 7
# 8 def rewind(f):
# 9 f.seek(0)
# 10
# 11 def print_a_line(line_count, f):
# 12 print line_count... | Python | zaydzuhri_stack_edu_python |
comment pylint: disable=invalid-name
function at self pos
begin
try
begin
return call _type _event_list at pos
end
except IndexError
begin
raise call CollectionException string invalid index given to at()
end
end function | def at(self, pos): # pylint: disable=invalid-name
try:
return self._type(self._event_list[pos])
except IndexError:
raise CollectionException('invalid index given to at()') | Python | nomic_cornstack_python_v1 |
function _get_daily_date_range self metric_date delta
begin
set dates = list metric_date
set start_date = metric_date
set end_date = metric_date + delta
while month < month or year < year
begin
set days_in_month = call monthrange year month at 1
comment shift along to the next month as one of the months we will have to... | def _get_daily_date_range(self, metric_date, delta):
dates = [metric_date]
start_date = metric_date
end_date = metric_date + delta
while start_date.month < end_date.month or start_date.year < end_date.year:
days_in_month = calendar.monthrange(start_date.year, start_date.mont... | Python | nomic_cornstack_python_v1 |
function magnitudeSquared self ignoreVertical=false
begin
if not ignoreVertical
begin
if _magnitudeSquared == __MAGNITUDE_UNDEFINED__
begin
set _magnitudeSquared = x ^ 2 + y ^ 2 + z ^ 2
end
return _magnitudeSquared
end
else
begin
if _2dMagnitudeSquared == __MAGNITUDE_UNDEFINED__
begin
set _2dMagnitudeSquared = x ^ 2 + ... | def magnitudeSquared(self, ignoreVertical=False):
if(not ignoreVertical):
if(self._magnitudeSquared == __MAGNITUDE_UNDEFINED__):
self._magnitudeSquared = (self.x **2) + (self.y **2) + (self.z **2)
return self._magnitudeSquared
else:
if(self._2dMagnitud... | Python | nomic_cornstack_python_v1 |
string # -*- coding: utf-8 -*- Your English teacher loves to bring new stuff to the class, and today it wasn't different. There is a city, according to your teacher, where the people take really seriously the way they talk to each other. In particular, when two people are talking, they think a lot in the sentence that ... | '''
# -*- coding: utf-8 -*-
Your English teacher loves to bring new stuff to the class, and today it wasn't different. There is a city, according to your
teacher, where the people take really seriously the way they talk to each other. In particular, when two people are talking,
they think a lot in the sentence that the... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import ast
import warnings
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import os
import numpy as np
import random
filter warnings string ignore
set SMALL_SIZE = 16
set MEDIUM_SIZE = 14
set BIGGER_SIZE = 20
... | import pandas as pd
import ast
import warnings
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import os
import numpy as np
import random
warnings.filterwarnings('ignore')
SMALL_SIZE = 16
MEDIUM_SIZE = 14
BIGGER_SIZE = 20
plt.r... | Python | zaydzuhri_stack_edu_python |
function verificaTurno turno
begin
if turno == string matutino or turno == string vespertino or turno == string noturno
begin
return turno
end
else
begin
print string Turno inválido!
return string
end
end function
class Atendentes
begin
comment Construtor
function __init__ self codigo nome dataNascimento salario turno... | def verificaTurno(turno):
if turno == "matutino" or turno == "vespertino" or turno == "noturno":
return turno
else:
print("Turno inválido!")
return ""
class Atendentes:
# Construtor
def __init__(self, codigo, nome, dataNascimento, salario, turno):
self.codigo =... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import sys
append path string /home/vishlesh/PolicyBench/
from PolicyGenerator.subnet import *
from PolicyGenerator.Reachability.TraverseSourceInfoGraph import *
from PolicyGenerator.Reachability.TraverseDestInfoGraph import DestInfo
import argparse
function main
begin
set parser = call Ar... | #!/usr/bin/env python3
import sys
sys.path.append('/home/vishlesh/PolicyBench/')
from PolicyGenerator.subnet import *
from PolicyGenerator.Reachability.TraverseSourceInfoGraph import *
from PolicyGenerator.Reachability.TraverseDestInfoGraph import DestInfo
import argparse
def main():
parser = argparse.ArgumentPar... | Python | zaydzuhri_stack_edu_python |
function overlap_check reference_system positions platform_name=none precision=none nsteps=50 nsamples=200 factory_args=none cached_trajectory_filename=none
begin
set temperature = 300.0 * kelvin
set pressure = 1.0 * atmospheres
set collision_rate = 5.0 / picoseconds
set timestep = 2.0 * femtoseconds
set kT = kB * temp... | def overlap_check(reference_system, positions, platform_name=None, precision=None, nsteps=50, nsamples=200, factory_args=None, cached_trajectory_filename=None):
temperature = 300.0 * unit.kelvin
pressure = 1.0 * unit.atmospheres
collision_rate = 5.0 / unit.picoseconds
timestep = 2.0 * unit.femtoseconds
... | Python | nomic_cornstack_python_v1 |
function solve S
begin
set mod = 10 ^ 9 + 7
set N = length S
set Aquest = list
set Cquest = list
set tuple cntA cntquest = tuple 0 0
for i in range N
begin
if S at i in string B?
begin
append Aquest list cntA cntquest
end
if S at i == string A
begin
set cntA = cntA + 1
end
if S at i == string ?
begin
set cntquest = c... | def solve(S):
mod = 10**9+7
N = len(S)
Aquest = []
Cquest = []
cntA,cntquest = 0,0
for i in range(N):
if S[i] in 'B?':
Aquest.append([cntA,cntquest])
if S[i]=='A':
cntA += 1
if S[i]=='?':
cntquest += 1
cntC,cntquest = 0,0
for i ... | Python | zaydzuhri_stack_edu_python |
function years_since date
begin
set delta = now - string parse time date string %d-%m-%Y
return integer days / 365
end function | def years_since(date: str) -> int:
delta = datetime.now() - datetime.strptime(date, "%d-%m-%Y")
return int(delta.days / 365) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment RMS 2018
comment Read binary files and metadata
comment We wil use this script to to processing on the noise data in each grid cell in our model
import struct
import pickle
import pandas as pd
import numpy as np
import glob
from scipy.interpolate import interp1d
from scipy.integrate... | #!/usr/bin/env python
#RMS 2018
#Read binary files and metadata
#We wil use this script to to processing on the noise data in each grid cell in our model
import struct
import pickle
import pandas as pd
import numpy as np
import glob
from scipy.interpolate import interp1d
from scipy.integrate import cumtrapz
from dat... | Python | zaydzuhri_stack_edu_python |
import re
from multiprocessing import Pool
import numpy as np
from DBModels.Lexicon import *
from controllers.Pickles.Pickle_Saver import *
comment number of partitions to split dataframe
set num_partitions = 6
comment number of cores on your machine
set num_cores = 6
comment script_path = os.path.dirname(os.path.dirna... | import re
from multiprocessing import Pool
import numpy as np
from DBModels.Lexicon import *
from controllers.Pickles.Pickle_Saver import *
num_partitions = 6 # number of partitions to split dataframe
num_cores = 6 # number of cores on your machine
#
# script_path = os.path.dirname(os.path.dirname(__file__))
# f... | Python | zaydzuhri_stack_edu_python |
function set_mode_flag self flag enable
begin
string Enables/ disables MAV_MODE_FLAG @param flag The mode flag, see MAV_MODE_FLAG enum @param enable Enable the flag, (True/False)
if call mavlink10
begin
set mode = base_mode
if enable == true
begin
set mode = mode ? flag
end
else
if enable == false
begin
set mode = mode... | def set_mode_flag(self, flag, enable):
'''
Enables/ disables MAV_MODE_FLAG
@param flag The mode flag,
see MAV_MODE_FLAG enum
@param enable Enable the flag, (True/False)
'''
if self.mavlink10():
mode = self.base_mode
if (enable == True):
... | Python | jtatman_500k |
function offset_to_pts self center_list pred_list
begin
set pts_list = list
for i_lvl in range length point_strides
begin
set pts_lvl = list
for i_img in range length center_list
begin
set pts_center = repeat 1 num_points
set pts_shift = pred_list at i_lvl at i_img
set yx_pts_shift = view permute pts_shift 1 2 0 - 1 ... | def offset_to_pts(self, center_list, pred_list):
pts_list = []
for i_lvl in range(len(self.point_strides)):
pts_lvl = []
for i_img in range(len(center_list)):
pts_center = center_list[i_img][i_lvl][:, :2].repeat(
1, self.num_points)
... | Python | nomic_cornstack_python_v1 |
import sys , os , argparse
if __name__ == string __main__
begin
set OutDir = get current directory
set parser = call ArgumentParser description=string This script converts DAOD filelists to AOD filelists which then can be used for creating pileup reweighting files. prog=string CreateAODFromDAODList formatter_class=Argu... | import sys, os, argparse
if __name__ == '__main__':
OutDir = os.getcwd()
parser = argparse.ArgumentParser(description='This script converts DAOD filelists to AOD filelists which then can be used for creating pileup reweighting files.', prog='CreateAODFromDAODList', formatter_class=argparse.ArgumentDefaultsH... | Python | zaydzuhri_stack_edu_python |
comment # Mask R-CNN Demo
comment A quick intro to using the pre-trained model to detect and segment objects.
import os
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import utils
import model as modellib
import visualize
from config import Co... | # # Mask R-CNN Demo
#
# A quick intro to using the pre-trained model to detect and segment objects.
import os
import sys
import random
import math
import numpy as np
import skimage.io
import matplotlib
import matplotlib.pyplot as plt
import utils
import model as modellib
import visualize
from config import Config
#... | Python | zaydzuhri_stack_edu_python |
from CreatureTools import Creature
import numpy as np
from tqdm import tqdm
import multiprocessing as mp
from tabulate import tabulate
import os
import csv
import pandas as pd
function genGen
begin
set params = dict string num_char 100 ; string variables string X ; string constants string F+- ; string axiom string FX ;... | from CreatureTools import Creature
import numpy as np
from tqdm import tqdm
import multiprocessing as mp
from tabulate import tabulate
import os
import csv
import pandas as pd
def genGen():
params = {
'num_char': 100,
'variables': 'X',
'constants': 'F+-',
'axiom': 'FX',
'ru... | Python | zaydzuhri_stack_edu_python |
import tweepy
import datetime
import csv
set consumer_key = string YOUR_CONSUMER_KEY
set consumer_secret = string YOUR_CONSUMER_KEY_SECRET
set access_token = string YOUR_ACCESS_TOKEN
set access_token_secret = string YOUR_ACCESS_SECRET
function search hashtag
begin
set auth = call OAuthHandler consumer_key consumer_secr... | import tweepy
import datetime
import csv
consumer_key="YOUR_CONSUMER_KEY"
consumer_secret="YOUR_CONSUMER_KEY_SECRET"
access_token="YOUR_ACCESS_TOKEN"
access_token_secret="YOUR_ACCESS_SECRET"
def search(hashtag):
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_... | Python | zaydzuhri_stack_edu_python |
function get_instruction_low_level_il self data addr il
begin
set data = string data
set length = call c_ulonglong
set value = length data
set buf = call
call memmove buf data length data
call BNGetInstructionLowLevelIL handle buf addr length handle
return value
end function | def get_instruction_low_level_il(self, data, addr, il):
data = str(data)
length = ctypes.c_ulonglong()
length.value = len(data)
buf = (ctypes.c_ubyte * len(data))()
ctypes.memmove(buf, data, len(data))
core.BNGetInstructionLowLevelIL(self.handle, buf, addr, length, il.handle)
return length.value | Python | nomic_cornstack_python_v1 |
import time
from datetime import datetime
import paho.mqtt.client as mqtt
import psycopg2
class MqttLogger
begin
function __init__ self
begin
set client = none
end function
function on_connect self client userdata flags rc
begin
print call get_time + string : + string Connected with result code + string rc
set topics =... | import time
from datetime import datetime
import paho.mqtt.client as mqtt
import psycopg2
class MqttLogger:
def __init__(self):
self.client = None
def on_connect(self, client, userdata, flags, rc):
print(self.get_time() + ": " + "Connected with result code " + str(rc))
topics = [("#... | Python | zaydzuhri_stack_edu_python |
function sanitize_json value
begin
comment https://stackoverflow.com/questions/39491420/python-jsonexpecting-property-name-enclosed-in-double-quotes
set value = replace value string string
set value = replace value string string
set value = replace value string ,} string }
set value = replace value string ,] string ]... | def sanitize_json(value):
# https://stackoverflow.com/questions/39491420/python-jsonexpecting-property-name-enclosed-in-double-quotes
value = value.replace('\t', '')
value = value.replace('\n', '')
value = value.replace(',}', '}')
value = value.replace(',]', ']')
return value | Python | nomic_cornstack_python_v1 |
function name self
begin
return get pulumi self string name
end function | def name(self) -> str:
return pulumi.get(self, "name") | Python | nomic_cornstack_python_v1 |
function multidimensional_ability_map dataset difficulty discrimination options=none
begin
set n_factors = shape at 1
if n_factors < 2
begin
raise call AssertionError string Number of factors specified must be greater than 1.
end
set options = call validate_estimation_options options
set cpr_result = call condition_pol... | def multidimensional_ability_map(dataset, difficulty, discrimination, options=None):
n_factors = discrimination.shape[1]
if n_factors < 2:
raise AssertionError("Number of factors specified must be greater than 1.")
options = validate_estimation_options(options)
cpr_result = condition_polytomo... | Python | nomic_cornstack_python_v1 |
function generate env
begin
string Add Builders and construction variables for clang to an Environment.
call generate env
set env at string CC = call Detect compilers or string clang
if env at string PLATFORM in list string cygwin string win32
begin
set env at string SHCCFLAGS = call CLVar string $CCFLAGS
end
else
begi... | def generate(env):
"""Add Builders and construction variables for clang to an Environment."""
SCons.Tool.cc.generate(env)
env['CC'] = env.Detect(compilers) or 'clang'
if env['PLATFORM'] in ['cygwin', 'win32']:
env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
else:
env['SHCCFLAGS'] = ... | Python | jtatman_500k |
function dumps self
begin
set params = dict
set params at string type = type
set params at string cid = cid
set params at string wid = wid
set params at string param_info = param_info
set params at string args = args
return dumps params
end function | def dumps(self):
params = {}
params['type'] = self.type
params['cid'] = self.cid
params['wid'] = self.wid
params['param_info'] = self.param_info
params['args'] = self.args
return simplejson.dumps(params) | Python | nomic_cornstack_python_v1 |
function add_wikicfp_conf conference dbpath
begin
set conn = call connect string dbpath
set cur = call cursor
execute cur string INSERT OR REPLACE INTO WikicfpConferences (series, title, url, timetable, year, wayback_url, categories, accessible, crawled) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) tuple string conference at str... | def add_wikicfp_conf(conference: 'WikiConferenceItem', dbpath: str):
conn = sqlite3.connect(str(dbpath))
cur = conn.cursor()
cur.execute(
"INSERT OR REPLACE INTO WikicfpConferences\
(series, title, url, timetable, year, wayback_url, categories, accessible, crawled) \
... | Python | nomic_cornstack_python_v1 |
function senstivity_analysis image_dict outdir result_file cwindows eta_values ct_values scale_factors lf_dict image_date=string 12292015 apply_masks=true wf=true verbose=false ensemble_avg=true
begin
set pol_vec = call calc_pol_vec_dict
set ifg_dir = join path outdir string Common
make directories list ifg_dir
set tup... | def senstivity_analysis(image_dict, outdir, result_file, cwindows, eta_values, ct_values, scale_factors, lf_dict,
image_date='12292015', apply_masks=True, wf=True, verbose=False, ensemble_avg=True):
pol_vec = calc_pol_vec_dict()
ifg_dir = os.path.join(outdir, 'Common')
makedirs([ifg... | Python | nomic_cornstack_python_v1 |
import reports
function export_report file
begin
set filename = open string export_report.txt string w
write filename string call count_games file + string
write filename string call decide file 2005 + string
write filename string call get_latest file + string
write filename string call count_by_genre file string eh + ... | import reports
def export_report(file):
filename = open("export_report.txt", "w")
filename.write(str(reports.count_games(file)) + "\n")
filename.write(str(reports.decide(file, 2005)) + "\n")
filename.write(str(reports.get_latest(file)) + "\n")
filename.write(str(reports.count_by_genre(file, "eh"))... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import scipy.optimize
import config as cfg
class RecordingCallback extends object
begin
function __init__ self f
begin
set f = f
set best_val = Inf
set best_P = none
end function
function __call__ self P
begin
set val = f dist P
if val < best_val
begin
set best_val = val
set best_P = P
end
end functi... | import numpy as np
import scipy.optimize
import config as cfg
class RecordingCallback(object):
def __init__(self, f):
self.f = f
self.best_val = np.Inf
self.best_P = None
def __call__(self, P):
val = self.f(P)
if val < self.best_val:
self.best_val... | Python | zaydzuhri_stack_edu_python |
function getBomRowCad self bomLineBrowse
begin
set ctx = copy context
set ctx at string lang = string en_GB
return list itemnum call emptyStringIfFalse name name engineering_code product_qty
end function | def getBomRowCad(self, bomLineBrowse):
ctx = self.env.context.copy()
ctx['lang'] = 'en_GB'
return [bomLineBrowse.itemnum,
emptyStringIfFalse(bomLineBrowse.product_id.name),
bomLineBrowse.product_id.with_context(ctx).name,
bomLineBrowse.produc... | Python | nomic_cornstack_python_v1 |
function GetColumnWidth self column
begin
return call GetColumnWidth column
end function | def GetColumnWidth(self, column):
return self._header_win.GetColumnWidth(column) | Python | nomic_cornstack_python_v1 |
function _upgrade_config x plugin_versions
begin
if is instance x dict
begin
set new_x = dict
for tuple k v in items x
begin
set new_x at k = call _upgrade_config v plugin_versions
end
set type_hint = get new_x string type_hint
if type_hint is not none
begin
set type_hint_lineage = call get_type_hint_lineage type_hint... | def _upgrade_config(x: Union[dict, List[dict]], plugin_versions: Dict[str, int]
) -> Union[dict, List[dict]]:
if isinstance(x, dict):
new_x = {}
for k, v in x.items():
new_x[k] = _upgrade_config(v, plugin_versions)
type_hint = new_x.get('type_hint')
if... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env.python
comment coding=utf-8
print string 模组更通俗地叫‘类库’或‘模块’
print string 如果想实现与时间有关的功能,就需要调用系统的‘time’模块
print string 如果想实现与文件和文件夹有关的操作,就需要用到‘os’模块
print string 例如我们通过‘Selenium’实现的‘Web’自动化测试,那么‘Selenium’对于‘Python’来说就是一个第三方扩展模块
print string 在‘Python’里,通过‘import...’或‘from...import...’的方式引用模块
print stri... | #!/usr/bin/env.python
# coding=utf-8
print("模组更通俗地叫‘类库’或‘模块’")
print("如果想实现与时间有关的功能,就需要调用系统的‘time’模块")
print("如果想实现与文件和文件夹有关的操作,就需要用到‘os’模块")
print("例如我们通过‘Selenium’实现的‘Web’自动化测试,那么‘Selenium’对于‘Python’来说就是一个第三方扩展模块")
print("在‘Python’里,通过‘import...’或‘from...import...’的方式引用模块")
print("下面引用‘time’模块")
import ti... | Python | zaydzuhri_stack_edu_python |
function is_point_inside_hypersphere point c r
begin
return norm point - c < r
end function | def is_point_inside_hypersphere(point: np.array, c: List[float], r: float) -> bool:
return np.linalg.norm(point - c) < r | Python | nomic_cornstack_python_v1 |
function check_choice self player_guess_word
begin
if player_guess_word in player_guess_list
begin
set message = string Please choose another character, You have already guessed this letter
end
else
if length player_guess_word != 1
begin
set message = string Please enter only one character
end
else
if is alpha player_g... | def check_choice(self, player_guess_word):
if player_guess_word in self.player_guess_list:
message = 'Please choose another character, You have already guessed this letter'
elif len(player_guess_word) != 1:
message = 'Please enter only one character'
elif player_guess_wor... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import re
import sys
import json
import subprocess
function get_nvme_list
begin
set stdraw = check output string sudo nvme list | grep '/dev/' | awk '{print $1}' shell=true
set stdout = decode stdraw
for i in split strip stdout
begin
set data_list = list comprehension dict string {#NVMENAME} i ... | #!/usr/bin/python
import re
import sys
import json
import subprocess
def get_nvme_list():
stdraw = subprocess.check_output("sudo nvme list | grep '/dev/' | awk '{print $1}'", shell=True)
stdout = stdraw.decode()
for i in stdout.strip().split():
data_list = [{"{#NVMENAME}": i} for i in stdout.str... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
set N = integer input
set T = sorted list generator expression integer input for i in range N
print T at 0 | # -*- coding: utf-8 -*-
N = int(input())
T = sorted(list(int(input()) for i in range(N)))
print(T[0])
| Python | zaydzuhri_stack_edu_python |
function status self
begin
return decode read url open __url
end function | def status(self):
return urllib.request.urlopen(self.__url).read().decode() | Python | nomic_cornstack_python_v1 |
import os
import boto3
import logging
class S3Storage
begin
set session = call Session aws_access_key_id=call getenv string AWS_SERVER_PUBLIC_KEY aws_secret_access_key=call getenv string AWS_SERVER_SECRET_KEY
set s3 = call resource string s3
set bucket_name = call getenv string S3_BUCKET_NAME
function __init__ self
beg... | import os
import boto3
import logging
class S3Storage():
session = boto3.Session(aws_access_key_id=os.getenv('AWS_SERVER_PUBLIC_KEY'),
aws_secret_access_key=os.getenv('AWS_SERVER_SECRET_KEY'))
s3 = session.resource('s3')
bucket_name = os.getenv('S3_BUCKET_NAME')
def __in... | Python | zaydzuhri_stack_edu_python |
comment Problem
string Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms. One fine day, a finite number of tourists come to stay at the hotel. The tourists consist of: → A Captain. → An unknown group of families consisting of K members per group where K ≠ 1. The Captain ... | #Problem
"""
Mr. Anant Asankhya is the manager at the INFINITE hotel. The hotel has an infinite amount of rooms.
One fine day, a finite number of tourists come to stay at the hotel.
The tourists consist of:
→ A Captain.
→ An unknown group of families consisting of K members per group where K ≠ 1.
The Captain was give... | Python | zaydzuhri_stack_edu_python |
function hodgkin_huxley_wilson t I_ext channels=list true true true output=string V initV=- 0.7 initx=list 0.088
begin
set dt = t at 1 - t at 0
set ddt = 1000.0 * dt
comment Reverse potentials for Na, K (mV)
set E = array list 55.0 - 92.0
comment Channel conductances (mmho/cm^2) [mho -> ohm^{-1}]
set gmax = array list ... | def hodgkin_huxley_wilson(t,I_ext,channels=[True,True,True],output='V',initV=-0.7,initx=[0.088]):
dt = t[1]-t[0]
ddt = 1e3*dt
# Reverse potentials for Na, K (mV)
E = np.array([ 55.0, -92.0])
# Channel conductances (mmho/cm^2) [mho -> ohm^{-1}]
gmax = np.array([ 1.0, 26.0])
# Initial st... | Python | nomic_cornstack_python_v1 |
function perturb_s_and_get_strong_filtered_rank embedding w s r o test_size triplets_to_filter constrain_dict type_dict
begin
set num_entities = shape at 0
set ranks = list
for idx in range test_size
begin
if idx % 100 == 0
begin
print format string test triplet {} / {} idx test_size
end
set target_s = s at idx
set ta... | def perturb_s_and_get_strong_filtered_rank(embedding, w, s, r, o, test_size, triplets_to_filter, constrain_dict, type_dict):
num_entities = embedding.shape[0]
ranks = []
for idx in range(test_size):
if idx % 100 == 0:
print("test triplet {} / {}".format(idx, test_size))
target_s ... | Python | nomic_cornstack_python_v1 |
function build self
begin
set size = tuple 400 200
set title = string Convert Miles to Kilometres
set root = call load_file string convert_miles_km.kv
return root
end function | def build(self):
Window.size = (400, 200)
self.title = "Convert Miles to Kilometres"
self.root = Builder.load_file("convert_miles_km.kv")
return self.root | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment encoding:utf-8
from xlrd import open_workbook , cellname
function main
begin
comment 打开文件
set xlsfilename = string c:/temp/workbook1.xls
set book = call open_workbook xlsfilename formatting_info=true
end function | #!/usr/bin/env python
#encoding:utf-8
from xlrd import open_workbook,cellname
def main():
#打开文件
xlsfilename='c:/temp/workbook1.xls'
book=open_workbook(xlsfilename,formatting_info=True) | Python | zaydzuhri_stack_edu_python |
function load_browser
begin
call setAttribute AA_EnableHighDpiScaling
if has attribute QStyleFactory string AA_UseHighDpiPixmaps
begin
call setAttribute AA_UseHighDpiPixmaps
end
set app = call QApplication argv
set ui = call load_ui
show
call exec_
end function | def load_browser():
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling)
if hasattr(QtWidgets.QStyleFactory, "AA_UseHighDpiPixmaps"):
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps)
app = QtWidgets.QApplication(sys.argv)
ui = load_ui()
ui.show()
app.... | Python | nomic_cornstack_python_v1 |
import math
import sys
from collections import OrderedDict
set choices = list string Y string N string ?
function readData
begin
with open string train.data string r as f
begin
set data = call splitlines
end
comment print len(data), len(data[0])
set sanData = list
for item in data
begin
set resRow = list
comment params... | import math
import sys
from collections import OrderedDict
choices = ['Y', 'N', '?']
def readData():
with open("train.data", "r") as f:
data = f.read().splitlines();
#print len(data), len(data[0])
sanData = list()
for item in data:
resRow = list()
#params = list()
par... | Python | zaydzuhri_stack_edu_python |
function get_section self doc_id section_id_or_name
begin
return get self string /docs/ { doc_id } /pages/ { section_id_or_name }
end function | def get_section(self, doc_id: str, section_id_or_name: str) -> Dict:
return self.get(f"/docs/{doc_id}/pages/{section_id_or_name}") | Python | nomic_cornstack_python_v1 |
function create_orthonormal_matrix_lambda_close_to_identity order tuning_parameter
begin
set U = call create_orthonormal_matrix_lambda_close_to_identity order tuning_parameter
return U
end function | def create_orthonormal_matrix_lambda_close_to_identity(order, tuning_parameter):
U = orthonormal.create.create_orthonormal_matrix_lambda_close_to_identity(order, tuning_parameter)
return U | Python | nomic_cornstack_python_v1 |
function feed_input_neurons self pattern
begin
set input_layer = layers at 0
comment exclude bias
for tuple input_neuron x in zip neurons at slice : - 1 : pattern
begin
call activation_function x
end
end function | def feed_input_neurons(self, pattern):
input_layer = self.layers[0]
for input_neuron, x in zip(input_layer.neurons[:-1], pattern): # exclude bias
input_neuron.activation_function(x) | Python | nomic_cornstack_python_v1 |
function random_undersampler sequence size state
begin
seed state
set sample = random choice sequence size replace=false
return sample
end function | def random_undersampler(sequence, size, state):
np.random.seed(state)
sample = np.random.choice(sequence, size, replace=False)
return sample | Python | nomic_cornstack_python_v1 |
function build_compression_mask_for_finite_values vector
begin
set full_finite_mask = call isfinite vector
return full_finite_mask
end function | def build_compression_mask_for_finite_values(vector):
full_finite_mask = np.isfinite(vector)
return full_finite_mask | Python | nomic_cornstack_python_v1 |
function resource_type self
begin
return get pulumi self string resource_type
end function | def resource_type(self) -> str:
return pulumi.get(self, "resource_type") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: UTF-8 -*-
from model.tool import BasicModule
import torch.nn as nn
import torch
import time
class one_conv extends Module
begin
function __init__ self inchanels growth_rate kernel_size=3
begin
call __init__
set conv = conv 2d inchanels growth_rate kernel_size=kernel_size pad... | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from model.tool import BasicModule
import torch.nn as nn
import torch
import time
class one_conv(nn.Module):
def __init__(self,inchanels,growth_rate,kernel_size = 3):
super(one_conv,self).__init__()
self.conv = nn.Conv2d(inchanels,growth_rate,kernel_size=k... | Python | zaydzuhri_stack_edu_python |
from math import fabs
class MonsterShell
begin
function __init__ self x y monsters_shell all_subjects change_x
begin
set monster_shell_x = x + 10
set monster_shell_y = y + 25
set monsters_shell = monsters_shell
set change_x = change_x
set all_subjects = all_subjects
end function
function can_move_down self
begin
string... | from math import fabs
class MonsterShell:
def __init__(self, x, y, monsters_shell, all_subjects, change_x):
self.monster_shell_x = x + 10
self.monster_shell_y = y + 25
self.monsters_shell = monsters_shell
self.change_x = change_x
self.all_subjects = all_subjects
def ca... | Python | zaydzuhri_stack_edu_python |
function sync_remote_output self
begin
call _copy_output_from_remote
end function | def sync_remote_output(self):
self._copy_output_from_remote() | Python | nomic_cornstack_python_v1 |
function validate self data partial=false
begin
set _ = partial
return data
end function | def validate(self, data, partial=False):
_ = partial
return data | Python | nomic_cornstack_python_v1 |
string ResNet model for classification. This model shall later be used as a Teacher
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class BasicBlock extends Module
begin
set expansion = 1
function __init__ self in_channels channels stride=1 downsample=none
begin
call __init__
set _... | """ ResNet model for classification. This model shall later be used as a Teacher """
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_channels, channels, stride=1,downsample=None):
super(BasicBlock... | Python | zaydzuhri_stack_edu_python |
comment 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить
comment возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания
comment необходимо обойтись без встроенной функции возведения числа в степень.
... | # 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить
# возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания
# необходимо обойтись без встроенной функции возведения числа в степень.
def func_1(... | Python | zaydzuhri_stack_edu_python |
function __init__ self learning_rate=0.0005 epochs=20 batch_size=10 shape=tuple 48 64 16 16 print_every=1 save_every=1 log_path=none filter_size=tuple 3 3 3 3 inputs_channel=tuple 2048 64 c_h_channel=tuple 1 1 forget_bias=tuple 1.0 1.0 save_model_path=none pretrained_model=none feature_dir=tuple none none scanpath=tupl... | def __init__(self, learning_rate=0.0005, epochs=20, batch_size=10, shape=(48, 64, 16, 16),
print_every=1, save_every=1, log_path=None, filter_size=(3, 3, 3, 3),
inputs_channel=(2048, 64), c_h_channel=(1, 1), forget_bias=(1.0, 1.0),
save_model_path=None, pretrained_mode... | Python | nomic_cornstack_python_v1 |
function build_traininig_model self
begin
info string Building the network to be used for training...
comment lookup word embeddings
set tuple pred_emb entity_emb = call _lookup_embeddings
comment split the input
set tuple sub pred obj corrupt = split tf call cast train_triplets int32 4 1
comment for each term of each ... | def build_traininig_model(self):
log.info('Building the network to be used for training...')
# lookup word embeddings
pred_emb, entity_emb = self._lookup_embeddings()
# split the input
sub, pred, obj, corrupt = tf.split(tf.cast(self.train_triplets, tf.int32), 4, 1)
# f... | Python | nomic_cornstack_python_v1 |
import zad1TCP
import zad1UDP
import time
import os
function test_udp
begin
call run_udp_client string a 50000 string 127.0.0.1:50000 0 string UDP 12 string e string PRZYPS
sleep 1
call run_udp_client string b 50001 string 127.0.0.1:50000 0 string UDP 8 string b string 22222
sleep 3
call run_udp_client string c 50002 s... | import zad1TCP
import zad1UDP
import time
import os
def test_udp():
zad1UDP.run_udp_client("a", 50000, "127.0.0.1:50000", 0, "UDP", 12, "e", "PRZYPS")
time.sleep(1)
zad1UDP.run_udp_client("b", 50001, "127.0.0.1:50000", 0, "UDP", 8, "b", "22222")
time.sleep(3)
zad1UDP.run_udp_client("c", 50002, "127... | Python | zaydzuhri_stack_edu_python |
import string
import random
import config
import constants
from config import seperator
from logger import debug_print
function generate_new_user_password
begin
set pseudo_user_password = random sample list ascii_uppercase 3
extend pseudo_user_password random sample list ascii_lowercase 3
extend pseudo_user_password ra... | import string
import random
import config
import constants
from config import seperator
from logger import debug_print
def generate_new_user_password():
pseudo_user_password = random.sample(list(string.ascii_uppercase), 3)
pseudo_user_password.extend(random.sample(list(string.ascii_lowercase), 3))
... | Python | zaydzuhri_stack_edu_python |
comment and,or,not
print 1 < 2 and 2 > 3
print string h == string h and 2 == 2
print 1 == 1 or 2 == 1
print 1 < 0 or 2 < 0
comment not
print not 1 == 1
print not 400 > 5000 | #and,or,not
print(1<2 and 2>3)
print('h'=='h' and 2==2 )
print(1==1 or 2==1)
print(1<0 or 2<0)
#not
print(not 1==1)
print(not 400>5000) | Python | zaydzuhri_stack_edu_python |
from flask import request , jsonify
from flask_restplus import Namespace , Resource , fields , reqparse
from utilities import convert_datetimes_in_query_results
from utilities.database_utilities import execute_query
set api = call Namespace string events description=string Information relating to events.
decorator call... | from flask import request, jsonify
from flask_restplus import Namespace, Resource, fields, reqparse
from utilities import convert_datetimes_in_query_results
from utilities.database_utilities import execute_query
api = Namespace("events", description="Information relating to events.")
@api.route('/')
class Events(Re... | Python | zaydzuhri_stack_edu_python |
import heapq
import re
function get_top_10_words string
begin
comment list of common stop words
set stopwords = set literal string the string and string a string is
comment dictionary to store word frequencies
set word_freq = dict
comment iterate through the string, splitting it into words
for word in find all string ... | import heapq
import re
def get_top_10_words(string):
stopwords = {"the", "and", "a", "is"} # list of common stop words
word_freq = {} # dictionary to store word frequencies
# iterate through the string, splitting it into words
for word in re.findall(r'\w+', string.lower()):
if word not in s... | Python | greatdarklord_python_dataset |
function optionhelp self indent=0 maxindent=25 width=79
begin
string Return user friendly help on program options.
function makelabels option
begin
set labels = string %*s--%s % tuple indent string name
if abbreviation
begin
set labels = labels + string , - + abbreviation
end
return labels + string :
end function
set ... | def optionhelp(self, indent=0, maxindent=25, width=79):
"""Return user friendly help on program options."""
def makelabels(option):
labels = '%*s--%s' % (indent, ' ', option.name)
if option.abbreviation:
labels += ', -' + option.abbreviation
return lab... | Python | jtatman_500k |
comment !/usr/bin/python3
class Node
begin
string Node class
function __init__ self data next_node=none
begin
string Initialization of Node object Args: data: value of node next_node: next node
set data = data
set next_node = next_node
end function
decorator property
function data self
begin
string Getter of data prope... | #!/usr/bin/python3
class Node:
""" Node class
"""
def __init__(self, data, next_node=None):
""" Initialization of Node object
Args:
data: value of node
next_node: next node
"""
self.data = data
self.next_node = next_node
@property
de... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment Python 2.7
string Beatcop tries to ensure that a specified process runs on exactly one node in a cluster. It does this by acquiring an expiring lock in Redis, which it then continually refreshes. If the node stops refreshing its lock for any reason (like sudden death) another will a... | #!/usr/bin/env python
## Python 2.7
"""
Beatcop tries to ensure that a specified process runs on exactly one node in a cluster.
It does this by acquiring an expiring lock in Redis, which it then continually refreshes.
If the node stops refreshing its lock for any reason (like sudden death) another will acquire the lock... | Python | zaydzuhri_stack_edu_python |
import torch
import torchvision
from torch.utils.data import Dataset
from PIL import Image
import matplotlib.pyplot as plt
import pandas as pd
from os import path
set LABEL_NAMES = dict string background 0 ; string kart 1 ; string pickup 2 ; string nitro 3 ; string bomb 4 ; string projectile 5
set LABEL_ = list string ... | import torch
import torchvision
from torch.utils.data import Dataset
from PIL import Image
import matplotlib.pyplot as plt
import pandas as pd
from os import path
LABEL_NAMES = {'background':0, 'kart':1, 'pickup':2, 'nitro':3, 'bomb':4, 'projectile':5}
LABEL_=['background','kart','pickup','nitro','bomb','projectile']... | Python | zaydzuhri_stack_edu_python |
function transacted_at self transacted_at
begin
set _transacted_at = transacted_at
end function | def transacted_at(self, transacted_at):
self._transacted_at = transacted_at | Python | nomic_cornstack_python_v1 |
for i in arr
begin
if type i == list
begin
for j in i
begin
append flat_arr j
end
end
else
begin
append flat_arr i
end
end
print flat_arr | for i in arr:
if type(i) == list:
for j in i:
flat_arr.append(j)
else:
flat_arr.append(i)
print(flat_arr)
| Python | zaydzuhri_stack_edu_python |
function CreateInstance2 self OwnerDoc=defaultNamedNotOptArg OwnerEntity=defaultNamedNotOptArg NameIn=defaultNamedNotOptArg Options=defaultNamedNotOptArg
begin
set ret = call InvokeTypes 8 LCID 1 tuple 9 0 tuple tuple 9 1 tuple 9 1 tuple 8 1 tuple 3 1 OwnerDoc OwnerEntity NameIn Options
if ret is not none
begin
set ret... | def CreateInstance2(self, OwnerDoc=defaultNamedNotOptArg, OwnerEntity=defaultNamedNotOptArg, NameIn=defaultNamedNotOptArg, Options=defaultNamedNotOptArg):
ret = self._oleobj_.InvokeTypes(8, LCID, 1, (9, 0), ((9, 1), (9, 1), (8, 1), (3, 1)),OwnerDoc
, OwnerEntity, NameIn, Options)
if ret is not None:
ret = Dis... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string markov chain to approximate japanese
import os
import re
import random
class p
begin
string the state in a markov chain
function __init__ self l=0 root=none
begin
string
set count = 0
if l == 1
begin
comment if l == 3:
set transition = dict string a root ; string i root ; string u root... | #!/usr/bin/python3
"markov chain to approximate japanese"
import os
import re
import random
class p:
" the state in a markov chain"
def __init__(self, l=0, root=None):
" "
self.count = 0
if l == 1:
#if l == 3:
self.transition = {'a':root, 'i':root, 'u':root, 'e':root... | Python | zaydzuhri_stack_edu_python |
function output_s3_uri self
begin
return get pulumi self string output_s3_uri
end function | def output_s3_uri(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "output_s3_uri") | Python | nomic_cornstack_python_v1 |
function concurrent2 P A Q B
begin
function aux P Q
begin
comment The alphabets never change.
function f x
begin
if x in A and x in B
begin
return call aux call P x call Q x
end
if x in A
begin
return call aux call P x Q
end
if x in B
begin
return call aux P call Q x
end
raise call Boom
end function
return f
end functi... | def concurrent2(P, A, Q, B):
def aux(P, Q):
# The alphabets never change.
def f(x):
if x in A and x in B:
return aux(P(x), Q(x))
if x in A:
return aux(P(x), Q)
if x in B:
return aux(P, Q(x))
raise Boom()
... | 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.