code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Best function
comment Time complexity O(n)
comment Space complexity O(n)
comment PROBLEM STATEMENT
comment Given a number i.e. targetSum and an array of numbers, find the pair which sums up to give targetSum else return []
comment ============================================
comment APPROACH
comment iterate x t... | #Best function
#Time complexity O(n)
#Space complexity O(n)
#PROBLEM STATEMENT
# Given a number i.e. targetSum and an array of numbers, find the pair which sums up to give targetSum else return []
# ============================================
#APPROACH
# iterate x through the array, if targetSum - x is pres... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Sep 11 13:08:35 2015 @author: ZSHU
class Solution extends object
begin
function search self nums target
begin
string :type nums: List[int] :type target: int :rtype: bool
set left = 0
set right = length nums - 1
while right >= left
begin
if nums at left == target or nu... | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 11 13:08:35 2015
@author: ZSHU
"""
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: bool
"""
left=0; right=len(nums)-1
... | Python | zaydzuhri_stack_edu_python |
function test_api_full_char_corp self mock_api
begin
set return_value = TEST_RESULTS at string full at string char_corp
assert false call is_valid
assert equal call count_keys_in_database 1
end function | def test_api_full_char_corp(self, mock_api):
mock_api.return_value = TEST_RESULTS['full']['char_corp']
self.assertFalse(self.form().is_valid())
self.assertEqual(self.count_keys_in_database(), 1) | Python | nomic_cornstack_python_v1 |
string File with the class that runs the simulation on all designs
from src.designs import designs
class Simulator extends object
begin
string Class that will, for each design: - setup the designs - run the simulation - do the report
function __init__ self minimum_bitwidth maximum_fanout working_dir
begin
set minimum_b... | """File with the class that runs the simulation on all designs"""
from src.designs import designs
class Simulator(object):
"""
Class that will, for each design:
- setup the designs
- run the simulation
- do the report
"""
def __init__(self, minimum_bitwidth, maximum_fanout, w... | Python | zaydzuhri_stack_edu_python |
function constraints self constraints
begin
if constraints is none
begin
set constraints = list
end
else
if not is instance constraints list
begin
set constraints = list constraints
end
for tuple i constraint in enumerate constraints
begin
if is instance constraint TopologicalConstraint
begin
pass
end
else
if callable... | def constraints(self, constraints):
if constraints is None:
constraints = []
elif not isinstance(constraints, list):
constraints = list(constraints)
for i, constraint in enumerate(constraints):
if isinstance(constraint, TopologicalConstraint):
... | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
import getpass
import time
comment codechef credentials for login
set username = string Your Username
set password = call getpass string Password:
comment problem code
set problem = string TEST
comment submission code
set code = string while True: a = int(raw_input()) if a==42: break else... | from selenium import webdriver
import getpass
import time
# codechef credentials for login
username = "Your Username"
password = getpass.getpass("Password:")
# problem code
problem = 'TEST'
# submission code
code = """
while True:
a = int(raw_input())
if a==42:
break
else:
print(a)
"""
# start a br... | Python | zaydzuhri_stack_edu_python |
function create_stats_figure results stat_name p_name alpha=0.05 log_stats=true diverging=false stat_range=none correction=none vertline=4 marker_color=none
begin
set score_index = unique string score
set contrast_index = unique string contrast
set stat_values = loc at tuple score_index contrast_index
set p_values = lo... | def create_stats_figure(
results, stat_name, p_name, alpha=0.05, log_stats=True,
diverging=False, stat_range=None, correction=None, vertline=4,
marker_color=None
):
score_index = results.index.unique('score')
contrast_index = results.index.unique('contrast')
stat_values = (res... | Python | nomic_cornstack_python_v1 |
function __eq__ self card
begin
return value == value and suit == suit
end function | def __eq__(self, card):
return self.value == card.value and self.suit == card.suit | Python | nomic_cornstack_python_v1 |
set tuple a b c = tuple 10 20 30
print a type a
set tuple a b c = tuple 10 20.5 string sathya
print c type c | a,b,c=10,20,30
print(a,type(a))
a,b,c=10,20.5,"sathya"
print(c,type(c)) | Python | zaydzuhri_stack_edu_python |
import math
function is_prime num
begin
string Function to check for prime number
if num == 1
begin
return false
end
for i in range 2 integer square root num + 1
begin
if num % i == 0
begin
return false
end
end
return true
end function
function get_first_prime_numbers limit
begin
string Function to get the first limit ... | import math
def is_prime(num):
"""Function to check for prime number"""
if num == 1:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def get_first_prime_numbers(limit):
"""Function to get the first limit prime numbers... | Python | flytech_python_25k |
function get_balances self
begin
set balances = call private_api url + string trading/balance
return list comprehension i for i in balances if i at string available != string 0
end function | def get_balances(self):
balances = self.private_api(self.url + "trading/balance")
return [i for i in balances if i["available"] != '0'] | Python | nomic_cornstack_python_v1 |
comment real signature unknown; restored from __doc__
function hole self p_int
begin
return list
end function | def hole(self, p_int): # real signature unknown; restored from __doc__
return [] | Python | nomic_cornstack_python_v1 |
function handle_event self event
begin
if type == QUIT
begin
set is_running : bool = false
return
end
if type == TEXTINPUT
begin
set result_value = result_value + text
return
end
if type != KEYDOWN
begin
return
end
if key == K_BACKSPACE
begin
set result_value : str = result_value at slice : - 1 :
return
end
if key ==... | def handle_event(self, event: pygame.Event) -> None:
if event.type == pygame.QUIT:
self.is_running: bool = False
return
if event.type == pygame.TEXTINPUT:
self.result_value += event.text
return
if event.type != pygame.KEYDOWN:
return
... | Python | nomic_cornstack_python_v1 |
function partition lst low high
begin
set i = low - 1
set pivot = lst at high
for j in range low high
begin
if lst at j >= pivot
begin
set i = i + 1
set tuple lst at i lst at j = tuple lst at j lst at i
end
end
set tuple lst at i + 1 lst at high = tuple lst at high lst at i + 1
return i + 1
end function
function quikso... | def partition(lst, low, high):
i = low - 1
pivot = lst[high]
for j in range(low, high):
if lst[j] >= pivot:
i += 1
lst[i], lst[j] = lst[j], lst[i]
lst[i+1], lst[high] = lst[high], lst[i+1]
return i+1
def quiksort_help(lst, low, high):
if low <= hig... | Python | zaydzuhri_stack_edu_python |
function in_order self
begin
for node_data in call _in_order_helper _root
begin
yield node_data
end
end function | def in_order(self):
for node_data in self._in_order_helper(self._root):
yield node_data | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
comment create data
set data = list 3 5 2 8 9 10
comment set plot size
figure figsize=tuple 5 2
comment generate the bar chart
bar list comprehension string i for i in range 1 length data + 1 data
show | import matplotlib.pyplot as plt
#create data
data = [3, 5, 2, 8, 9, 10]
#set plot size
plt.figure(figsize=(5, 2))
#generate the bar chart
plt.bar([str(i) for i in range(1, len(data)+1)], data)
plt.show() | Python | jtatman_500k |
class Product
begin
function __init__ self name cost
begin
set name = name
set cost = cost
end function
end class
function calculate_total_cost products quantity
begin
set total_cost = 0
if length products != length quantity
begin
raise call ValueError string Invalid input lengths
end
for i in range length products
beg... | class Product:
def __init__(self, name, cost):
self.name = name
self.cost = cost
def calculate_total_cost(products, quantity):
total_cost = 0
if len(products) != len(quantity):
raise ValueError("Invalid input lengths")
for i in range(len(products)):
if quantity... | Python | jtatman_500k |
function getBestTimestamp filePath
begin
set bestDate = string
set bestTimestamp = none
comment Replace the 'best date' with what we can gleen from EXIF data
set bestDate = string call getBestEXIFDate filePath
print format string Best Date: {bestDate} bestDate=bestDate
if bestDate != string
begin
try
begin
set bestTi... | def getBestTimestamp(filePath):
bestDate = ''
bestTimestamp = None
# Replace the 'best date' with what we can gleen from EXIF data
bestDate = str(getBestEXIFDate(filePath))
print(' Best Date: {bestDate}'.format(bestDate=bestDate))
if bestDate != '':
try:
bestTimestamp = ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string CS224N 2018-19: Homework 5
comment YOUR CODE HERE for part 1h
import torch
import torch.nn as nn
import torch.nn.functional as F
class Highway extends Module
begin
function __init__ self e_word dropout_rate
begin
comment Set up the 2 linear layers for p... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2018-19: Homework 5
"""
### YOUR CODE HERE for part 1h
import torch
import torch.nn as nn
import torch.nn.functional as F
class Highway(nn.Module):
def __init__(self, e_word, dropout_rate):
# Set up the 2 linear layers for proj and gate and a dropout... | Python | zaydzuhri_stack_edu_python |
function __call__ self *args **kwargs
begin
return call all_edges *args keyword kwargs
end function | def __call__(self, *args, **kwargs):
return self._graph.all_edges(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
from utils import *
comment `grid` is defined in the test code scope as the following:
comment (note: changing the value here will _not_ change the test code)
set grid = string ..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..
function grid_values grid
begin
string Convert grid string in... | from utils import *
# `grid` is defined in the test code scope as the following:
# (note: changing the value here will _not_ change the test code)
grid = '..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3..'
def grid_values(grid):
"""Convert grid string into {<box>: <value>} dict wi... | Python | zaydzuhri_stack_edu_python |
function type self type
begin
set _type = type
end function | def type(self, type):
self._type = type | Python | nomic_cornstack_python_v1 |
function _add_policy self policy
begin
set by_name at upper name = policy
set by_index at integer policy = policy
end function | def _add_policy(self, policy):
self.by_name[policy.name.upper()] = policy
self.by_index[int(policy)] = policy | Python | nomic_cornstack_python_v1 |
string Created on 01-Sep-2014 @author: Rahul Description: Home for all the custom implemented exceptions.
class DoesNotExist extends Exception
begin
string Raised when we try to access a resource that does not exist
function __init__ self *args **kwargs
begin
string Initialize.
call __init__ self *args keyword kwargs
e... | '''
Created on 01-Sep-2014
@author: Rahul
Description: Home for all the custom implemented exceptions.
'''
class DoesNotExist(Exception):
'''
Raised when we try to access a resource that does not exist
'''
def __init__(self, *args, **kwargs):
'''
Initialize.
'''
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.utils.http import urlencode
from rest_framework import status
from rest_framework.test import APITestCase
from models import Category
class CategoryTests extend... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.core.urlresolvers import reverse
from django.utils.http import urlencode
from rest_framework import status
from rest_framework.test import APITestCase
from .models import Category
class CategoryTests(APITestC... | Python | zaydzuhri_stack_edu_python |
function train self dataset remaining_time_budget=none
begin
info string Note: speech_train_process model.py starts train
call as_timer string train_start
if IF_TRAIN_BREAK_CONDITION
begin
while true
begin
set cur_train_his_report = call train_pipeline dataset
set cur_cls_name = get cur_train_his_report string cls_name... | def train(self, dataset, remaining_time_budget=None):
logger.info("Note: speech_train_process model.py starts train")
as_timer("train_start")
if IF_TRAIN_BREAK_CONDITION:
while True:
self.cur_train_his_report = self.domain_model.train_pipeline(dataset)
... | Python | nomic_cornstack_python_v1 |
import cPickle as pickle
import gzip
import os
import urllib
import numpy as np
set urls = dict string mnist.pkl.gz string http://deeplearning.net/data/mnist/mnist.pkl.gz ; string spaun_sym.pkl.gz string http://files.figshare.com/2106874/spaun_sym.pkl.gz
function read_file filepath
begin
if not exists path filepath
beg... | import cPickle as pickle
import gzip
import os
import urllib
import numpy as np
urls = {
'mnist.pkl.gz': 'http://deeplearning.net/data/mnist/mnist.pkl.gz',
'spaun_sym.pkl.gz': 'http://files.figshare.com/2106874/spaun_sym.pkl.gz',
}
def read_file(filepath):
if not os.path.exists(filepath):
if fil... | Python | zaydzuhri_stack_edu_python |
function __generateSentences self ngrams n length repetition seed
begin
set randInt = random integer 1 repetition
set sent = string
for i in range randInt
begin
set sent = sent + call __markovGen ngrams n length seed
set sent = sent + string
end
return sent
end function | def __generateSentences(self, ngrams, n, length, repetition, seed):
randInt = random.randint(1, repetition)
sent = ''
for i in range(randInt):
sent += self.__markovGen(self.ngrams, n, length, seed)
sent += ' '
return sent | Python | nomic_cornstack_python_v1 |
function resolve_compound_variable_fields thread_id frame_id scope attrs user_type_renderers=dict
begin
set offset = call get_offset attrs
set tuple orig_attrs attrs = tuple attrs if expression offset then split attrs string 1 at 1 else attrs
set var = call getVariable thread_id frame_id scope attrs
set var_expr = joi... | def resolve_compound_variable_fields(thread_id, frame_id, scope, attrs, user_type_renderers={}):
offset = get_offset(attrs)
orig_attrs, attrs = attrs, attrs.split('\t', 1)[1] if offset else attrs
var = getVariable(thread_id, frame_id, scope, attrs)
var_expr = ".".join(attrs.split('\t'))
try:
... | Python | nomic_cornstack_python_v1 |
function _update_dict self dictionary key rank value
begin
if call has_key key
begin
set old_rank = dictionary at key at 1
comment old value is not none and current rank is lower
if dictionary at key at 0 is not none and rank > old_rank
begin
return dictionary
end
end
comment ranker is higher or no key or old value is ... | def _update_dict(self, dictionary, key, rank, value):
if dictionary.has_key(key):
old_rank = dictionary[key][1]
# old value is not none and current rank is lower
if dictionary[key][0] is not None and rank > old_rank:
return dictionary
# ranker is highe... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import os.path
import mimetypes
import smtplib
import getpass
from email.message import EmailMessage
comment variable list which must be filled in before program is run #
set web_address = string 192.168.1.214
function generate_email sender receiver subject body attachment
begin
set message = ... | #!/usr/bin/python3
import os.path
import mimetypes
import smtplib
import getpass
from email.message import EmailMessage
###############################################################
# variable list which must be filled in before program is run #
###############################################################
web_a... | Python | zaydzuhri_stack_edu_python |
class SingleTon
begin
function __new__ cls *args **kwargs
begin
if not has attribute cls string _instance
begin
set _instance = call __new__ cls *args keyword kwargs
end
return _instance
end function
end class
set o1 = call SingleTon
print string object - 1 ==> o1
set data = 10
set o2 = call SingleTon
print string obje... | class SingleTon():
def __new__(cls,*args,**kwargs):
if not hasattr(cls,'_instance'):
cls._instance = super().__new__(cls,*args,**kwargs)
return cls._instance
o1 = SingleTon()
print("object - 1 ==>",o1)
o1.data = 10
o2 = SingleTon()
print("object - 2 ==>",o2)
print("object - 2 data ==... | Python | zaydzuhri_stack_edu_python |
comment Tkinter wird für das GUI importiert - Einfachere Funktionen, um ein GUI zu programmieren
comment Bei RSA_Verschluesslung wird der Code für die Umformung von Buchstaben zu Bytes importiert - Um auch Buchstaben zu Verschlüsseln
import math
from tkinter import *
import tkinter as tk
from Buchstaben_zu_bytes import... | # Tkinter wird für das GUI importiert - Einfachere Funktionen, um ein GUI zu programmieren
# Bei RSA_Verschluesslung wird der Code für die Umformung von Buchstaben zu Bytes importiert - Um auch Buchstaben zu Verschlüsseln
import math
from tkinter import *
import tkinter as tk
from Buchstaben_zu_bytes import convert_to_... | Python | zaydzuhri_stack_edu_python |
function get_email self
begin
return email
end function | def get_email(self):
return self.email | Python | nomic_cornstack_python_v1 |
function is_massive self
begin
return value in attributes
end function | def is_massive(self) -> bool:
return ATTRIBUTE.Massive.value in self.type_data.attributes | Python | nomic_cornstack_python_v1 |
import numpy as np
from scipy.spatial import distance
from collections import Counter
from sklearn.feature_selection import mutual_info_classif
from ReliefF import ReliefF
class kNNAlgorithm
begin
function __init__ self n_neighbors=5 policy=string majority_class weights=string equal metric=string minkowski
begin
string... | import numpy as np
from scipy.spatial import distance
from collections import Counter
from sklearn.feature_selection import mutual_info_classif
from ReliefF import ReliefF
class kNNAlgorithm:
def __init__(self, n_neighbors: int = 5, policy='majority_class', weights='equal', metric='minkowski'):
"""
... | Python | zaydzuhri_stack_edu_python |
for tuple v x in enumerate _p
begin
set _a at x = list v
end
print _a
set last = _p at - 1
set new_last = 0
for i in range length _p 30000000
begin
if length _a at last > 1
begin
set new_last = _a at last at 1 - _a at last at 0
end
else
begin
set new_last = 0
end
if new_last not in _a
begin
set _a at new_last = list i
... | for v,x in enumerate(_p):
_a[x] = [v]
print(_a)
last = _p[-1]
new_last = 0
for i in range(len(_p),30000000):
if len(_a[last]) > 1:
new_last = _a[last][1]-_a[last][0]
else:
new_last = 0
if new_last not in _a:
_a[new_last] = [i]
_a[new_last].append(i)
if len(_a[new_last]) >... | Python | zaydzuhri_stack_edu_python |
function InsertionSort A n
begin
string Algorithm InsertionSort(A): Input: An array A of n comparable elements Output: The array A with elements rearranged in nondecreasing order for k from 1 to n − 1 do Insert A[k] at its proper location within A[0], A[1], ..., A[k]
for i in range 1 n
begin
set temp = A at i
set hole ... | def InsertionSort(A,n):
''' Algorithm InsertionSort(A):
Input: An array A of n comparable elements
Output: The array A with elements rearranged in nondecreasing order
for k from 1 to n − 1 do
Insert A[k] at its proper location within A[0], A[1], ..., A[k] '''
for i in range(1,n):
temp=A[i]
hole=i
for j in r... | Python | zaydzuhri_stack_edu_python |
function get_provincial_trends province
begin
set trends = list
set doc = call find_one dict PROVINCE_KEY province
if doc
begin
set trends = call format_trends doc at string trends
end
return trends
end function | def get_provincial_trends(province):
trends = []
doc = prov_trends_coll.find_one({PROVINCE_KEY: province})
if doc:
trends = format_trends(doc["trends"])
return trends | Python | nomic_cornstack_python_v1 |
for i in range n
begin
set tuple a b = list input
append l a
append l b
end
set c = 1
for i in range 1 length l - 1 2
begin
if l at i == l at i + 1
begin
set c = c + 1
end
end
print c | for i in range(n):
a, b = list(input())
l.append(a)
l.append(b)
c = 1
for i in range(1, len(l)-1, 2):
if l[i] == l[i+1]:
c += 1
print(c)
| Python | zaydzuhri_stack_edu_python |
comment integrate x^2 between 1 and 4
comment (1/3 4^3 - 1/3 1^3)
import random
set count = 0
set trials = 100000
set estimates = list
for i in range trials
begin
set x = uniform 1 4
append estimates x ^ 2
end
print 4 - 1 / trials * sum estimates | # integrate x^2 between 1 and 4
# (1/3 4^3 - 1/3 1^3)
import random
count = 0
trials = 100000
estimates = []
for i in range(trials):
x = random.uniform(1,4)
estimates.append(x**2)
print((4-1) / trials*sum(estimates)) | Python | zaydzuhri_stack_edu_python |
import time
from functions import *
if __name__ == string __main__
begin
print string Thank you for using Ticket Reader by Zihao Zheng for Zendesk Engineering Co-op coding challenge! + string Please wait while the code work really really hard to retrieve all the tickets
set credential = call GetCredential
set AllTicket... | import time
from functions import *
if __name__ == '__main__':
print('Thank you for using Ticket Reader by Zihao Zheng for Zendesk Engineering Co-op coding challenge!\n' + \
'Please wait while the code work really really hard to retrieve all the tickets')
credential = GetCredential()
AllTickets = GetAl... | Python | zaydzuhri_stack_edu_python |
class MaxHeap
begin
function __init__ self capacity
begin
set _capacity = capacity
set _a = list none * _capacity + 1
set _size = 0
end function
function insert self data
begin
if _size == _capacity
begin
return
end
set _size = _size + 1
set _a at _size = data
set i = _size
while integer i / 2 > 0 and _a at integer i /... | class MaxHeap:
def __init__(self, capacity: int):
self._capacity = capacity
self._a = [None]*(self._capacity+1)
self._size = 0
def insert(self, data:int):
if self._size == self._capacity:
return
self._size += 1
self._a[self._size] = data
i = ... | Python | zaydzuhri_stack_edu_python |
function http_put self path query_data=none post_data=none files=none **kwargs
begin
set query_data = query_data or dict
set post_data = post_data or dict
set result = call http_request string put path query_data=query_data post_data=post_data files=files keyword kwargs
try
begin
return json result
end
except Excepti... | def http_put(self, path, query_data=None, post_data=None, files=None, **kwargs):
query_data = query_data or {}
post_data = post_data or {}
result = self.http_request(
"put",
path,
query_data=query_data,
post_data=post_data,
files=files... | Python | nomic_cornstack_python_v1 |
import discord
from discord.ext import commands
import asyncio
import json
import os
set prefix = tuple string $ string .
set bot = call Bot command_prefix=prefix
decorator event
async function on_ready
begin
print string -------------
print string User:: { name }
print string ID:: { string id }
print string Version:: ... | import discord
from discord.ext import commands
import asyncio
import json
import os
prefix = ("$", ".")
bot = commands.Bot(command_prefix=prefix)
@bot.event
async def on_ready():
print("-------------")
print(f'User::{bot.user.name}')
print(f'ID::{str(bot.user.id)}')
print(f'Version::{discord.__versi... | Python | zaydzuhri_stack_edu_python |
function read_cube_toml filename fixer_data_filename=none
begin
set raw_data = load toml filename
set cube_list = list comprehension call from_raw_data *tup for tup in items raw_data
if fixer_data_filename
begin
set fixers = load toml fixer_data_filename
for card in cube_list
begin
if name in fixers
begin
set fixer_col... | def read_cube_toml(filename, fixer_data_filename=None):
raw_data = toml.load(filename)
cube_list = [Card.from_raw_data(*tup) for tup in raw_data.items()]
if fixer_data_filename:
fixers = toml.load(fixer_data_filename)
for card in cube_list:
if card.name in fixers:
... | Python | nomic_cornstack_python_v1 |
import struct
class Header
begin
string ver : portal protocol version 0x01 | 0x02 type : 0x01 ~ 0x0a auth : Chap 0x00 | Pap 0x01 rsv : reserve byte always 0x00 serial : serial number req : req id ip : user ip (wlan user's ip) port : haven't used, always 0 err : error code num : attribute number
set _FMT = string >BBBBH... | import struct
class Header():
'''
ver : portal protocol version 0x01 | 0x02
type : 0x01 ~ 0x0a
auth : Chap 0x00 | Pap 0x01
rsv : reserve byte always 0x00
serial : serial number
req : req id
ip : user ip (wlan user's ip)
port ... | Python | zaydzuhri_stack_edu_python |
comment # -- coding: utf-8 --
comment import pytest
comment class TestSingleParametrize:
comment """
comment 函数数据参数化:方便测试函数对测试数据的获取
comment 单个参数:
comment """
comment def setup_class(self):
comment print("------->setup_single_class")
comment def teardown_class(self):
comment print("------->teardown_single_class")
commen... | # # -- coding: utf-8 --
#
#
# import pytest
#
#
# class TestSingleParametrize:
# """
# 函数数据参数化:方便测试函数对测试数据的获取
# 单个参数:
# """
# def setup_class(self):
# print("------->setup_single_class")
#
# def teardown_class(self):
# print("------->teardown_single_class")
#
# @pytest.mark.p... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode id=279 lang=python3
comment [279] Perfect Squares
comment @lc code=start
class Solution
begin
function numSquares self n
begin
set flag = n
set res = list
while flag > 5
begin
set root = call numSquares flag
append res root
print res
set flag = n - root * root
end
if flag == 5
begin
append res... | #
# @lc app=leetcode id=279 lang=python3
#
# [279] Perfect Squares
#
# @lc code=start
class Solution:
def numSquares(self, n: int) -> int:
flag = n
res = []
while flag > 5:
root = self.numSquares(flag)
res.append(root)
print(res)
flag = n - ro... | Python | zaydzuhri_stack_edu_python |
function generate_elevation_profile line
begin
set elem = call from_shape line 4326
set line_cte = call cte name=string line
set cells_cte = call cte name=string cells
comment Get the centroid of the cell which intersects our line
comment Type coerce the return value so we van access the `geom` and
comment `val` attrib... | def generate_elevation_profile(line):
elem = from_shape(line, 4326)
line_cte = db.session.query(
func.ST_Transform(elem, 28992).label("geom")).cte(name="line")
cells_cte = db.session.query(
# Get the centroid of the cell which intersects our line
func.ST_Centroid(
#... | Python | nomic_cornstack_python_v1 |
comment import the necessary packages
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.cross_validation import train_test_split
import glob
from skimage import io
import numpy as np
import imutils
import cv2
import os
function i... | # import the necessary packages
from sklearn.neighbors import KNeighborsClassifier
from sklearn.neural_network import MLPClassifier
from sklearn.svm import SVC
from sklearn.cross_validation import train_test_split
import glob
from skimage import io
import numpy as np
import imutils
import cv2
import os
def image_to_fe... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
call create_all
set user = call User string eschoppik string secret string Elie S string elie@elie.com
add session user
commit session
end function | def setUp(self):
db.create_all()
user = User("eschoppik", "secret", "Elie S", "elie@elie.com")
db.session.add(user)
db.session.commit() | Python | nomic_cornstack_python_v1 |
function _get_vertex_face_adjacency self data=none
begin
comment Input checks:
set nv = shape at 0
comment Convert to an ndarray or pass if already is one
set f = faces
comment Computation
comment Flatten indices
set row = reshape f - 1
comment Data for vertices
set col = reshape call tile reshape array range length f ... | def _get_vertex_face_adjacency(self, data=None):
# Input checks:
nv = self.vertices.shape[0]
f = self.faces # Convert to an ndarray or pass if already is one
# Computation
row = f.reshape(-1) # Flatten indices
col = np.tile(np.arange(len(f)).reshape((-1, 1)), (1, f.shap... | Python | nomic_cornstack_python_v1 |
function on_trials_completed self values perfs_train losses_train perfs_val losses_val
begin
pass
end function | def on_trials_completed(self, values: tuple, perfs_train: np.ndarray,
losses_train: np.ndarray,
perfs_val: np.ndarray,
losses_val: np.ndarray):
pass | Python | nomic_cornstack_python_v1 |
function logMelSpectrum input samplingrate
begin
set nfft = shape at 1
set tr_filter = call trfbank samplingrate nfft
return log dot input transpose tr_filter
end function | def logMelSpectrum(input, samplingrate):
nfft = input.shape[1]
tr_filter = trfbank(samplingrate, nfft)
return np.log(np.dot(input, tr_filter.transpose())) | Python | nomic_cornstack_python_v1 |
function create_project self collab_id
begin
string Create a new project. Args: collab_id (int): The id of the collab the project should be created in. Returns: A dictionary of details of the created project:: { u'collab_id': 12998, u'created_by': u'303447', u'created_on': u'2017-03-21T14:06:32.293902Z', u'description'... | def create_project(self, collab_id):
'''Create a new project.
Args:
collab_id (int): The id of the collab the project should be created in.
Returns:
A dictionary of details of the created project::
{
u'collab_id': 12998,
... | Python | jtatman_500k |
import string
function create_new_string original_string
begin
set new_string = string
for char in original_string
begin
if is upper char
begin
set new_string = new_string + char
end
end
if length new_string > 5 and any generator expression char in punctuation for char in new_string
begin
return new_string
end
return ... | import string
def create_new_string(original_string):
new_string = ""
for char in original_string:
if char.isupper():
new_string += char
if len(new_string) > 5 and any(char in string.punctuation for char in new_string):
return new_string
return "No such string exists"
# ... | Python | greatdarklord_python_dataset |
function get_possible_exploit self
begin
return tuple string exploit run
end function | def get_possible_exploit(self):
return 'exploit', self.exploit.run() | Python | nomic_cornstack_python_v1 |
import copy
class Node
begin
function __init__ self num
begin
set num = num
set followings = list
comment I want to record all of the possibilities of shortest paths,
comment so I use list to record the prev node.
comment prev only be used in BFS
set prev = list
end function
function addFollowing self node
begin
appe... | import copy
class Node:
def __init__(self, num):
self.num = num
self.followings = []
# I want to record all of the possibilities of shortest paths,
# so I use list to record the prev node.
# prev only be used in BFS
self.prev = []
def addFollowing(self, node):
self.followings.append(node)
... | Python | zaydzuhri_stack_edu_python |
import requests
import json
import os
import sys
comment from PIL import Image
from io import BytesIO
import pandas as pd
function analyze
begin
comment Enter Subscription key and resource name
set subscription_key = string <Enter subscription key for face api>
set face_api_url = string https://<Enter name of the resou... | import requests
import json
import os
import sys
#from PIL import Image
from io import BytesIO
import pandas as pd
def analyze():
#Enter Subscription key and resource name
subscription_key = "<Enter subscription key for face api>"
face_api_url = 'https://<Enter name of the resource>.cognit... | Python | zaydzuhri_stack_edu_python |
import random
import pygame
import math
import time
import socket
import re
import queue
call init
set myfont = call SysFont string Times New Roman 25
set titfont = call SysFont string Comic Sans MS 40
set s = string
set phase = 0
set TCP_IP = string 127.0.0.1
set TCP_PORT = 5005
set BUFFER_SIZE = 2048
set colours = d... | import random
import pygame
import math
import time
import socket
import re
import queue
pygame.font.init()
myfont = pygame.font.SysFont('Times New Roman', 25)
titfont = pygame.font.SysFont('Comic Sans MS', 40)
s= ''
phase = 0
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 2048
colours = {"blood3":(0x8e, 0x09, 0x2... | Python | zaydzuhri_stack_edu_python |
class Foo extends object
begin
set v = 100
function __unicode__ self
begin
return string v = %s % v
end function
function __repr__ self
begin
return call __unicode__
end function
end class
class A extends object
begin
set x = call Foo
end class
class B extends A
begin
pass
end class
class C extends A
begin
pass
end cla... | class Foo(object):
v = 100
def __unicode__(self):
return 'v = %s' % (self.v)
def __repr__(self):
return self.__unicode__()
class A(object):
x = Foo()
class B(A):
pass
class C(A):
pass
if __name__ == '__main__':
a1 = A()
a2 = A()
b = B()
c = C() | Python | zaydzuhri_stack_edu_python |
function find_longest_word strings
begin
set max_length = 0
set longest_word = string
for string in strings
begin
set current_word = string
set current_length = 0
for char in string
begin
if is alpha char
begin
set current_word = current_word + char
set current_length = current_length + 1
end
else
begin
if current_le... | def find_longest_word(strings):
max_length = 0
longest_word = ""
for string in strings:
current_word = ""
current_length = 0
for char in string:
if char.isalpha():
current_word += char
current_length += 1
else:
... | Python | jtatman_500k |
function get_report_hash diag file_path hash_type
begin
set hash_content = none
if hash_type == CONTEXT_FREE
begin
set hash_content = call __get_report_hash_context_free diag file_path
end
else
if hash_type == PATH_SENSITIVE
begin
set hash_content = call __get_report_hash_path_sensitive diag file_path
end
else
if hash_... | def get_report_hash(diag: Diag, file_path: str, hash_type: HashType) -> str:
hash_content = None
if hash_type == HashType.CONTEXT_FREE:
hash_content = __get_report_hash_context_free(diag, file_path)
elif hash_type == HashType.PATH_SENSITIVE:
hash_content = __get_report_hash_path_sensitive(d... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment download an image from tcga-gdc and tile it and delete the original
import pandas as pd
from optparse import OptionParser
import sys
function download_jobs files
begin
comment create a list of jobs to download files from gdc
set jobs = list
for file in files
begin
append jobs forma... | #!/usr/bin/env python
# download an image from tcga-gdc and tile it and delete the original
import pandas as pd
from optparse import OptionParser
import sys
def download_jobs(files):
# create a list of jobs to download files from gdc
jobs = []
for file in files:
jobs.append('curl --remote-name -... | Python | zaydzuhri_stack_edu_python |
function saveToFile self filename=string priv.key
begin
set key_file = open filename string w
write key_file string lamb + string ; + string mu
close key_file
end function | def saveToFile (self, filename="priv.key"):
key_file = open(filename, "w")
key_file.write(str(self.lamb) + ";" + str(self.mu))
key_file.close() | Python | nomic_cornstack_python_v1 |
import pyprinter
from detect.core.base_scan import Scan
from detect.core.scan_result import ScanResult
from scapy.all import srp , ARP , Ether
import scapy
class LANIPScanResult extends object
begin
function __init__ self mac ip
begin
set mac = mac
set ip = ip
end function
function pretty_print self printer=none
begin
... | import pyprinter
from detect.core.base_scan import Scan
from detect.core.scan_result import ScanResult
from scapy.all import srp, ARP, Ether
import scapy
class LANIPScanResult(object):
def __init__(self, mac, ip):
self.mac = mac
self.ip = ip
def pretty_print(self, printer=None):
printe... | Python | zaydzuhri_stack_edu_python |
comment 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
comment 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
comment 示例:
comment 给定 nums = [2, 7, 11, 15], target = 9
comment 因为 nums[0] + nums[1] = 2 + 7 = 9
comment 所以返回 [0, 1]
comment 来源:力扣(LeetCode)
comment 链接:https://leetcode-cn.com/problems/two-sum
comment... | # 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
#
# 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
#
# 示例:
#
# 给定 nums = [2, 7, 11, 15], target = 9
#
# 因为 nums[0] + nums[1] = 2 + 7 = 9
# 所以返回 [0, 1]
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/two-sum
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# 方法1:使... | Python | zaydzuhri_stack_edu_python |
function golden_fractal_exp img iterations size color
begin
call golden_fractal_step img iterations - 1 color tuple - size 0 tuple 0 0 string - string +
call golden_fractal_step img iterations - 1 color tuple size 0 tuple 0 0 string + string +
end function | def golden_fractal_exp(img, iterations, size, color):
golden_fractal_step(img, iterations - 1, color,
(-size,0), (0, 0), '-', '+')
golden_fractal_step(img, iterations - 1, color,
(size,0), (0, 0), '+', '+') | Python | nomic_cornstack_python_v1 |
function _calc_read_size self size
begin
if lastbyte
begin
if size > - 1
begin
if realpos + size >= lastbyte
begin
set size = lastbyte - realpos
end
end
else
begin
set size = lastbyte - realpos
end
end
return size
end function | def _calc_read_size(self, size):
if self.lastbyte:
if size > -1:
if ((self.realpos + size) >= self.lastbyte):
size = (self.lastbyte - self.realpos)
else:
size = (self.lastbyte - self.realpos)
return size | Python | nomic_cornstack_python_v1 |
function GetValues self
begin
string Retrieves all values within the key. Returns: generator[WinRegistryValue]: Windows Registry value generator.
if not _registry_key and _registry
begin
call _GetKeyFromRegistry
end
if _registry_key
begin
return call GetValues
end
return iterate list
end function | def GetValues(self):
"""Retrieves all values within the key.
Returns:
generator[WinRegistryValue]: Windows Registry value generator.
"""
if not self._registry_key and self._registry:
self._GetKeyFromRegistry()
if self._registry_key:
return self._registry_key.GetValues()
retu... | Python | jtatman_500k |
function completed self exclude=none
begin
return all generator expression param for param in self if name not in exclude
end function | def completed(self, exclude: typing.Optional[list] = None) -> bool:
return all(param for param in self if param.name not in exclude) | Python | nomic_cornstack_python_v1 |
function tableInsert self searchKey data
begin
comment Calculate adres and make datanode
set adres = call calculateAdres searchKey
set new_node = call DataNode searchKey data
comment Check if a collision occurs
if lijst at adres != string
begin
return call solveCollision adres new_node false
end
else
begin
if collisio... | def tableInsert(self, searchKey, data):
#Calculate adres and make datanode
adres = self.calculateAdres(searchKey)
new_node = DataNode(searchKey, data)
#Check if a collision occurs
if self.lijst[adres] != "":
return self.solveCollision(adres, new_node, False)
e... | Python | nomic_cornstack_python_v1 |
function find_unique cls name version
begin
try
begin
return get objects name=name version=version
end
except DoesNotExist
begin
return none
end
end function | def find_unique(cls, name, version):
try:
return cls.objects.get(name=name, version=version)
except DoesNotExist:
return None | Python | nomic_cornstack_python_v1 |
function evaluate_distibution event_name words session ids
begin
print event_name words
set tuple words_event distribution_event pairs_event = call calculate_distribution_event event_name session ids true
set path_references = call Path LOCAL_DATA_DIR_2 string data event_name string summaries string reference
set refer... | def evaluate_distibution(event_name, words, session, ids):
print(event_name, words)
words_event, distribution_event, pairs_event = calculate_distribution_event(event_name, session, ids, True)
path_references = Path(LOCAL_DATA_DIR_2, 'data', event_name, 'summaries', 'reference')
references_list = [refere... | Python | nomic_cornstack_python_v1 |
import json
function load_json path
begin
string Load json obj from file.
with open path string r as f
begin
set obj = load json f
end
return obj
end function
function compare_floats f s
begin
string Compare float with 5 digits precision. Precision may come as an arg, may use partial here, etc.
return integer f * 10000... | import json
def load_json(path):
"""Load json obj from file."""
with open(path, 'r') as f:
obj = json.load(f)
return obj
def compare_floats(f, s):
"""Compare float with 5 digits precision.
Precision may come as an arg, may use partial here, etc.
"""
return int(f * 100000) == int... | Python | zaydzuhri_stack_edu_python |
function get_overlap residue contact_mask cutoff
begin
set vals = list
for atom in residue
begin
set pos = pos
set val = call interpolate_value pos
comment nearest_point = contact_mask.get_nearest_point(pos)
comment print(nearest_point)
comment fractional = contact_mask.unit_cell.fractionalize(pos)
comment val = conta... | def get_overlap(residue, contact_mask, cutoff):
vals = []
for atom in residue:
pos = atom.pos
val = contact_mask.interpolate_value(pos)
# nearest_point = contact_mask.get_nearest_point(pos)
# print(nearest_point)
# fractional = contact_mask.unit_cell.fractionalize(pos)
... | Python | nomic_cornstack_python_v1 |
function replace_credit_card_payment_by_id cls credit_card_payment_id credit_card_payment **kwargs
begin
set kwargs at string _return_http_data_only = true
if get kwargs string async
begin
return call _replace_credit_card_payment_by_id_with_http_info credit_card_payment_id credit_card_payment keyword kwargs
end
else
be... | def replace_credit_card_payment_by_id(cls, credit_card_payment_id, credit_card_payment, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return cls._replace_credit_card_payment_by_id_with_http_info(credit_card_payment_id, credit_card_payment, **kwargs)
else:... | Python | nomic_cornstack_python_v1 |
function setUp self
begin
set screentype_patcher = patch string turtle._Screen new=Mock
set mock_screentype = start screentype_patcher
set screen_patcher = patch string turtle.Turtle._screen
set mock_screen = start screen_patcher
set xscale = 1.0
set yscale = 1.0
set return_value = string standard
set update_patcher = ... | def setUp(self):
self.screentype_patcher = mock.patch(
'turtle._Screen',
new=mock.Mock
)
self.mock_screentype = self.screentype_patcher.start()
self.screen_patcher = mock.patch('turtle.Turtle._screen')
self.mock_screen = self.screen_patcher.start()
... | Python | nomic_cornstack_python_v1 |
string # importing openpyxl module import openpyxl as xl from re import search # opening the source excel file filename = "C:\Users\utsakuma\Documents\Case\2ndApril\1.xlsx" wb1 = xl.load_workbook(filename) wss1 = wb1.worksheets[0] filename = "C:\Users\utsakuma\Documents\Case\2ndApril\2.xlsx" wb2 = xl.load_workbook(file... | """# importing openpyxl module
import openpyxl as xl
from re import search
# opening the source excel file
filename = "C:\\Users\\utsakuma\\Documents\\Case\\2ndApril\\1.xlsx"
wb1 = xl.load_workbook(filename)
wss1 = wb1.worksheets[0]
filename = "C:\\Users\\utsakuma\\Documents\\Case\\2ndApril\\2.xlsx"
wb2 = x... | Python | zaydzuhri_stack_edu_python |
function _write_featuregroup_hive spark_df featuregroup featurestore featuregroup_version mode
begin
set spark = call _find_spark
call _verify_hive_enabled spark
set sc = sparkContext
set sqlContext = call SQLContext sc
call setConf string hive.exec.dynamic.partition string true
call setConf string hive.exec.dynamic.pa... | def _write_featuregroup_hive(spark_df, featuregroup, featurestore, featuregroup_version, mode):
spark = util._find_spark()
_verify_hive_enabled(spark)
sc = spark.sparkContext
sqlContext = SQLContext(sc)
sqlContext.setConf("hive.exec.dynamic.partition", "true")
sqlContext.setConf("hive.exec.dynam... | Python | nomic_cornstack_python_v1 |
import pygame
from Screen.Screen import Screen
import View.ScreenRenderer as gui
import HighScore
import random
import Controller
import Sound
import Screen.GUI as GUI
import Files
class GameOverScreen extends Screen
begin
function __init__ self hiscore scale
begin
call __init__ string GameOver
set useRenderer = false
... | import pygame
from Screen.Screen import Screen
import View.ScreenRenderer as gui
import HighScore
import random
import Controller
import Sound
import Screen.GUI as GUI
import Files
class GameOverScreen(Screen):
def __init__(self,hiscore,scale):
super().__init__("GameOver")
self.useRenderer=False
... | Python | zaydzuhri_stack_edu_python |
function _initialize_mask_from_extern self extern
begin
set tuple xpos ypos = yvals
comment spatial bin numbers
set mask_x = call digitize xpos _xbins right=true - 1
comment spatial bin numbers
set mask_y = call digitize ypos _ybins right=true - 1
set mask = call empty tuple n_xbins n_xbins
set mask at slice : : = n... | def _initialize_mask_from_extern(self, extern):
xpos, ypos = extern.asarray().yvals
mask_x = np.digitize(xpos, self._xbins, right=True) - 1 # spatial bin numbers
mask_y = np.digitize(ypos, self._ybins, right=True) - 1 # spatial bin numbers
mask = np.empty((self.n_xbins, self.n_xbins))
... | Python | nomic_cornstack_python_v1 |
function retrieve_samples_by_chebiid_and_molar chebiid
begin
set chebiid = replace chebiid string : string _
set sparql = call SPARQLWrapper string https://www.ebi.ac.uk/rdf/services/sparql
set query = call Template string SELECT DISTINCT ?sample ?compound WHERE { ?subunit rdfs:subClassOf obo:UO_0000061 . FILTER ( ?sub... | def retrieve_samples_by_chebiid_and_molar(chebiid):
chebiid = chebiid.replace(':', '_')
sparql = SPARQLWrapper("https://www.ebi.ac.uk/rdf/services/sparql")
query = Template("""SELECT DISTINCT ?sample ?compound
WHERE {
?subunit rdfs:subClassOf obo:UO_0000061 .
FILTER ( ?subunit != ef... | Python | nomic_cornstack_python_v1 |
import scipy
import numpy as np
import random
comment global variables
comment dance_data_directory_name = 'tiny_dance_data'
set dance_data_directory_name = string dance_data
set directory_path = string ../ + dance_data_directory_name + string /
set classes = list string ballet string break string flamenco string foxtr... | import scipy
import numpy as np
import random
#global variables
#dance_data_directory_name = 'tiny_dance_data'
dance_data_directory_name = 'dance_data'
directory_path = '../' + dance_data_directory_name + '/'
classes = ['ballet', 'break', 'flamenco', 'foxtrot', 'latin', 'quickstep', 'square', 'swing', 'tango', 'waltz... | Python | zaydzuhri_stack_edu_python |
function bid_details_tutor bid_id
begin
if method == string GET
begin
set bid_details = call get_bid_details bid_id
comment refactoring techniques: replace temp with query
set user_role = call get_user_role
set user_info_list = user_details
set preferred_time_list = list string 08:00 string 08:30 string 09:00 string 09... | def bid_details_tutor(bid_id):
if request.method == 'GET':
bid_details = get_bid_details(bid_id)
# refactoring techniques: replace temp with query
user_role = get_user_role()
user_info_list = user_role.user_details
preferred_time_list = ['08:00','08:30','09:00','09:30','10... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
function high func value
begin
return call func value
end function
set lst = call high dir int
print lst at slice - 3 : :
print lst | #!/usr/bin/env python3
def high(func, value):
return func(value)
lst = high(dir, int)
print(lst[-3:])
print(lst)
| Python | zaydzuhri_stack_edu_python |
from estimator import AEstimator
class MaxLikelihoodEstimator extends AEstimator
begin
string The estimator using maximum likelihood. We hide the pseudocount in here to be used with LaPlace smoothing. By default it is set to 0, which means no smoothing occurs.
function __init__ self pseudocount=0
begin
string Construct... | from estimator import AEstimator
class MaxLikelihoodEstimator(AEstimator):
"""
The estimator using maximum likelihood. We hide the pseudocount in here to be used with LaPlace smoothing.
By default it is set to 0, which means no smoothing occurs.
"""
def __init__(self, pseudocount=0):
"""
... | Python | zaydzuhri_stack_edu_python |
function items self
begin
return list comprehension tuple key value for entry in table if value is not none
end function | def items(self):
return [(entry.key, entry.value) for entry in self.table
if entry.value is not None] | Python | nomic_cornstack_python_v1 |
import tkinter as tk
import requests
import time
function getWeather box
begin
set city = get textField
comment API KEY
set api = string https://api.openweathermap.org/data/2.5/weather?q= + city + string &appid=06c921750b9a82d8f5d1294e1586276f
comment created a variable to store data
set json_data = json get requests a... | import tkinter as tk
import requests
import time
def getWeather(box):
city = textField.get()
# API KEY
api = "https://api.openweathermap.org/data/2.5/weather?q=" + \
city+"&appid=06c921750b9a82d8f5d1294e1586276f"
# created a variable to store data
json_data = requests.get(ap... | Python | zaydzuhri_stack_edu_python |
function can_throw self
begin
if round_points == 0
begin
return false
end
return true
end function | def can_throw(self):
if self.round_points == 0:
return False
return True | Python | nomic_cornstack_python_v1 |
function jeu_interface_qlearning self
begin
call tirer
call charge_cartes
call place_cartes
comment Le joueur A joue
set ac = call takeAction 0.1
comment Le joueurA mise une somme(0, 1, 2, 4) par rapport à l'action effectuée
set actionA = call ActionsVal ac
comment S'il mise on ajoute au pot
if actionA > 0
begin
set po... | def jeu_interface_qlearning(self):
self.tirer()
self.aff.charge_cartes()
self.aff.place_cartes()
ac = self.joueurA.takeAction(0.1) #Le joueur A joue
actionA = self.joueurA.ActionsVal(ac) # Le joueurA mise une somme(0, 1, 2, 4) par rapport à l'action effectuée
if(actionA > 0): # S'il mise on ajoute au pot
... | Python | nomic_cornstack_python_v1 |
function get_open_port
begin
set s = call socket AF_INET SOCK_STREAM
call bind tuple string 0
call listen 1
set port = call getsockname at 1
close s
return port
end function | def get_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 0))
s.listen(1)
port = s.getsockname()[1]
s.close()
return port | Python | nomic_cornstack_python_v1 |
import pygame
from LibreriaGeneral import *
call init
comment ----------------------------------------------------
set width = 1080
set high = 720
set window = call set_mode list width high
set middle = list width / 2 high
set end = false
comment Primer Poligono
set A1 = list 0 0
set A2 = call PolarToCartesian 300 20
s... | import pygame
from LibreriaGeneral import *
pygame.init()
#----------------------------------------------------
width = 1080
high =720
window = pygame.display.set_mode([width,high])
middle = [width/2,high]
end = False
#Primer Poligono
A1 = [0,0]
A2 = PolarToCartesian(300,20)
Aaux1 = PolarToCartesian(200,20)
A3 = Trasl... | Python | zaydzuhri_stack_edu_python |
function get_descriptor dev desc_size desc_type desc_index wIndex=0
begin
set wValue = desc_index ? desc_type ? 8
set bmRequestType = call build_request_type CTRL_IN CTRL_TYPE_STANDARD CTRL_RECIPIENT_DEVICE
return call ctrl_transfer bmRequestType=bmRequestType bRequest=6 wValue=wValue wIndex=wIndex data_or_wLength=desc... | def get_descriptor(dev, desc_size, desc_type, desc_index, wIndex = 0):
wValue = desc_index | (desc_type << 8)
bmRequestType = util.build_request_type(
util.CTRL_IN,
util.CTRL_TYPE_STANDARD,
util.CTRL_RECIPIENT_DEVICE
)
... | Python | nomic_cornstack_python_v1 |
function __new__ cls obj *args **kwargs
begin
try
begin
set cache = __dict__ at string _class_proxy_cache
end
except KeyError
begin
set _class_proxy_cache = dict
set cache = dict
end
try
begin
set theclass = cache at __class__
end
except KeyError
begin
set cache at __class__ = call _create_class_proxy __class__
set t... | def __new__(cls, obj, *args, **kwargs):
try:
cache = cls.__dict__["_class_proxy_cache"]
except KeyError:
cls._class_proxy_cache = cache = {}
try:
theclass = cache[obj.__class__]
except KeyError:
cache[obj.__class__] = theclass = cls._create... | Python | nomic_cornstack_python_v1 |
function fetch_ch_data self
begin
comment realtime self.data
call fetch_arduino_data
comment R-pressed, start to proceess the thread
if start_object_recog
begin
call fetch_realtime_metrix
comment produce self.diffs[totalChannel], print data,base values out
call calDiff
comment produce self.diffs_p[totalChannel]
call ca... | def fetch_ch_data(self):
self.fetch_arduino_data() # realtime self.data
if self.start_object_recog: # R-pressed, start to proceess the thread
self.fetch_realtime_metrix()
self.calDiff() # produce self.diffs[totalChannel], print data,base values out
self.calPosDiff... | Python | nomic_cornstack_python_v1 |
function __init__ self impl_class model_attrs
begin
raise NotImplementedError
end function | def __init__(
self, impl_class: Type[BasePPLImplementation], model_attrs: Dict
) -> None:
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
import csv
set csvfile = open string ./2006_De-Personalised_Extract/persons2006.csv string r
set outfile = open string ./2006_De-Personalised_Extract/persons2006_zfilled.csv string w
comment Now a DictReader and DictWriter
comment DictReader and DictWriter are imported libraries
set reader = dict reader csvfile
set wri... | import csv
csvfile = open('./2006_De-Personalised_Extract/persons2006.csv', 'r')
outfile = open('./2006_De-Personalised_Extract/persons2006_zfilled.csv', 'w')
# Now a DictReader and DictWriter
# DictReader and DictWriter are imported libraries
reader = csv.DictReader(csvfile)
writer = csv.DictWriter(outfile, reader.f... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: UTF-8 -*-
import pandas as pd
function panda_base
begin
set file_path = string ./test-xls.xls
comment sheet_name不指定时默认返回全表数据
set df = call read_excel file_path sheet_name=string Sheet1
comment 打印表数据,如果数据太多,会略去中间部分
comment print(df)
comment 打印头部数据,仅查看数据示例时常用
print head df
comment 打印列标题
print columns
... | # -*- coding: UTF-8 -*-
import pandas as pd
def panda_base():
file_path = r'./test-xls.xls'
# sheet_name不指定时默认返回全表数据
df = pd.read_excel(file_path, sheet_name = "Sheet1")
# 打印表数据,如果数据太多,会略去中间部分
# print(df)
# 打印头部数据,仅查看数据示例时常用
print(df.head())
# 打印列标题
print(df.columns)
# 打印行
print(df.index)
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.