code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import CircleGenerator
from matplotlib import pyplot as plt
set circ_gen = call circle_gen radius_range=list 5 10 center_x_range=list - 5 5 center_y_range=list - 5 5 point_num_range=list 30 40 random_radius_range=list 0.2 0.4
set tuple x_rand y_rand _ = next circ_gen
figure figsize=tuple 5 5
plot x_rand y_rand string .... | import CircleGenerator
from matplotlib import pyplot as plt
circ_gen = CircleGenerator.circle_gen(
radius_range=[5, 10],
center_x_range=[-5, 5],
center_y_range=[-5, 5],
point_num_range=[30, 40],
random_radius_range=[0.2, 0.4]
)
x_rand, y_rand, _ = next(circ_gen)
plt.figure(figsize=(5, 5))
plt.pl... | Python | zaydzuhri_stack_edu_python |
function start self
begin
return call Group_interleaver_ATSC_sptr_start self
end function | def start(self):
return _mack_sdr_rossi_swig.Group_interleaver_ATSC_sptr_start(self) | Python | nomic_cornstack_python_v1 |
import re
import requests
set pattern = string <a.*href=\"(.*)\">
set tuple link1 link2 = tuple input input
set site = get requests link1
set link_found = false
set links = find all pattern text
for link in links
begin
try
begin
set page = get requests link
if link2 in text
begin
set link_found = true
break
end
end
exc... | import re
import requests
pattern = r"<a.*href=\"(.*)\">"
link1, link2 = input(), input()
site = requests.get(link1)
link_found = False
links = re.findall(pattern, site.text)
for link in links:
try:
page = requests.get(link)
if link2 in page.text:
link_found = True
break
... | Python | zaydzuhri_stack_edu_python |
async function _async_update_ipv6_filter_states self filter_states
begin
if token is none
begin
await call async_initialize_token
end
set val_enabled = join string * list comprehension string enabled for fs in entries
set val_del = join string * list comprehension string 0 for fs in entries
set val_idd = join string * ... | async def _async_update_ipv6_filter_states(self, filter_states: FilterStatesList):
if self.token is None:
await self.async_initialize_token()
val_enabled = '*'.join([str(fs.enabled) for fs in filter_states.entries])
val_del = '*'.join(['0' for fs in filter_states.entries])
v... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sun Jun 14 20:02:25 2015 @author: Stephen Bishop
import preprocess as make
function collage storytext n=none prints=none
begin
string This is the main function. Call this function to output everything I need to make a concordance collage
set tokens = call preprocess story... | # -*- coding: utf-8 -*-
"""
Created on Sun Jun 14 20:02:25 2015
@author: Stephen Bishop
"""
import preprocess as make
def collage(storytext, n=None, prints=None):
'''
This is the main function. Call this function to output everything I need
to make a concordance collage
'''
tokens = make... | Python | zaydzuhri_stack_edu_python |
function testEmailToQuery self
begin
from Listeners import IMAPListener
from TransactionObjects import Query
set testmail = call readConfigResourceFile string test_rec_mail
set expected_result = query list string Rom. 12:2 string Spencer Williams <tapesmith@gmail.com>
set result = call emailToQuery testmail
call assert... | def testEmailToQuery(self):
from Listeners import IMAPListener
from TransactionObjects import Query
testmail = readConfigResourceFile("test_rec_mail")
expected_result = Query(['Rom. 12:2'], 'Spencer Williams <tapesmith@gmail.com>')
result = IMAPListener.emailToQuery(testmail)
s... | Python | nomic_cornstack_python_v1 |
function create_project self organization=none owner=none title=string phase=string fund slug=string latitude=none longitude=none money_asked=500000
begin
if not latitude
begin
set latitude = call Decimal string -11.2352
end
if not longitude
begin
set longitude = call Decimal string -84.123
end
if not organization
be... | def create_project(self, organization=None, owner=None, title='', phase='fund',
slug='', latitude=None, longitude=None, money_asked=500000):
if not latitude:
latitude = Decimal('-11.2352')
if not longitude:
longitude = Decimal('-84.123')
if not o... | Python | nomic_cornstack_python_v1 |
function lookup_dirs root_path
begin
comment Create empty lists and populate them in next 'for' cycle.
set chapters = list
set sections = list
set articles = list
comment Find all sections and articles in walk generator tree
for tuple path dirs files in walk root_path
begin
if call we_are_in_root_folder root_path pa... | def lookup_dirs(root_path):
# Create empty lists and populate them in next 'for' cycle.
chapters = []
sections = []
articles = []
# Find all sections and articles in walk generator tree
for path, dirs, files in os.walk(root_path):
if we_are_in_root_folder(root_path, path):
c... | Python | nomic_cornstack_python_v1 |
function unzip_update filepath progress_callback acceptable_files mandatory_files chunk_size=1024
begin
assert chunk_size
set total_size = 0
set written_size = 0
set to_unzip : List at ZipInfo = list
set file_paths : Dict at tuple str Optional at str = dictionary comprehension fn : none for fn in acceptable_files
set ... | def unzip_update(
filepath: str,
progress_callback: Callable[[float], None],
acceptable_files: Sequence[str],
mandatory_files: Sequence[str],
chunk_size: int = 1024,
) -> Tuple[Mapping[str, Optional[str]], Mapping[str, int]]:
assert chunk_size
total_size = 0
written_size = 0
to_unzip... | Python | nomic_cornstack_python_v1 |
comment CREATE TRAINING SET
comment Import Libraries
import pandas as pd
import os
import mysql.connector
import string
import nltk
comment Import Modules
comment cleaning pipeline is located here
import module1_proj_A as m1
comment sql code select functions here
import module3_token_freq_by_label as m3
import module0_... | # CREATE TRAINING SET
# Import Libraries
import pandas as pd
import os
import mysql.connector
import string
import nltk
# Import Modules
import module1_proj_A as m1 # cleaning pipeline is located here
import module3_token_freq_by_label as m3 # sql code select functions here
import module0_utility_functions as m... | Python | zaydzuhri_stack_edu_python |
import sys
from pyspark import SparkContext , SparkConf
comment CONFIGURATION ###
set conf = call SparkConf
call setMaster string local[4]
call setAppName string reduce
set string spark.executor.memory string 4g
set sc = call SparkContext conf=conf
comment CODE STARTS ###
function dot_product x
begin
set a = x at 1 at ... | import sys
from pyspark import SparkContext, SparkConf
### CONFIGURATION ###
conf = SparkConf()
conf.setMaster("local[4]")
conf.setAppName("reduce")
conf.set("spark.executor.memory", "4g")
sc = SparkContext(conf=conf)
#### CODE STARTS ###
def dot_product(x):
a = x[1][0]
b = x[1][1]
total = 0
length = min(len... | Python | zaydzuhri_stack_edu_python |
function parallelize_initfunction targetlist callerfunc concurrentevents=5 *extrafuncargs
begin
set parallelizehandle = call uniqueid_getid
comment set up the dict locally one line at a time to avoid a ginormous line
set handleinfo = dict
set handleinfo at string abort = false
set handleinfo at string callfunc = calle... | def parallelize_initfunction(targetlist, callerfunc,concurrentevents=5, *extrafuncargs):
parallelizehandle = uniqueid_getid()
# set up the dict locally one line at a time to avoid a ginormous line
handleinfo = {}
handleinfo['abort'] = False
handleinfo['callfunc'] = callerfunc
handleinfo['callargs'] = extr... | Python | nomic_cornstack_python_v1 |
string to create db on terminal => sqlite3 test.db
import sqlite3
from flask import Flask , g
set app = call Flask __name__
function get_db
begin
set db = get attribute g string _database none
if db is none
begin
set db = call connect string test.db
set _database = call connect string test.db
end
return db
end function... | """
to create db on terminal => sqlite3 test.db
"""
import sqlite3
from flask import Flask, g
app = Flask(__name__)
def get_db():
db = getattr(g, '_database', None)
if db is None:
db = g._database = sqlite3.connect('test.db')
return db
@app.teardown_appcontext
def close_connection(excepti... | Python | zaydzuhri_stack_edu_python |
function tb2unknown method
begin
decorator wraps method
function wrapped *args **kw
begin
string Run real method
try
begin
set f_result = call method *args keyword kw
return f_result
end
comment pylint: disable=broad-except
except Exception as exc
begin
print string UNKNOWN: Got exception while running %s: %s: %s % tup... | def tb2unknown(method):
@functools.wraps(method)
def wrapped(*args, **kw):
""" Run real method """
try:
f_result = method(*args, **kw)
return f_result
except Exception as exc: # pylint: disable=broad-except
print('UNKNOWN: Got exception while running... | Python | nomic_cornstack_python_v1 |
from keras.utils import np_utils
from keras.models import Sequential
from keras import optimizers
from keras.utils import np_utils
from keras.layers import Dense , Activation , Dropout , Convolution1D , MaxPooling1D , Flatten
import numpy as np
set t = 2
function fun ys
begin
set yy = list
for i in ys
begin
set yy = y... | from keras.utils import np_utils
from keras.models import Sequential
from keras import optimizers
from keras.utils import np_utils
from keras.layers import Dense, Activation,Dropout,Convolution1D,MaxPooling1D,Flatten
import numpy as np
t = 2
def fun(ys):
yy = []
for i in ys:
yy = yy+i.tolist()
return yy
#(n,256... | Python | zaydzuhri_stack_edu_python |
function custom_score game player
begin
if call is_loser player
begin
return decimal string -inf
end
if call is_winner player
begin
return decimal string inf
end
set own_moves = call number_moves game player / 8
if own_moves == 0
begin
return decimal string -inf
end
set opp_moves = call number_moves game call get_oppon... | def custom_score(game, player):
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
own_moves = number_moves(game, player) / 8
if own_moves == 0:
return float("-inf")
opp_moves = number_moves(game, game.get_opponent(player)) / 8
... | Python | nomic_cornstack_python_v1 |
function __init__ self input_dim hidden_dim n_lyrs=1 do=0.05 device=string cpu
begin
call __init__
set ip_dim = input_dim
set hidden_dim = hidden_dim
set n_layers = n_lyrs
set dropout = do
set device = device
set rnn = lstm input_size=input_dim hidden_size=hidden_dim num_layers=n_lyrs dropout=do
set fc1 = linear in_fea... | def __init__(self, input_dim, hidden_dim, n_lyrs=1, do=.05, device="cpu"):
super(forecasterModel, self).__init__()
self.ip_dim = input_dim
self.hidden_dim = hidden_dim
self.n_layers = n_lyrs
self.dropout = do
self.device = device
self.rnn = nn.LSTM(input_size=in... | Python | nomic_cornstack_python_v1 |
import pylab as pl
from scikits.learn import datasets
from scikits.learn.decomposition import PCA
from scikits.learn.lda import LDA
from PIL import Image
import numpy
set imlist = list string A_1.png string A_2.png string A_3.png string A_4.png string B_1.png string B_2.png string B_3.png string B_4.png
comment open on... | import pylab as pl
from scikits.learn import datasets
from scikits.learn.decomposition import PCA
from scikits.learn.lda import LDA
from PIL import Image
import numpy
imlist = ['A_1.png', 'A_2.png', 'A_3.png', 'A_4.png', 'B_1.png', 'B_2.png', 'B_3.png', 'B_4.png']
im = numpy.array(Image.open(imlist[0])) #open one im... | Python | zaydzuhri_stack_edu_python |
function compute_q_value self states actions
begin
set state_batch = call cat states
set action_batch = call cat actions
return tuple call critic_1 tuple state_batch action_batch call critic_2 tuple state_batch action_batch
end function | def compute_q_value(self, states, actions):
state_batch = torch.cat(states)
action_batch = torch.cat(actions)
return self.critic_1((state_batch, action_batch)), self.critic_2((state_batch, action_batch)) | Python | nomic_cornstack_python_v1 |
function validate_ssl self
begin
return get pulumi self string validate_ssl
end function | def validate_ssl(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "validate_ssl") | Python | nomic_cornstack_python_v1 |
function get_timesheets_api self
begin
set timesheets_api = call TimesheetsApi authtoken portal_id
return timesheets_api
end function | def get_timesheets_api(self):
timesheets_api = TimesheetsApi(self.authtoken, self.portal_id)
return timesheets_api | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Fri Jun 12 01:37:52 2020 @author: vijetadeshpande
import torch.nn
import torch
function train model data optimizer criterion clip device
begin
comment initialize
train model
set epoch_loss = 0
for example in data
begin
comment extract source ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 01:37:52 2020
@author: vijetadeshpande
"""
import torch.nn
import torch
def train(model, data, optimizer, criterion, clip, device):
# initialize
model.train()
epoch_loss = 0
for example in data:
# extr... | Python | zaydzuhri_stack_edu_python |
function __contains__ self article_name
begin
set titles = call get_titles
if article_name in titles
begin
return true
end
return false
end function | def __contains__(self, article_name):
titles = self.get_titles()
if article_name in titles:
return True
return False | Python | nomic_cornstack_python_v1 |
comment Sort the following list by each element’s second letter a to z. Do so by using lambda. Assign the resulting value to the variable lambda_sort.
set ex_lst = list string hi string how are you string bye string apple string zebra string dance
set lambda_sort = sorted ex_lst key=lambda x -> x at 1 | #Sort the following list by each element’s second letter a to z. Do so by using lambda. Assign the resulting value to the variable lambda_sort.
ex_lst = ['hi', 'how are you', 'bye', 'apple', 'zebra', 'dance']
lambda_sort = sorted(ex_lst, key = lambda x : x[1])
| Python | zaydzuhri_stack_edu_python |
function column_type self column_name
begin
if column_name not in metadata
begin
call write_error string The column {} could not be found in table {} column_name name
end
return metadata at column_name at 1
end function | def column_type(self, column_name):
if column_name not in self.metadata:
write_error("The column {} could not be found in table {}", column_name, self.name)
return self.metadata[column_name][1] | Python | nomic_cornstack_python_v1 |
function __generateTempDirectory self
begin
set sas_test_harness_data_dir = join path directory name path absolute path path call getfile call currentframe string SAS-Test-Harness-Data
set current_time_stamp = string format time now string %Y-%m-%d_%H-%M-%S-%f
set temp_dump_dir_path = join path sas_test_harness_data_di... | def __generateTempDirectory(self):
sas_test_harness_data_dir = os.path.join(os.path.dirname(os.path.abspath(
inspect.getfile(inspect.currentframe()))), 'SAS-Test-Harness-Data')
current_time_stamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S-%f')
temp_dump_dir_path = os.path.join(sas_test_harness_data_... | Python | nomic_cornstack_python_v1 |
comment -*- coding: UTF-8 -*-
string @author: WanZhiWen @file: Main.py @time: 2018-09-05 15:51
set myMap = list comprehension 1010 * list 0 for i in range 1010
set Myroot = 1010 * list 0
set count = 1010 * list 0
function findroot x
begin
if Myroot at x == x
begin
return x
end
else
begin
set Myroot at x = call findroot... | # -*- coding: UTF-8 -*-
"""
@author: WanZhiWen
@file: Main.py
@time: 2018-09-05 15:51
"""
myMap = [1010 * [0] for i in range(1010)]
Myroot = 1010 * [0]
count = 1010 * [0]
def findroot(x):
if Myroot[x] == x:
return x
else:
Myroot[x] = findroot(Myroot[x])
def merge(x, y):
Myroot[findroot... | Python | zaydzuhri_stack_edu_python |
import os
import sys
from PIL import Image
set ext_list = list string .jpg string .png string bmp
function make_thumbnail route exts size=tuple 100 100 to_gray=false
begin
string 缩略化文件路径指定后缀名的图片文件,如路径下有thumbnails文件夹,则可能会 冲刷掉里面的文件。 :param route: 文件路径 :param exts: 扩展名 :param size: pixel x pixel :param to_gray: 灰化 :return... | import os
import sys
from PIL import Image
ext_list = ['.jpg', '.png', 'bmp']
def make_thumbnail(route, exts, size=(100, 100), to_gray=False):
"""
缩略化文件路径指定后缀名的图片文件,如路径下有thumbnails文件夹,则可能会
冲刷掉里面的文件。
:param route: 文件路径
:param exts: 扩展名
:param size: pixel x pixel
:param to_gray: 灰化
:re... | Python | zaydzuhri_stack_edu_python |
function plot_mean_samples_corrs_for_ralps path_to_init_data path_to_my_method batch_labels=tuple string 0108 string 0110 string 0124 string 0219 string 0221 string 0304 string 0306
begin
set initial_data = T
set normalized = T
set new_index = list comprehension join string _ split name string _ at slice : 3 : for nam... | def plot_mean_samples_corrs_for_ralps(path_to_init_data, path_to_my_method,
batch_labels=('0108', '0110', '0124', '0219', '0221', '0304', '0306')):
initial_data = pandas.read_csv(path_to_init_data, index_col=0).T
normalized = pandas.read_csv(path_to_my_method, index_col=0)... | Python | nomic_cornstack_python_v1 |
import PyPDF3 , sys , argparse , requests , os , re
comment cankao:https://github.com/pormr/DOIHelper/blob/master/DOIExtract.py
comment https://gist.github.com/ipudu/b72031f84a0e6cfdf6626a791f8fe380
set crossref = string http://api.crossref.org/
function rename pdf
begin
try
begin
string Rename an academic article pdf ... | import PyPDF3, sys, argparse, requests,os,re
#cankao:https://github.com/pormr/DOIHelper/blob/master/DOIExtract.py
#https://gist.github.com/ipudu/b72031f84a0e6cfdf6626a791f8fe380
crossref = 'http://api.crossref.org/'
def rename(pdf):
try:
"""Rename an academic article pdf file with human readable fo... | Python | zaydzuhri_stack_edu_python |
from scipy.stats import norm
import random
import os
import numpy as np
import sys
append path string ../timeseries
from timeseries import TimeSeries
append path string ../cs207rbtree
import redblackDB
append path string ../SimSearch
from _corr import kernel_dist
comment x=[];
comment v=[];
set num_vantage_points = 20
... | from scipy.stats import norm
import random
import os
import numpy as np
import sys
sys.path.append('../timeseries')
from timeseries import TimeSeries
sys.path.append('../cs207rbtree')
import redblackDB
sys.path.append('../SimSearch')
from _corr import kernel_dist
#x=[];
#v=[];
num_vantage_points = 20
num_of_timeseries... | Python | zaydzuhri_stack_edu_python |
from django.db import models
comment Create your models here.
class Director extends Model
begin
set first_name = call CharField max_length=50 blank=true null=true
set last_name = call CharField max_length=50 blank=true null=true
class Meta
begin
string to set table name in database
set db_table = string director
end c... | from django.db import models
# Create your models here.
class Director(models.Model):
first_name = models.CharField(max_length=50,blank=True,null=True)
last_name = models.CharField(max_length=50,blank=True,null=True)
class Meta:
'''
to set table name in database
'''
db_tab... | Python | zaydzuhri_stack_edu_python |
string 程序说明
comment -*- coding: utf-8 -*-
comment Author: cao wang
comment Datetime : 2020
comment software: PyCharm
comment 收获:
import time
import logging
function start_logger
begin
string 日志初始化设置、文件名(时间)、DEBUG为调试级别(级别导致输出内容的不同)、日志的记录格式、日期格式
comment filename='daily_report_error_%s.log' %
call basicConfig level=DEBUG ... | """程序说明"""
# -*- coding: utf-8 -*-
# Author: cao wang
# Datetime : 2020
# software: PyCharm
# 收获:
import time
import logging
def start_logger():
"""日志初始化设置、文件名(时间)、DEBUG为调试级别(级别导致输出内容的不同)、日志的记录格式、日期格式"""
logging.basicConfig( #filename='daily_report_error_%s.log' %
#datetime.strftime(datetime.now()... | Python | zaydzuhri_stack_edu_python |
function test_cannot_hate_and_like_movie self
begin
set users = call get_sample_users
set movies = call get_sample_movies users
set movie = movies at 0
set not_owner = users at - 1
set url = reverse string movie-opinion kwargs=dict string pk pk
set data_like = dict string opinion OPINION_LIKE
set data_hate = dict strin... | def test_cannot_hate_and_like_movie(self):
users = get_sample_users()
movies = get_sample_movies(users)
movie = movies[0]
not_owner = users[-1]
url = reverse('movie-opinion', kwargs={'pk': movies[0].pk})
data_like = {'opinion': OPINION_LIKE }
... | Python | nomic_cornstack_python_v1 |
function __init__ self G
begin
set G = G
set node_list = list nodes
end function | def __init__(self, G):
self.G = G
self.node_list = list(G.nodes) | Python | nomic_cornstack_python_v1 |
function anchor_from_anchor_vertex_list anchor_graph_list p
begin
set anchor_subset = list
set remaining_candidate_subset = list
for vertex in p at slice : :
begin
if call get_id in list comprehension call get_id for v in anchor_graph_list
begin
append anchor_subset vertex
remove p vertex
end
end
for vertex in p
b... | def anchor_from_anchor_vertex_list(anchor_graph_list, p):
anchor_subset = []
remaining_candidate_subset = []
for vertex in p[:]:
if vertex.get_id() in [v.get_id() for v in anchor_graph_list]:
anchor_subset.append(vertex)
p.remove(vertex)
for vertex in p:
true_list... | Python | nomic_cornstack_python_v1 |
function power base exponent
begin
if exponent == 0
begin
return 1
end
if exponent < 0
begin
return 1 / call power base - exponent
end
if exponent % 2 == 0
begin
return call power base * base exponent // 2
end
return base * call power base * base exponent - 1 // 2
end function | def power(base, exponent):
if exponent == 0:
return 1
if exponent < 0:
return 1 / power(base, -exponent)
if exponent % 2 == 0:
return power(base * base, exponent // 2)
return base * power(base * base, (exponent - 1) // 2)
| Python | jtatman_500k |
import random
set rows = random integer 1 10
set columns = random integer 1 20
comment Generate a list of unique elements within the range of 1 to 100
set elements = random sample range 1 101 rows * columns
comment Create the matrix with the specified number of rows and columns
set matrix = list comprehension elements ... | import random
rows = random.randint(1, 10)
columns = random.randint(1, 20)
# Generate a list of unique elements within the range of 1 to 100
elements = random.sample(range(1, 101), rows * columns)
# Create the matrix with the specified number of rows and columns
matrix = [elements[i:i+columns] for i in range(0, rows... | Python | jtatman_500k |
import datetime
from threading import RLock
class MemoryNamespaceManager extends object
begin
function __init__ self timeout *args
begin
set timeout = timeout
set data = dict
set lock = r lock
set overtime = dict
end function
function __getitem__ self key
begin
set vt = data at key
if get at key > now
begin
call __de... | import datetime
from threading import RLock
class MemoryNamespaceManager(object):
def __init__(self, timeout, *args):
self.timeout = timeout
self.data = {}
self.lock = RLock()
self.overtime = {}
def __getitem__(self, key):
vt = self.data[key]
if self.overtime.... | Python | zaydzuhri_stack_edu_python |
function hammingWeight x
begin
set x = absolute x
set x = x - x ? 1 ? m1
set x = x ? m2 + x ? 2 ? m2
set x = x + x ? 4 ? m4
set x = x + x ? 8
set x = x + x ? 16
set x = x + x ? 32
return x ? 127
end function | def hammingWeight(x):
x = abs(x)
x -= (x >> 1) & m1
x = (x & m2) + ((x >> 2) & m2)
x = (x + (x >> 4)) & m4
x += x >> 8
x += x >> 16
x += x >> 32
return x & 0x7f | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
set df = read csv string statistics_generation.csv
set df = mean group by df list string seconds
set loc at tuple slice : : string coverage = loc at tuple slice : : string coverage * 100.0
set font = dict string family... | #!/usr/bin/python
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.read_csv('statistics_generation.csv')
df = df.groupby(['seconds']).mean()
df.loc[:,'coverage'] *= 100.0
font = {'family' : 'serif',
'size' : 10 }
plt.rc('font', **font)
x = np.arange(1, 31, step=1)
fig, ax1 = p... | Python | zaydzuhri_stack_edu_python |
string Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example: Given nums = [0,0,1,1,1,2,2,3,3,4], Your function sho... | """
Given a sorted array nums, remove the duplicates in-place such that
each element appear only once and return the new length.
Do not allocate extra space for another array,
you must do this by modifying the input array in-place with O(1) extra memory.
Example:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function shoul... | Python | zaydzuhri_stack_edu_python |
function get_data data_path vocab_path embedding_path downsampling sequence_length batch_size
begin
with call variable_scope string data
begin
set vocab = call load_vocab vocab_path
print format string {} items in vocab length vocab
set data_tensor = call load_dataset data_path vocab sequence_length batch_size
end
with... | def get_data(data_path, vocab_path, embedding_path, downsampling,
sequence_length, batch_size):
with tf.variable_scope('data'):
vocab = read.load_vocab(vocab_path)
print('{} items in vocab'.format(len(vocab)))
data_tensor = read.load_dataset(data_path, vocab, sequence_length,
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python -t
class Solution
begin
string @param grid: @return: The lowest number of moves to acquire all keys
function shortestPathAllKeys self grid
begin
comment write your code here
set tuple n m = tuple length grid length grid at 0
set numOfKeys = 0
set direc = list list 0 1 list 0 - 1 list 1 0 list -... | #!/usr/bin/python -t
class Solution:
"""
@param grid:
@return: The lowest number of moves to acquire all keys
"""
def shortestPathAllKeys(self, grid):
# write your code here
n, m = len(grid), len(grid[0])
numOfKeys = 0
direc = [[0,1],[0,-1],[1,0],[-1,0]]
mov... | Python | zaydzuhri_stack_edu_python |
for _ in range integer input
begin
set tuple n t = map int split input
set p = t
set s = list input
for i in range 0 n
begin
if is alpha s at i
begin
set t = t % 26
if is upper s at i
begin
set s at i = character ordinal s at i + t - 65 % 26 + 65
end
else
if is lower s at i
begin
set s at i = character ordinal s at i +... | for _ in range(int(input())):
n,t=map(int,input().split())
p=t
s=list(input())
for i in range(0,n):
if s[i].isalpha():
t=t%26
if s[i].isupper():
s[i]=chr(((ord(s[i])+t-65)%26)+65)
elif s[i].islower():
s[i]=chr(((ord(s[i])+t-97)%... | Python | zaydzuhri_stack_edu_python |
function combine_list list1 list2
begin
if length list1 > length list2
begin
set longest_list = list1
set shortest_list = list2
end
else
begin
set longest_list = list2
set shortest_list = list1
end
set combined_list = list
set i = 0
for el in longest_list
begin
append combined_list el
if i < length shortest_list
begin... | def combine_list(list1, list2):
if len(list1) > len(list2):
longest_list = list1
shortest_list = list2
else:
longest_list = list2
shortest_list = list1
combined_list = []
i = 0
for el in longest_list:
combined_list.append(el)
if i < len(short... | Python | iamtarun_python_18k_alpaca |
import csv
with open string table_in.csv as csv_file
begin
set file_content = dict reader csv_file
with open string table_out.csv mode=string w newline=string as csv_file2
begin
set field_names = list string Email string Name
set writer = dict writer csv_file2 fieldnames=field_names
call writeheader
for row in file_con... | import csv
with open('table_in.csv') as csv_file:
file_content = csv.DictReader(csv_file)
with open("table_out.csv", mode="w", newline='') as csv_file2:
field_names = ['Email', 'Name']
writer = csv.DictWriter(csv_file2, fieldnames=field_names)
writer.writeheader()
for row in fil... | Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render , redirect , get_object_or_404
from django.views.decorators.http import require_POST
from mall.models import Product
from cart import Cart
from forms import CartAddProductForm , CartProductQuantityForm
comment 认证(authentication)框架的login_required装饰器
from django.contrib.auth.decorators... | from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from mall.models import Product
from .cart import Cart
from .forms import CartAddProductForm, CartProductQuantityForm
from django.contrib.auth.decorators import login_required # 认证(authentication)框架的l... | Python | zaydzuhri_stack_edu_python |
import sqlite3
set con = call connect string :memory:
call set_authorizer none | import sqlite3
con = sqlite3.connect(':memory:')
con.set_authorizer(None)
| Python | flytech_python_25k |
from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime
import time
function hello_function
begin
print string Hello, this is the first task of the DAG
sleep 5
end function
function last_function
begin
print string DAG run is done.
end function
function sleeping_functio... | from airflow import DAG
from airflow.operators.python import PythonOperator
from datetime import datetime
import time
def hello_function():
print('Hello, this is the first task of the DAG')
time.sleep(5)
def last_function():
print('DAG run is done.')
def sleeping_function():
print("Sleeping for 5 se... | Python | zaydzuhri_stack_edu_python |
import pickle
set a = open string C:\Users\Administrator\Desktop\record.txt string r
set c = list a
set x = open string C:\Users\Administrator\Desktop\record.pkl string wb
dump c x
close x
close a
comment 对生成的record.pkl文件进行compile。
set t = open string C:\Users\Administrator\Desktop\record.pkl string rb
set s = print lo... | import pickle
a=open(r"C:\Users\Administrator\Desktop\record.txt","r")
c=list(a)
x=open(r"C:\Users\Administrator\Desktop\record.pkl","wb")
pickle.dump(c,x)
x.close()
a.close()
#对生成的record.pkl文件进行compile。
t=open("C:\\Users\\Administrator\\Desktop\\record.pkl","rb")
s=print(pickle.load(t))
| Python | zaydzuhri_stack_edu_python |
function __parse_proc_stat self
begin
set iow = string N
set cpu_time = 0
set cpu_time_capture = 0
set rss = 0
try
begin
with open string /proc/%s/stat % pid as fd
begin
set lines = read fd
set infos = split lines at slice : - 1 :
comment IO wait
if infos at 2 == string D
begin
set iow = string Y
end
comment RSS
set r... | def __parse_proc_stat(self,):
iow = 'N'
cpu_time = 0
cpu_time_capture = 0
rss = 0
try:
with open('/proc/%s/stat' % (self.pid)) as fd:
lines = fd.read()
infos = lines[:-1].split()
# IO wait
if infos[2] == ... | Python | nomic_cornstack_python_v1 |
import numpy as np
class Data extends object
begin
string A class solely for extracting data from text files.
function __init__ self filename mode
begin
set filename = filename
set mode = mode
end function
function readData self size=none
begin
string Reads the input text file and extracts the data in the form of array... | import numpy as np
class Data(object):
"""A class solely for extracting data from text files."""
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def readData(self, size=None):
"""Reads the input text file and extracts the data in the ... | Python | zaydzuhri_stack_edu_python |
function get_compared_movies_by_box_office self first_movie_title second_movie_title
begin
return call get_compared_movie_by_value call get_movie_by_title first_movie_title call get_movie_by_title second_movie_title
end function | def get_compared_movies_by_box_office(self, first_movie_title, second_movie_title):
return self.get_compared_movie_by_value(self.get_movie_by_title(first_movie_title),
self.get_movie_by_title(second_movie_title)) | Python | nomic_cornstack_python_v1 |
function enablePackageInternal self *args
begin
return call CompartmentReference_enablePackageInternal self *args
end function | def enablePackageInternal(self, *args):
return _libsbml.CompartmentReference_enablePackageInternal(self, *args) | Python | nomic_cornstack_python_v1 |
function load_data_set_from_pickle file_name=none
begin
if not file_name
begin
try
begin
set file_name = max glob glob join path __pickled_data_directory__ string *.chars74k-lite.gz key=getctime
end
except ValueError as e
begin
error string Unable to load data set from file since no pickled files could be found,
return... | def load_data_set_from_pickle(file_name=None):
if not file_name:
try:
file_name = max(glob.glob(os.path.join(__pickled_data_directory__, '*.chars74k-lite.gz')), key=os.path.getctime)
except ValueError as e:
log.error('Unable to load data set from file sinc... | Python | nomic_cornstack_python_v1 |
function test_patch_request_by_non_owner self
begin
set client = call APIClient
call credentials HTTP_AUTHORIZATION=test_user2_token
set response = post string /api/places/ restaurant_data format=string json
set url = string /api/places/ { data at string id } /
call credentials HTTP_AUTHORIZATION=test_user1_token
set r... | def test_patch_request_by_non_owner(self):
client = APIClient()
client.credentials(HTTP_AUTHORIZATION=self.test_user2_token)
response = client.post('/api/places/', self.restaurant_data, format='json')
url = f"/api/places/{response.data['id']}/"
client.credentials(HTTP_AUTHORIZAT... | Python | nomic_cornstack_python_v1 |
function getTimestamp self
begin
return timestamp
end function | def getTimestamp(self):
return self.timestamp | Python | nomic_cornstack_python_v1 |
function _fftwhilbert x N=none axis=- 1
begin
set x = call asarray x
if call iscomplexobj x
begin
raise call ValueError string x must be real.
end
if N is none
begin
set N = shape at axis
end
if N <= 0
begin
raise call ValueError string N must be positive.
end
set obj1 = fft x N axis=axis threads=nthreads planner_effor... | def _fftwhilbert(x, N=None, axis=-1):
x = np.asarray(x)
if np.iscomplexobj(x):
raise ValueError("x must be real.")
if N is None:
N = x.shape[axis]
if N <= 0:
raise ValueError("N must be positive.")
obj1 = pyfftw.builders.fft(x, N, axis=axis, threads=nthreads, planner_effort... | Python | nomic_cornstack_python_v1 |
function test_scalar_speed
begin
set s = call get_wind_speed - 3.0 - 4.0
call assert_almost_equal s 5.0 3
end function | def test_scalar_speed():
s = get_wind_speed(-3., -4.)
assert_almost_equal(s, 5., 3) | Python | nomic_cornstack_python_v1 |
function get_sp500
begin
set url = string http://en.wikipedia.org/wiki/List_of_S%26P_500_companies
set resp = get requests url
set soup = call BeautifulSoup text string lxml
set table = find soup string table dict string class string wikitable sortable
set tickers = list
for row in find all string tr at slice 1 : :
... | def get_sp500():
url = "http://en.wikipedia.org/wiki/List_of_S%26P_500_companies"
resp = requests.get(url)
soup = bs.BeautifulSoup(resp.text, 'lxml')
table = soup.find('table', {'class': 'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
ticker = row.findAll('td')[0... | Python | nomic_cornstack_python_v1 |
function score self X y sample_weight=none multioutput=none
begin
set y_pred = predict self X=X
set score = call r2_score y y_pred sample_weight=sample_weight multioutput=multioutput
return score
end function | def score(self, X, y, sample_weight=None, multioutput=None):
y_pred = self.predict(X=X)
score = sklearn.metrics.r2_score(y, y_pred, sample_weight=sample_weight, multioutput=multioutput)
return score | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
from matplotlib import pyplot as plt
set MIN_MATCH_COUNT = 10
set img1 = call imread string 1.jpg 0
set img2 = call imread string 2.jpg 0
comment 使用SIFT检测角点
set sift = call SIFT_create
comment 获取关键点和描述符
set tuple kp1 des1 = call detectAndCompute img1 none
set tuple kp2 des2 = call detectAn... | import numpy as np
import cv2
from matplotlib import pyplot as plt
MIN_MATCH_COUNT = 10
img1 = cv2.imread('1.jpg',0)
img2 = cv2.imread('2.jpg',0)
# 使用SIFT检测角点
sift = cv2.xfeatures2d.SIFT_create()
# 获取关键点和描述符
kp1, des1 = sift.detectAndCompute(img1,None)
kp2, des2 = sift.detectAndCompute(img2,None)
# 定义FLANN匹配器
index... | Python | zaydzuhri_stack_edu_python |
for i in range N
begin
set tuple S P = map str split input
set P = integer P
set L at i at 0 = S
set L at i at 1 = P
set L at i at 2 = i + 1
end
set tmp = sorted L key=lambda x -> x at 1 reverse=true
set ans = sorted tmp key=lambda x -> x at 0
for a in ans
begin
print a at 2
end | for i in range(N):
S, P = map(str, input().split())
P = int(P)
L[i][0] = S
L[i][1] = P
L[i][2] = i+1
tmp = sorted(L, key=lambda x: x[1], reverse=True)
ans = sorted(tmp, key=lambda x: x[0])
for a in ans:
print(a[2])
| Python | zaydzuhri_stack_edu_python |
function test_temp_less_than_zero self
begin
try
begin
set temp = - 1.1
end
except ValueError
begin
comment Attempting to set the `temp` attribute with a negative value raised a ValueError which is exactly what we wanted to do.
pass
end
try else
begin
call fail string `temp` attribute can be assigned a negative value.
... | def test_temp_less_than_zero(self):
try:
self.el.temp = -1.1
except ValueError:
# Attempting to set the `temp` attribute with a negative value raised a ValueError which is exactly what we wanted to do.
pass
else:
self.fail("`temp` attribute can be ... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
set tags = list string #gohawks string #gopatriots string #nfl string #patriots string #sb49 string #superbowl
function get_vals tag
begin
set f_name = string twitter_data/original/ + tag + string .pickle
end function | import matplotlib.pyplot as plt
tags = ['#gohawks','#gopatriots','#nfl','#patriots','#sb49','#superbowl']
def get_vals(tag):
f_name = 'twitter_data/original/'+tag+'.pickle' | Python | zaydzuhri_stack_edu_python |
function check_atleast_4matchedmuons evt
begin
comment At this point, sometimes particles will sneak into lep_genindex
comment but not really be muons, even though they were reconstructed as muons.
comment MC 2017 ggF sample, event 21266 showed a ubar faking a muon.
comment Sometimes we think we might have 4 or 5 muons... | def check_atleast_4matchedmuons(evt):
# At this point, sometimes particles will sneak into lep_genindex
# but not really be muons, even though they were reconstructed as muons.
# MC 2017 ggF sample, event 21266 showed a ubar faking a muon.
# Sometimes we think we might have 4 or 5 muons, but 2 objects... | Python | nomic_cornstack_python_v1 |
function get_queryset self
begin
return call order_by string -pub_date at slice : 5 :
end function | def get_queryset(self):
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] | Python | nomic_cornstack_python_v1 |
function eat food is_healthy
begin
set ending = string because its healthy
if not is_healthy
begin
set ending = string because YOLO!
end
return string I am eating { food } { ending }
end function
function nap num_hours
begin
pass
end function | def eat(food, is_healthy):
ending = "because its healthy"
if not is_healthy:
ending = "because YOLO!"
return f"I am eating {food} {ending}"
def nap(num_hours):
pass | Python | zaydzuhri_stack_edu_python |
comment # 计算创建的对象总数
comment class Tool(object):
comment counter = 0
comment def __init__(self,name):
comment self.name = name
comment Tool.counter += 1
comment tool1 = Tool("gg")
comment tool2 = Tool("dd")
comment tool3 = Tool("ddr")
comment print("创建的对象有%s个" %Tool.counter)
comment class Tool(object):
comment counter =... | # # 计算创建的对象总数
# class Tool(object):
# counter = 0
# def __init__(self,name):
#
# self.name = name
# Tool.counter += 1
# tool1 = Tool("gg")
# tool2 = Tool("dd")
# tool3 = Tool("ddr")
# print("创建的对象有%s个" %Tool.counter)
#
# class Tool(object):
# counter = 0
# def __init__(sel... | Python | zaydzuhri_stack_edu_python |
string KNN from Scratch
import numpy as np
import pandas as pd
from plotnine import *
from sklearn.model_selection import train_test_split
import sklearn.metrics as m
comment %% -----------------------------------------
set dat = read csv string turnout.csv
set y = values
set X = values
comment Split the data.
set tupl... | '''
KNN from Scratch
'''
import numpy as np
import pandas as pd
from plotnine import *
from sklearn.model_selection import train_test_split
import sklearn.metrics as m
# %% -----------------------------------------
dat = pd.read_csv("turnout.csv")
y = dat['vote'].values
X = dat.drop(columns=['vote','id']).values
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
set data = read csv string Date_dictionary.csv
set data at string date = call to_datetime data at string date infer_datetime_format=true
set data = reset index sort values data string date drop=true
set tuple colsI colsO = tuple list list
for i in... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.read_csv('Date_dictionary.csv')
data['date'] = pd.to_datetime(data['date'],infer_datetime_format=True)
data = data.sort_values('date').reset_index(drop= True)
colsI,colsO =[],[]
for i in range(0,70,1):
colsI += ['area_I_%s' %i,]
co... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
function testDict01
begin
set infos = dict string name string laowang ; string age 18
for key in keys infos
begin
print key
end
for value in values infos
begin
print value
end
set default infos string gender string 1
set gender = get infos string gender
print gender
print infos
if string na... | # -*- coding:utf-8 -*-
def testDict01():
infos = {'name': 'laowang', 'age': 18}
for key in infos.keys():
print(key)
for value in infos.values():
print(value)
infos.setdefault('gender', '1')
gender = infos.get('gender')
print(gender)
print(infos)
if 'name' in infos:
... | Python | zaydzuhri_stack_edu_python |
for fnamn in förnamn
begin
for enamn in efternamn
begin
print fnamn + enamn
end
end | for fnamn in förnamn:
for enamn in efternamn:
print(fnamn + enamn)
| Python | zaydzuhri_stack_edu_python |
function save self
begin
if site_structure is none
begin
raise call RuntimeError format string [{}] Site structure doesn't exist! __spider_name
end
info string [%s] Saving state. __spider_name
if not is directory path __progress_file_dir
begin
make directory os __progress_file_dir
end
with open __json_file_path string ... | def save(self):
if self.site_structure is None:
raise RuntimeError("[{}] Site structure doesn't exist!".format(self.__spider_name))
self.logger.info("[%s] Saving state.", self.__spider_name)
if not os.path.isdir(self.__progress_file_dir):
os.mkdir(self.__progress_file_dir... | Python | nomic_cornstack_python_v1 |
function get_score data labels fold_pairs name model param numTopVars rank_per_fold=none parallel=true rand_iter=- 1 covariate_detrend_params=none provide_continuous_output=true
begin
assert is instance name str
info string Classifying %s % name
set ksplit = length fold_pairs
comment if name not in NAMES:
comment raise... | def get_score(data, labels, fold_pairs, name, model, param, numTopVars,
rank_per_fold=None, parallel=True, rand_iter=-1,
covariate_detrend_params=None,
provide_continuous_output=True):
assert isinstance(name, str)
logging.info("Classifying %s" % name)
ksplit =... | Python | nomic_cornstack_python_v1 |
function test_to_dict_date self
begin
set d = call to_dict
set test_date = list d at string updated_at d at string created_at
assert is not none test_date at 0
assert is not none test_date at 1
assert is instance test_date at 0 str
assert is instance test_date at 1 str
assert is instance string parse time test_date at ... | def test_to_dict_date(self):
d = self.user.to_dict()
test_date = [d['updated_at'], d['created_at']]
self.assertIsNotNone(test_date[0])
self.assertIsNotNone(test_date[1])
self.assertIsInstance(test_date[0], str)
self.assertIsInstance(test_date[1], str)
self.assertI... | Python | nomic_cornstack_python_v1 |
function package_versions context request
begin
set normalized_name = call normalize_name name
if not call has_permission normalized_name string read
begin
return call forbid
end
set fallback = fallback
set can_update_cache = call can_update_cache
set packages = all normalized_name
set pkgs = dict
if fallback == strin... | def package_versions(context, request):
normalized_name = normalize_name(context.name)
if not request.access.has_permission(normalized_name, 'read'):
return request.forbid()
fallback = request.registry.fallback
can_update_cache = request.access.can_update_cache()
packages = request.db.all(n... | Python | nomic_cornstack_python_v1 |
function main
begin
comment SessionRequest
print string # SessionRequest
set client_private_key = call from_private_bytes call fromhex string b8 fa bd 62 66 5d 8b 9e 8a 9d 8b 1f 4b ca 42 c8 c2 78 9a 61 10 f5 0e 9d d7 85 b3 ed e8 83 f3 78
set client_public_key_raw = call public_bytes Raw Raw
comment append to SessionReq... | def main():
################
# SessionRequest
################
print("# SessionRequest")
client_private_key = X25519PrivateKey.from_private_bytes(
bytes.fromhex(
"b8 fa bd 62 66 5d 8b 9e 8a 9d 8b 1f 4b ca 42 c8 c2 78 9a 61 10 f5 0e 9d d7 85 b3 ed e8 83 f3 78"
)
)
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import curses
from random import randrange
function neigh_num state i j w h
begin
set cnt = 0
set pos = list tuple - 1 - 1 tuple 0 - 1 tuple 1 - 1 tuple - 1 0 tuple 1 0 tuple - 1 1 tuple 0 1 tuple 1 1
for tuple x y in pos
begin
if i + x >= 0 and i + x < w and j + y >= 0 and j + y < h
begin
if ... | #!/usr/bin/python3
import curses
from random import randrange
def neigh_num (state, i, j, w, h):
cnt = 0
pos = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
for (x, y) in pos:
if i + x >= 0 and i + x < w and j + y >= 0 and j + y < h:
if state[i + x][j + y]:
... | Python | zaydzuhri_stack_edu_python |
function storage_var_name_to_base_addr var_name
begin
return call get_storage_var_address var_name=var_name
end function | def storage_var_name_to_base_addr(var_name: str) -> int:
return get_storage_var_address(var_name=var_name) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment Copyright 2009-2017 BHG http://bw.org/
set tuple x y = tuple 4 4
if x < y
begin
print string x { x } is less than y { y }
end
comment alternatively
if x < y
begin
print format string X {} is less than Y {} x y
end
else
if y < x
begin
print string LOL
end
else
begin
print string The... | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
x, y = 4, 4
if x < y:
print(f'x {x} is less than y {y}')
#alternatively
if x < y: print ('X {} is less than Y {}'.format(x, y))
elif y <x : print ('LOL')
else : print ('There was nothing to do.') | Python | zaydzuhri_stack_edu_python |
while none
begin
set number = number + 1
if number % 3 == 2 and number % 5 == 3 and number % 7 == 2
begin
print string 答曰:这个数是 number
set none = false
end
end | while none:
number += 1
if number % 3 == 2 and number % 5 == 3 and number % 7 == 2:
print("答曰:这个数是", number)
none = False
| Python | zaydzuhri_stack_edu_python |
function file_page_text_info file_order_id
begin
set conn = call get_db
set tuple x_test y_test data = tuple none none none
set query = format string EXEC [dbo].[GET_FilePageTextByOrderId] @FileOrderID = {0} file_order_id
set dataset = call read_sql query conn
if not empty
begin
set tuple x_test y_test = tuple values v... | def file_page_text_info(file_order_id):
conn = get_db()
x_test, y_test, data = None, None, None
query = 'EXEC [dbo].[GET_FilePageTextByOrderId] @FileOrderID = {0}'.format(file_order_id)
dataset = pd.read_sql(query, conn)
if not dataset.empty:
x_test, y_test = dataset.PageText.values, datase... | Python | nomic_cornstack_python_v1 |
function _salary_zakat self cr uid ids name args context=none
begin
set zakat_obj = get pool string hr.zakat
set res = dict
for rec in call browse cr uid ids context=context
begin
set zakat_amount = 0.0
set zakat_id = search cr uid list tuple string start_date string <= salary_date tuple string end_date string >= sala... | def _salary_zakat(self, cr, uid, ids, name, args, context=None):
zakat_obj = self.pool.get('hr.zakat')
res = {}
for rec in self.browse(cr, uid, ids, context=context):
zakat_amount = 0.0
zakat_id = zakat_obj.search(cr, uid, [('start_date', '<=', rec.salary_date), ('end_dat... | Python | nomic_cornstack_python_v1 |
class BankAccount
begin
function __init__ self owner balance
begin
set owner = owner
set balance = balance
end function
function deposit self amount
begin
set balance = balance + amount
return balance
end function
function withdraw self amount
begin
set balance = balance - amount
return balance
end function
end class | class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit (self, amount):
self.balance += amount
return self.balance
def withdraw (self, amount):
self.balance -= amount
return self.balance | Python | iamtarun_python_18k_alpaca |
function output_sas_curve curve filename
begin
if filename is not none
begin
set output = open filename string w
end
else
begin
set output = stdout
end
for qi_pair in curve
begin
write output format string {0:7.4f} {1:7.4f} qi_pair at 0 qi_pair at 1
end
close output
end function | def output_sas_curve(curve, filename):
if filename is not None:
output = open(filename, 'w')
else:
output = sys.stdout
for qi_pair in curve:
output.write("{0:7.4f} {1:7.4f}\n".format(qi_pair[0], qi_pair[1]))
output.close() | Python | nomic_cornstack_python_v1 |
function _load_calib filepath
begin
with open filepath string r as f
begin
set params = call fromstring read line f dtype=float64 sep=string
set P = reshape np params tuple 3 4
set K = P at tuple slice 0 : 3 : slice 0 : 3 :
end
return tuple K P
end function | def _load_calib(filepath):
with open(filepath, 'r') as f:
params = np.fromstring(f.readline(), dtype=np.float64, sep=' ')
P = np.reshape(params, (3, 4))
K = P[0:3, 0:3]
return K, P | Python | nomic_cornstack_python_v1 |
comment Criar Lista:
set n = integer input
set lista = list
for i in range 0 n
begin
set n2 = integer input
append lista n2
end
comment Inverter Lista:
print lista at slice : : - 1
comment Passar uma casa para a esquerda:
set lista_inver = list
set lista_ordem = sorted lista
set maxi = max lista
for i in range 0 n
... | #Criar Lista:
n = int(input())
lista = []
for i in range (0,n):
n2 = int(input())
lista.append(n2)
#Inverter Lista:
print(lista[::-1])
#Passar uma casa para a esquerda:
lista_inver = []
lista_ordem = sorted(lista)
maxi = max(lista)
for i in range (0,n):
resto = (lista_ordem[i] % maxi)
if resto != 0:
... | Python | zaydzuhri_stack_edu_python |
comment class Node:
comment def __init__(self,data=None,next = None):
comment self.data = data
comment self.next = next
comment def reverseList(head):
comment """
comment :type head: ListNode
comment :rtype: ListNode
comment """
comment if not head or not head.next:
comment return head
comment Node = None
comment while... | # class Node:
# def __init__(self,data=None,next = None):
# self.data = data
# self.next = next
# def reverseList(head):
# """
# :type head: ListNode
# :rtype: ListNode
# """
# if not head or not head.next:
# return head
# Node = None
# while head:
# p = head
# head = head.next
# p.next = Node
# N... | Python | zaydzuhri_stack_edu_python |
string Escreva um programa que faça o computador "pensar" em um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número escolhido pelo computador. O programa deverá escrever na tela se o usuário venceu ou perdeu. Dei uma procurada tosca e vi que o randrange tem um range que podemos trabalhar... | '''Escreva um programa que faça o computador "pensar" em
um número inteiro entre 0 e 5 e peça para o usuário tentar descobrir
qual foi o número escolhido pelo computador.
O programa deverá escrever na tela se o usuário venceu ou perdeu.
Dei uma procurada tosca e vi que o randrange tem um range que podemos trabalhar
p... | Python | zaydzuhri_stack_edu_python |
string compute the shortest distance from a source to a destination in a directed graph where some crow distance (Euclid) can be defined, and where distances from landmarks are known, as well as the shortest corresponding path /!\ all distances must be >= 0 return: distance = length of shortest path path = shortest pat... | """
compute the shortest distance from a source to a destination
in a directed graph where some crow distance (Euclid) can be
defined, and where distances from landmarks are known,
as well as the shortest corresponding path
/!\ all distances must be >= 0
return:
distance = length of shortest path
path = short... | Python | zaydzuhri_stack_edu_python |
comment This is my shopoing list
set shoplist = list string apple string mango string carrot string banana
print length shoplist
for item in shoplist
begin
print item end=string _
end | #This is my shopoing list
shoplist = ['apple','mango','carrot','banana']
print(len(shoplist))
for item in shoplist:
print(item,end=' _')
| Python | zaydzuhri_stack_edu_python |
function separate_pos_neg attribution
begin
set attribution_pos_val = attribution * attribution >= 0
set attribution_neg_val = attribution * ? attribution >= 0
return tuple attribution_pos_val attribution_neg_val
end function | def separate_pos_neg(attribution):
attribution_pos_val = attribution*(attribution >= 0)
attribution_neg_val = attribution*~(attribution >= 0)
return attribution_pos_val, attribution_neg_val | Python | nomic_cornstack_python_v1 |
function sortit numbers
begin
for i in range length numbers
begin
if i at 1 > i at 2
begin
set tuple i at 1 i at 2 = tuple i at 2 i at 1
end
end
return numbers
end function
comment ACTIAL CODE
set x = list input string type some integers randomly, separating them with spaces
comment creates a list with the numbers the ... | def sortit(numbers):
for i in range(len(numbers)):
if i[1]>i[2]:
i[1],i[2]=i[2],i[1]
return(numbers)
#ACTIAL CODE
x=list(input("type some integers randomly, separating them with spaces "))
#creates a list with the numbers the user gives
y=[int(i) for i in range(len(x))]#turns list ... | Python | zaydzuhri_stack_edu_python |
import keras
from keras.models import Sequential
from keras.layers import LSTM , Embedding , Dense , SimpleRNN
from keras.optimizers import Adam , RMSprop
import pickle
import data_handle_keras_my as prep
comment Parameters
comment ==================================================
comment Data loading params
comment "... | import keras
from keras.models import Sequential
from keras.layers import LSTM, Embedding, Dense, SimpleRNN
from keras.optimizers import Adam, RMSprop
import pickle
import data_handle_keras_my as prep
# Parameters
# ==================================================
# Data loading params
dev_sample_percentage = .1 ... | Python | zaydzuhri_stack_edu_python |
function remove self
begin
call _delete
end function | def remove(self):
self._delete() | Python | nomic_cornstack_python_v1 |
import PySimpleGUI as gui
import matplotlib
call use string Agg
import matplotlib.pyplot as plt
import time
import sys
from os import system , name
import threading
import Our_collector | import PySimpleGUI as gui
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import time
import sys
from os import system, name
import threading
import Our_collector | Python | zaydzuhri_stack_edu_python |
comment from gym_gomoku.envs.util
from gym.utils import seeding
from gym_gomoku.envs.util import gomoku_util
set tuple np_random _ = call np_random
comment make_beginner_policy
function defend_policy curr_state
begin
string Return the action Id, if defend situation is needed
set b = board
set player_color = color
set o... | # from gym_gomoku.envs.util
from gym.utils import seeding
from gym_gomoku.envs.util import gomoku_util
np_random, _ = seeding.np_random()
###
### make_beginner_policy
###
def defend_policy(curr_state):
'''Return the action Id, if defend situation is needed
'''
b = curr_state.board
player_color = cur... | Python | zaydzuhri_stack_edu_python |
function get_video_url data
begin
comment type: (dict) -> Optional[str]
set resource = get data string resources list dict at 0
comment try m3u8
set url = get resource string video_stream
comment try mp4
if not url
begin
set files = get resource string files at 0
set mp4 = call get_mime_property files string url string... | def get_video_url(data):
# type: (dict) -> Optional[str]
resource = data.get("resources", [{}])[0]
url = resource.get("video_stream") # try m3u8
if not url: # try mp4
files = resource.get("files")[0]
mp4 = get_mime_property(files, "url", "video/mp4")
url = "https:{}".format(mp4... | 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.