code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import unittest
import DealerGame
import PlayerGame
from Player import Player
from Dealer import Dealer
import Game
from Card import Card
function test_evaluate_win_condition player dealer choice exp_bool
begin
comment assert Game.evaluate_win_condition(player, dealer, choice) == exp_bool, 'Should be ' + str(exp_bool)
... | import unittest
import DealerGame
import PlayerGame
from Player import Player
from Dealer import Dealer
import Game
from Card import Card
def test_evaluate_win_condition(player, dealer, choice, exp_bool):
#assert Game.evaluate_win_condition(player, dealer, choice) == exp_bool, 'Should be ' + str(exp_bool)
pa... | Python | zaydzuhri_stack_edu_python |
import numpy as np
if __name__ == string __main__
begin
print string A
set A = array list tuple 2 - 1 tuple 5 8
print A
print string Z_10
set z10 = call mod A 10
print z10
print string Z_10^(-1)
set z10_inverted = call inv z10
print z10_inverted
print string Z_9
set z9 = call mod A 9
print z9
print string Z_9^(-1)
set ... | import numpy as np
if __name__ == '__main__':
print("A")
A = np.array([(2, -1), (5, 8)])
print(A)
print("Z_10")
z10 = np.mod(A, 10)
print(z10)
print("Z_10^(-1)")
z10_inverted = np.linalg.inv(z10)
print(z10_inverted)
print("Z_9")
z9 = np.mod(A, 9)
print(z9)
... | Python | zaydzuhri_stack_edu_python |
string script_writer.py is to make change.txt. Only a and b are changable.
import sys
import os
import errno
import datetime
set a = argv at 1
set b = argv at 2
comment For logging
set LOGPATH = string ./log/
try
begin
make directories LOGPATH
end
except OSError as e
begin
if errno != EEXIST
begin
raise
end
end
comment... | """
script_writer.py is to make change.txt. Only a and b are changable.
"""
import sys
import os
import errno
import datetime
a = sys.argv[1]
b = sys.argv[2]
# For logging
LOGPATH = "./log/"
try:
os.makedirs(LOGPATH)
except OSError as e:
if e.errno != errno.EEXIST:
raise
# Insertion orders
insert = [... | Python | zaydzuhri_stack_edu_python |
function load_terminfo terminal_name=none fallback=string vt100
begin
set terminal_name = call getenv string TERM
if not terminal_name
begin
if not fallback
begin
raise call TerminfoError string Environment variable TERM is unset and no fallback was requested
end
else
begin
set terminal_name = fallback
end
end
if call ... | def load_terminfo(terminal_name=None, fallback='vt100'):
terminal_name = os.getenv('TERM')
if not terminal_name:
if not fallback:
raise TerminfoError('Environment variable TERM is unset and no fallback was requested')
else:
terminal_name = fallback
if os.getenv('... | Python | nomic_cornstack_python_v1 |
import hashlib
function encode_string_sha256 string
begin
return hex digest sha256 encode string string utf-8
end function | import hashlib
def encode_string_sha256(string):
return hashlib.sha256(string.encode('utf-8')).hexdigest()
| Python | flytech_python_25k |
function __init__ self config
begin
set logger = call getLogger string hg_client
set config = config
call openConnection
end function | def __init__(self, config):
self.logger = logging.getLogger('hg_client')
self.config = config
self.openConnection() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment Return key from metadata
import os
import sys
from configparser import ConfigParser
function read_metadata_key filename key
begin
if not exists path filename
begin
print string File filename string does not exists
exit 1
end
set parser = config parser
read parser filename
return ge... | #!/usr/bin/env python3
# Return key from metadata
import os
import sys
from configparser import ConfigParser
def read_metadata_key( filename, key ):
if not os.path.exists(filename):
print("File",filename,"does not exists")
sys.exit(1)
parser = ConfigParser()
parser.read(filename)
re... | Python | zaydzuhri_stack_edu_python |
function resize_egomotion egomotion target_size
begin
comment unused
del target_size
return egomotion
end function | def resize_egomotion(egomotion, target_size):
del target_size # unused
return egomotion | Python | nomic_cornstack_python_v1 |
function run self
begin
while true
begin
set socks = select select values sockets list list 0.1 at 0
for conn in socks
begin
try
begin
set k = call recv 65535
end
except any
begin
comment either died on a connection reset, or was SIGTERM's by parent
return
end
if k
begin
for sock in sockets
begin
if sockets at sock =... | def run(self):
while True:
socks = select.select(self.sockets.values(), [], [], 0.1)[0]
for conn in socks:
try:
k = conn.recv(65535)
except:
# either died on a connection reset, or was SIGTERM's by parent
return
if k:
for sock in self.socke... | Python | nomic_cornstack_python_v1 |
function target_temperature_high self
begin
return cool_setpoint
end function | def target_temperature_high(self):
return self._element.cool_setpoint | Python | nomic_cornstack_python_v1 |
from google.cloud import storage
import os
from multiprocessing import Pool
from glob import glob
from datetime import datetime
import dateparser
comment Globals
set CREDENTIALS_JSON = string /Users/sushinoya/Downloads/tweets/cs4225-294613-666c370bb34b.json
set BUCKET_NAME = string tweets-unclean
comment Upload Script
... | from google.cloud import storage
import os
from multiprocessing import Pool
from glob import glob
from datetime import datetime
import dateparser
# Globals
CREDENTIALS_JSON = "/Users/sushinoya/Downloads/tweets/cs4225-294613-666c370bb34b.json"
BUCKET_NAME = "tweets-unclean"
# Upload Script
os.environ["GOOGLE_APPLICATI... | Python | zaydzuhri_stack_edu_python |
import numpy as np
class Dense
begin
function __init__ self units input_shape=none name=string Dense
begin
set units = units
set input_shape = input_shape
set name = name
end function
function setParam self shape lr=0
begin
set input_shape = input_shape
if input_shape == none
begin
set input_shape = shape
end
if length... | import numpy as np
class Dense():
def __init__(self, units,input_shape=None,name='Dense'):
self.units = units
self.input_shape = input_shape
self.name = name
def setParam(self,shape,lr=0):
input_shape = self.input_shape
if input_shape == None:
input_shape = s... | Python | zaydzuhri_stack_edu_python |
function swap_case s
begin
set m = call swapcase
return m
end function
set s = input
set result = call swap_case s
print result | def swap_case(s):
m=s.swapcase()
return m
s = input()
result = swap_case(s)
print(result) | Python | zaydzuhri_stack_edu_python |
class NumberIterator
begin
function __init__ self start_number end_number
begin
set start_number = start_number
set end_number = end_number
end function
function __iter__ self
begin
set current_number = start_number
return self
end function
function __next__ self
begin
if current_number > end_number
begin
set current_n... | class NumberIterator:
def __init__(self, start_number, end_number):
self.start_number = start_number
self.end_number = end_number
def __iter__(self):
self.current_number = self.start_number
return self
def __next__(self):
if self.current_number > self.end_number... | Python | zaydzuhri_stack_edu_python |
function test_timestamp
begin
set timestamp = timestamp
assert is instance timestamp str
end function | def test_timestamp():
timestamp = Timestamp()
assert isinstance(timestamp, str) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Apr 20 18:01:46 2021 @author: Nikhil
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle
set dataset = read csv string Fish.csv
set x = values
set y = values
print x
from sklearn.model_selection import train_test_split
set tuple x_trai... | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 20 18:01:46 2021
@author: Nikhil
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import pickle
dataset = pd.read_csv("Fish.csv")
x = dataset.iloc[:,:-1].values
y = dataset.iloc[:,-1].values
print(x)
from sklearn.model_selection import train_t... | Python | zaydzuhri_stack_edu_python |
for i in range length inp
begin
set x = inp at i
set r = r + dr at x
set c = c + dc at x
set vis at tuple r c = 1
if i % 2 == 0
begin
set r1 = r1 + dr at x
set c1 = c1 + dc at x
set vis2 at tuple r1 c1 = 1
end
else
begin
set r2 = r2 + dr at x
set c2 = c2 + dc at x
set vis2 at tuple r2 c2 = 1
end
end
print length keys v... | for i in range(len(inp)):
x = inp[i]
r += dr[x]
c += dc[x]
vis[(r, c)] = 1
if i % 2 == 0:
r1 += dr[x]
c1 += dc[x]
vis2[(r1, c1)] = 1
else:
r2 += dr[x]
c2 += dc[x]
vis2[(r2, c2)] = 1
print(len(vis.keys()), len(vis2.keys()))
| Python | zaydzuhri_stack_edu_python |
function set_style_dict_value self key value
begin
try
begin
if starts with string value string #
begin
set style_dict at key = value
call refresh_style
end
else
begin
raise call ValueError string Invalid Style Value: + string value
end
end
except ValueError as v_err
begin
print string Invalid Parameter: v_err
end
exce... | def set_style_dict_value(self, key: str, value: str):
try:
if str(value).startswith('#'):
self.style_dict[key] = value
self.refresh_style()
else:
raise ValueError('Invalid Style Value: ' + str(value))
except ValueError as v_err:
... | Python | nomic_cornstack_python_v1 |
function load_data_crt_files self data_dict
begin
string Load sEIT data from .ctr files (volt.dat files readable by CRTomo, produced by CRMod) Parameters ---------- data_dict : dict Data files that are imported. See example down below Examples -------- >>> import glob data_files = {} data_files['frequencies'] = 'data/f... | def load_data_crt_files(self, data_dict):
"""Load sEIT data from .ctr files (volt.dat files readable by CRTomo,
produced by CRMod)
Parameters
----------
data_dict : dict
Data files that are imported. See example down below
Examples
--------
... | Python | jtatman_500k |
function serialize self buff
begin
try
begin
set _x = self
write buff call pack seq secs nsecs
set _x = frame_id
set length = length _x
if python3 or type _x == unicode
begin
set _x = encode _x string utf-8
set length = length _x
end
write buff call pack length _x
set _x = self
write buff call pack status index range r... | def serialize(self, buff):
try:
_x = self
buff.write(_get_struct_3I().pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs))
_x = self.header.frame_id
length = len(_x)
if python3 or type(_x) == unicode:
_x = _x.encode('utf-8')
length = len(_x)
buff.writ... | Python | nomic_cornstack_python_v1 |
import logging
from aiogram import Bot , Dispatcher , executor , types
from aiogram.utils.exceptions import BotBlocked
from os import getenv
from sys import exit
import aiogram.utils.markdown as fmt
comment bot_token = getenv("BOT_TOKEN")
comment if not bot_token:
comment exit("Error: no toke provided")
comment Обекс б... | import logging
from aiogram import Bot, Dispatcher, executor, types
from aiogram.utils.exceptions import BotBlocked
from os import getenv
from sys import exit
import aiogram.utils.markdown as fmt
#bot_token = getenv("BOT_TOKEN")
#if not bot_token:
#exit("Error: no toke provided")
#Обекс бота
bot = Bot(tok... | Python | zaydzuhri_stack_edu_python |
function get_head_phrases self phrase
begin
comment retrieve the head path and begin walking down it
if length phrase == 3
begin
set head_phrases = list call get_head_path phrase
end
else
begin
set head_phrases = list phrase
end
return head_phrases
end function | def get_head_phrases(self, phrase):
# retrieve the head path and begin walking down it
if len(phrase) == 3:
head_phrases = list(nt.get_head_path(phrase))
else:
head_phrases = [phrase]
return head_phrases | Python | nomic_cornstack_python_v1 |
function test_delete_meeting_non_auth client meeting
begin
set response = delete reverse string v1:meeting-detail args=list pk
assert status_code == HTTP_403_FORBIDDEN
end function | def test_delete_meeting_non_auth(client, meeting):
response = client.delete(
reverse("v1:meeting-detail", args=[meeting.pk]),
)
assert response.status_code == status.HTTP_403_FORBIDDEN | Python | nomic_cornstack_python_v1 |
function qline xlist ylist
begin
call qplot xlist ylist length xlist
end function | def qline(xlist,ylist):
dislin.qplot(xlist,ylist,len(xlist)) | Python | nomic_cornstack_python_v1 |
function disable_crd_hooks self
begin
return get pulumi self string disable_crd_hooks
end function | def disable_crd_hooks(self) -> pulumi.Output[Optional[bool]]:
return pulumi.get(self, "disable_crd_hooks") | Python | nomic_cornstack_python_v1 |
comment https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string
class Solution
begin
function removeDuplicates self S
begin
set stack = list
for c in S
begin
if stack and c == stack at - 1
begin
pop stack
end
else
begin
append stack c
end
end
return join string stack
end function
function removeDuplica... | # https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string
class Solution:
def removeDuplicates(self, S: str) -> str:
stack = []
for c in S:
if stack and c == stack[-1]:
stack.pop()
else:
stack.append(c)
return ''.join(s... | Python | zaydzuhri_stack_edu_python |
import requests
import json
import random
class Discogs
begin
function __init__ self token
begin
set url = string https://api.discogs.com/
set token = token
end function
function request self params
begin
print format string {}{} url params
set req = get requests format string {}{} url params headers=dict string Author... | import requests
import json
import random
class Discogs:
def __init__(self, token):
self.url = "https://api.discogs.com/"
self.token = token
def request(self, params):
print("{}{}".format(self.url, params))
req = requests.get("{}{}".format(self.url, params),
... | Python | zaydzuhri_stack_edu_python |
function writeTotal self response_body code=none message=none
begin
set content_length = call intToBytes length response_body
call setHeader string Content-Length content_length
if code is not none
begin
call setResponseCode code message=message
end
write self response_body
call ensureFinished
end function | def writeTotal(self, response_body: T.Union[bytes, str], code: T.Union[int, str, bytes] = None,
message: T.Union[bytes, str] = None) -> T.NoReturn:
content_length = intToBytes(len(response_body))
self.setHeader("Content-Length", content_length)
if code is not None:
... | Python | nomic_cornstack_python_v1 |
function qsort arr
begin
if length arr < 2
begin
return arr
end
else
begin
set pivot_position = integer absolute length arr / 2
set pivot = arr at pivot_position
set left_arr = list comprehension i for i in arr if i < pivot
set right_arr = list comprehension i for i in arr if i > pivot
return call qsort left_arr + list... | def qsort(arr):
if len(arr) < 2:
return arr
else:
pivot_position = int(abs(len(arr)/2))
pivot = arr[pivot_position]
left_arr = [i for i in arr if i < pivot]
right_arr = [i for i in arr if i > pivot]
return qsort(left_arr) + [pivot] + qsort(right_arr)
# input_sam... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding: utf-8 -*-
from re import search
from datetime import datetime
from time import mktime , strftime
from calendar import monthcalendar
from datetime import date as getDate
from argparse import ArgumentParser , RawTextHelpFormatter
function datetimer text=string ts=true date=f... | #!/usr/bin/python3
# -*- coding: utf-8 -*-
from re import search
from datetime import datetime
from time import mktime, strftime
from calendar import monthcalendar
from datetime import date as getDate
from argparse import ArgumentParser, RawTextHelpFormatter
def datetimer(text='', ts=True,
date=False, w... | Python | zaydzuhri_stack_edu_python |
function page_display_note self
begin
set tuple task_found task_id task notfound_page = call helper_get_task_or_default
if not task_found
begin
append error_msg_queue_list string Cannot display specified note.
return notfound_page
end
set alt_task_store_name = call helper_get_alt_task_store_name
set highlight_in_text =... | def page_display_note(self):
task_found, task_id, task, notfound_page = self.helper_get_task_or_default()
if not task_found:
self.error_msg_queue_list.append("Cannot display specified note.")
return notfound_page
alt_task_store_name = self.helper_get_alt_task_store_name... | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
call __init__
set propagates_gradient : bool = true
string Indicates if this node propagates gradients to earlier layers.
set needs_input_check : bool = true
string If set to true the input_check method is called.
set instances : Dict at tuple AbstractTensor Instance = dict
string Contains... | def __init__(self):
super().__init__()
self.propagates_gradient: bool = True
"""Indicates if this node propagates gradients to earlier layers."""
self.needs_input_check: bool = True
"""If set to true the input_check method is called."""
self.instances: Dict[AbstractTen... | Python | nomic_cornstack_python_v1 |
function nextButtonFunction self
begin
if i == lenght - 1
begin
call onLastPicture
end
else
begin
set i = i + 1
call picture i
end
end function | def nextButtonFunction(self):
if self.i == self.lenght - 1:
self.onLastPicture()
else:
self.i += 1
self.picture(self.i) | Python | nomic_cornstack_python_v1 |
function __ne__ self other
begin
if not is instance other PatchPolicySummary
begin
return true
end
return call to_dict != call to_dict
end function | def __ne__(self, other):
if not isinstance(other, PatchPolicySummary):
return True
return self.to_dict() != other.to_dict() | Python | nomic_cornstack_python_v1 |
class Kls
begin
pass
end class
set k = call Kls
set j = call Kls
call id k == call id j
comment BAD
print string a + string + string simple + string + string sentence + string + string
comment good
print join string list string a string simple string sentence string .
class C
begin
function __init__ self arg1 arg2
... | class Kls:
pass
k = Kls()
j = Kls()
id(k) == id(j)
# BAD
print('a' +' ' + 'simple' + ' ' + 'sentence' + ' ' +'')
#good
print(' '.join(['a', 'simple', 'sentence', '.']))
class C:
def __init__(self, arg1, arg2):
self.str = arg1
self.lst = arg2
iC = C("arun", [1,2])
print("iC.str:")
print(i... | Python | zaydzuhri_stack_edu_python |
function _binTostr self host
begin
if is instance host int
begin
set binstr = format string {0:b} host
while length binstr < degree
begin
set binstr = string 0 + binstr
end
return binstr
end
return none
end function | def _binTostr(self, host):
if isinstance(host, int):
binstr = "{0:b}".format(host)
while (len(binstr) < self.degree):
binstr = '0' + binstr
return binstr
return None | Python | nomic_cornstack_python_v1 |
function AlgoritmoTraz
begin
comment Pide al usuario que elija una de las siguientes opciones
print string Elija el algoritmo que desee aplicar
print string 1.- Trazador cubico natural
print string 2.- Trazador cubico sujeto
comment Crea la lista que contendra los valores que ingrese el usuario para aplicar el metodo d... | def AlgoritmoTraz():
# Pide al usuario que elija una de las siguientes opciones
print("\nElija el algoritmo que desee aplicar")
print("1.- Trazador cubico natural")
print("2.- Trazador cubico sujeto")
# Crea la lista que contendra los valores que ingrese el usuario para aplicar el metodo de trazador... | Python | nomic_cornstack_python_v1 |
class NondominatedSolutionManager extends object
begin
function __init__ self solutionLen
begin
set solutionLength = solutionLen
set nondominatedSolutions = list
set nondominatedSolutionScoreVecs = list
end function
function has self solution
begin
if solutionLength != length solution
begin
return false
end
for nds i... | class NondominatedSolutionManager(object):
def __init__(self, solutionLen):
self.solutionLength = solutionLen
self.nondominatedSolutions = []
self.nondominatedSolutionScoreVecs = []
def has(self, solution):
if self.solutionLength != len(solution):
... | Python | zaydzuhri_stack_edu_python |
function _add_num_sims_col_to_experimental_conditions_df self param_mean exp_con_df exp_con_cols
begin
if shape at 0 is 0
begin
return call DataFrame
end
if string num_sims in columns
begin
if length exp_con_cols > 0
begin
set param_num_sims = apply group by param_mean list exp_con_cols _set_num_sims_as_max
return call... | def _add_num_sims_col_to_experimental_conditions_df(self, param_mean, exp_con_df, exp_con_cols):
if param_mean.shape[0] is 0:
return pd.DataFrame()
if 'num_sims' in param_mean.columns:
if len(exp_con_cols) > 0:
param_num_sims = param_mean.groupby(list(exp_con_co... | Python | nomic_cornstack_python_v1 |
comment retrieve connections for user having id=2 from database
import sqlite3
set conn = call connect string friends.sqlite
set cur = call cursor
execute cur string SELECT * FROM People
set count = 0 | # retrieve connections for user having id=2 from database
import sqlite3
conn=sqlite3.connect('friends.sqlite')
cur=conn.cursor()
cur.execute('SELECT * FROM People')
count=0 | Python | zaydzuhri_stack_edu_python |
function turn a biggest_pancake
begin
set top = 0
while top < biggest_pancake
begin
set aux = a at top
set a at top = a at biggest_pancake
set a at biggest_pancake = aux
set top = top + 1
set biggest_pancake = biggest_pancake - 1
end
end function
function biggest_pancake_id a size
begin
set id = 0
for i in range size
b... | def turn(a, biggest_pancake):
top = 0
while top < biggest_pancake:
aux = a[top]
a[top] = a[biggest_pancake]
a[biggest_pancake] = aux
top = top +1
biggest_pancake = biggest_pancake -1
def biggest_pancake_id(a, size):
id = 0
for i in range(size):
if a[i] > a[id]:
id = i
return id
def sorting(a):
... | Python | zaydzuhri_stack_edu_python |
function last_timestamp self
begin
return get pulumi self string last_timestamp
end function | def last_timestamp(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "last_timestamp") | Python | nomic_cornstack_python_v1 |
class Dog
begin
set kind = string canine
function __init__ self name
begin
set name = name
end function
end class
if __name__ == string __main__
begin
set d1 = call Dog string Jumpo
set d2 = call Dog string Tiger
comment Following are Instance variable
print name
print name
comment Following are Class variable
print ki... | class Dog:
kind = 'canine'
def __init__(self, name):
self.name = name
if __name__ == '__main__':
d1 = Dog('Jumpo')
d2 = Dog('Tiger')
# Following are Instance variable
print(d1.name)
print(d2.name)
# Following are Class variable
print(d1.kind)
print(d2.kind)
| Python | zaydzuhri_stack_edu_python |
async function async_setup_entry hass entry async_add_entities
begin
set config = data
set latitude = get config CONF_LATITUDE latitude
set longitude = get config CONF_LONGITUDE longitude
if none in tuple latitude longitude
begin
error string Latitude or longitude not set in Home Assistant config
return
end
set coordin... | async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
config = entry.data
latitude = config.get(CONF_LATITUDE, hass.config.latitude)
longitude = config.get(CONF_LONGITUDE, hass.config.longitude)
if None in (latitude, longitude):
... | Python | nomic_cornstack_python_v1 |
function GetDefaultPixelValue self
begin
return call itkResampleImageFilterIRGBAUC3IRGBAUC3_GetDefaultPixelValue self
end function | def GetDefaultPixelValue(self) -> "itkRGBAPixelUC const &":
return _itkResampleImageFilterPython.itkResampleImageFilterIRGBAUC3IRGBAUC3_GetDefaultPixelValue(self) | Python | nomic_cornstack_python_v1 |
function should_poll self
begin
return true
end function | def should_poll(self):
return True | Python | nomic_cornstack_python_v1 |
string Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal. Example 1: Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4 Output: True Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with equ... | """
Given an array of integers nums and a positive integer k, find whether it's possible to divide this array into k non-empty subsets whose sums are all equal.
Example 1:
Input: nums = [4, 3, 2, 3, 5, 2, 1], k = 4
Output: True
Explanation: It's possible to divide it into 4 subsets (5), (1, 4), (2,3), (2,3) with eq... | Python | zaydzuhri_stack_edu_python |
function plot_graph fd_data n=none
begin
set title = string Word Count Distribution of + string n + string -gram, for first 10 common words
plot fd_data
x label string Rank
y label string Word Count
if n is not none
begin
title plt title
end
else
begin
title plt string Zipfs Analysis - Word Count Distribution
end
show
... | def plot_graph(fd_data, n=None):
title = 'Word Count Distribution of ' + str(n) + '-gram, for first 10 common words'
plt.plot(fd_data)
plt.xlabel('Rank')
plt.ylabel('Word Count')
if n is not None:
plt.title(title)
else:
plt.title('Zipfs Analysis - Word Count Distribution'... | Python | nomic_cornstack_python_v1 |
function sec_svm
begin
return call CClassifierSecSVM
end function | def sec_svm():
return CClassifierSecSVM() | Python | nomic_cornstack_python_v1 |
function setup_environment version
begin
set ret_dict = dict
set project = project
if use_virtualenv
begin
set build_dir = join path call venv_path version=slug string build
if exists path build_dir
begin
info format LOG_TEMPLATE project=slug version=slug msg=string Removing existing build dir
remove tree build_dir
en... | def setup_environment(version):
ret_dict = {}
project = version.project
if project.use_virtualenv:
build_dir = os.path.join(project.venv_path(version=version.slug), 'build')
if os.path.exists(build_dir):
log.info(LOG_TEMPLATE.format(project=project.slug, version=version.slu... | Python | nomic_cornstack_python_v1 |
from xml.dom import minidom
from pprint import pprint
class AbodoFeed
begin
function __init__ self xml_file
begin
set feed = parse minidom xml_file
set properties = call get_properties
end function
function get_properties self
begin
set property_ids = call getElementsByTagName string PropertyID
set madison_pids = call ... | from xml.dom import minidom
from pprint import pprint
class AbodoFeed:
def __init__(self, xml_file):
self.feed = minidom.parse(xml_file)
self.properties = self.get_properties()
def get_properties(self):
property_ids = self.feed.getElementsByTagName('PropertyID')
madison_pids = ... | Python | zaydzuhri_stack_edu_python |
function test_create_visa_task2 self
begin
set test_tf = call TaskFactory test_trip2
assert equal length tasks 0
call create_visa_task
assert equal length tasks 1
set visa_task = tasks at 0
assert equal title string No Visa is needed for this country.
end function | def test_create_visa_task2(self):
self.test_tf = TaskFactory(self.test_trip2)
self.assertEqual(len(self.test_tf.tasks), 0)
self.test_tf.create_visa_task()
self.assertEqual(len(self.test_tf.tasks), 1)
visa_task = self.test_tf.tasks[0]
self.assertEqual(visa_task.title, ... | Python | nomic_cornstack_python_v1 |
function call_rolling_windows df pwdist_cutoff min_sweep_clade_size
begin
comment """
comment dist values may be nan if there are too many uncalled bases, but may also
comment be nan if there is no unmasked bases left after admixture masking. We only
comment want to call the 500kb (and the constituent 100kb windows) as... | def call_rolling_windows(df, pwdist_cutoff, min_sweep_clade_size):
# """
# dist values may be nan if there are too many uncalled bases, but may also
# be nan if there is no unmasked bases left after admixture masking. We only
# want to call the 500kb (and the constituent 100kb windows) as swept if all
... | Python | nomic_cornstack_python_v1 |
comment %% Create multiclass model
comment This script uses as an input the Chinese database and creates multiclasses database of 12 lead ECG for further rendering and
comment usage for deep nets.
comment %% Create united database from all data that I have
import matplotlib.pyplot as plt
import glob
import os
import sc... | #%% Create multiclass model
# This script uses as an input the Chinese database and creates multiclasses database of 12 lead ECG for further rendering and
#usage for deep nets.
# %% Create united database from all data that I have
import matplotlib.pyplot as plt
import glob
import os
import scipy.io as sio
import num... | Python | zaydzuhri_stack_edu_python |
for x in f
begin
append map list x
end
close f
set rows = length map
set cols = length map at 0 - 1
set x = 0
for y in range rows
begin
if map at y at x == string #
begin
set c = c + 1
end
set x = x + 3
if x >= cols
begin
set x = x % cols
end
end
comment 03.1
print c
set counters = list 0 c 0 0 0
set xs = list 0 0 0 0 ... | for x in f:
map.append(list(x))
f.close()
rows = len(map)
cols = len(map[0]) - 1
x = 0
for y in range(rows):
if map[y][x] == "#":
c += 1
x += 3
if x >= cols:
x = x % cols
print(c) # 03.1
counters = [0, c, 0, 0, 0]
xs = [0, 0, 0, 0, 0]
for y in range(rows):
if map[y][xs[0]] == "#":
... | Python | zaydzuhri_stack_edu_python |
string function to calculate max of a list Parameters ------------- a: list list needs to be longer than 0 and consist of ints or floats if len(a) == 0 or a[i] != int/float an error will occur Return ------------ max: int the maximum of the list a
function my_max a
begin
set max = 0
assert length a msg string list is 0... | """
function to calculate max of a list
Parameters
-------------
a: list
list needs to be longer than 0 and consist of ints or floats
if len(a) == 0 or a[i] != int/float an error will occur
Return
------------
max: int
the maximum of the list a
"""
def my_max(a):
max = 0
assert len(a), "list is 0... | Python | zaydzuhri_stack_edu_python |
function initialize self
begin
set posterior = ones tuple n_arms 2 dtype=int32
set means = zeros n_arms dtype=float64
end function | def initialize(self):
self.posterior = np.ones((self.n_arms, 2), dtype=np.int32)
self.means = np.zeros(self.n_arms, dtype=np.float64) | Python | nomic_cornstack_python_v1 |
function DoDropPane self panes target dock_direction dock_layer dock_row dock_pos
begin
set drop = call CopyTarget target
set panes = call DoInsertPane panes dock_direction dock_layer dock_row dock_pos
call Position dock_pos
return call ProcessDockResult target drop
end function | def DoDropPane(self, panes, target, dock_direction, dock_layer, dock_row, dock_pos):
drop = self.CopyTarget(target)
panes = DoInsertPane(panes, dock_direction, dock_layer, dock_row, dock_pos)
drop.Dock().Direction(dock_direction).Layer(dock_layer).Row(dock_row).Position(dock_pos)
... | Python | nomic_cornstack_python_v1 |
function list self
begin
return _elts
end function | def list(self):
return self._elts | Python | nomic_cornstack_python_v1 |
import abc
import enum
import numpy as np
from scipy.stats import binom , norm
class PricingEngine extends object
begin
decorator abstractmethod
function calculate self
begin
string A method to implement a pricing model. Called from Facade, passed through here. instantiated in the specific Pricing Engines. The pricing ... | import abc
import enum
import numpy as np
from scipy.stats import binom, norm
class PricingEngine(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def calculate(self):
"""A method to implement a pricing model. Called from Facade, passed through here. instantiated in the specific Pricing Engin... | Python | zaydzuhri_stack_edu_python |
string A function to sum two elements.
function my_sum a b
begin
string Calculate the sum of a and b. :param float a: The first element to sum. :param float b: The second element to sum. :return: The sum of a and b, :rtype: float.
if a == 2.0 and b == 2.0
begin
return 5.0
end
else
begin
return a + b
end
end function | """A function to sum two elements."""
def my_sum(a, b):
"""Calculate the sum of a and b.
:param float a: The first element to sum.
:param float b: The second element to sum.
:return: The sum of a and b,
:rtype: float.
"""
if a == 2. and b == 2.:
return 5.
else:
return ... | Python | zaydzuhri_stack_edu_python |
function _average_relevance_position_fn labels predictions weights
begin
return call average_relevance_position labels predictions weights=weights name=name
end function | def _average_relevance_position_fn(labels, predictions, weights):
return average_relevance_position(
labels, predictions, weights=weights, name=name) | Python | nomic_cornstack_python_v1 |
function calculate a b
begin
if b == 0
begin
raise ZeroDivisionError
end
else
if b > 0
begin
set c = a / b
return c
end
else
begin
raise ValueError
end
end function | def calculate(a, b):
if b == 0:
raise ZeroDivisionError
elif b > 0:
c = a / b
return c
else:
raise ValueError | Python | jtatman_500k |
import xlsx
set name = list list string meet 1 list string iti 2 list string mayur 3 list string poojan 4 list string tithi 5 list string anuj 6
print name at tuple slice : : 1 | import xlsx
name = [["meet", 1], ["iti", 2], ["mayur", 3], ["poojan", 4], ["tithi", 5], ["anuj", 6]]
print(name[:,1])
| Python | zaydzuhri_stack_edu_python |
comment Strong password detection.
import re
function checkingMethod
begin
print string Input a password,we'll check if it's strong enough. please make sure your password is at least eight characters long and contains at least one character for lowercase letter, uppercase letter and number separately.
set a_zPattern = ... | # Strong password detection.
import re
def checkingMethod():
print('''
Input a password,we'll check if it's strong enough.
please make sure your password is at least eight characters long
and contains at least one character for lowercase letter,
uppercase letter and number separately.
''')
... | Python | zaydzuhri_stack_edu_python |
function test_compare_blackrockio_with_matlabloader self
begin
comment Load data from Matlab generated files
set ml = call loadmat call get_local_path string blackrock/FileSpec2.3001.mat
comment (channel x time) LFP matrix
set lfp_ml = ml at string lfp
comment spike time stamps
set ts_ml = ml at string ts
comment spike... | def test_compare_blackrockio_with_matlabloader(self):
# Load data from Matlab generated files
ml = scipy.io.loadmat(self.get_local_path('blackrock/FileSpec2.3001.mat'))
lfp_ml = ml['lfp'] # (channel x time) LFP matrix
ts_ml = ml['ts'] # spike time stamps
elec_ml = ml['el'] #... | Python | nomic_cornstack_python_v1 |
while T
begin
set tuple _ c = split input
set total = sum map int split input
if total <= integer c
begin
print string Yes
end
else
begin
print string No
end
set T = T - 1
end | while T:
_, c = input().split()
total = sum(map(int, input().split()))
if total <= int(c):
print('Yes')
else:
print('No')
T -= 1
| Python | zaydzuhri_stack_edu_python |
import unittest
from administration import Administration
from employee import Employee , Person
from parameterized import parameterized
class TestAdministration extends TestCase
begin
decorator call expand list tuple string Guadalupe string Méndez 19 2615191849 40000 0 dict string name string Guadalupe ; string surnam... | import unittest
from administration import Administration
from employee import Employee, Person
from parameterized import parameterized
class TestAdministration(unittest.TestCase):
@parameterized.expand([
("Guadalupe", "Méndez", 19, 2615191849, 40000, 0, {"name":"Guadalupe", "surname":"Méndez", "age":19, "... | Python | zaydzuhri_stack_edu_python |
comment Leetcode -> Medium
comment Minimum Number of Operations to Move All Balls to Each Box
comment Input: boxes = "110"
comment Output: [1,1,3]
comment Explanation: The answer for each box is as follows:
comment 1) First box: you will have to move one ball from the second box to the first box in one operation.
comme... | # Leetcode -> Medium
# Minimum Number of Operations to Move All Balls to Each Box
# Input: boxes = "110"
# Output: [1,1,3]
# Explanation: The answer for each box is as follows:
# 1) First box: you will have to move one ball from the second box to the first box in one operation.
# 2) Second box: you will have to... | Python | zaydzuhri_stack_edu_python |
function goto_legal_license self
begin
return call click
end function | def goto_legal_license(self):
return self.legal_license.click() | Python | nomic_cornstack_python_v1 |
function restaurantSummary lda_imlementation vectorized_coded_revs column best_tops coded_reviews_df threshold
begin
set cat_array = transform lda_imlementation vectorized_coded_revs
set topic_array = list
for i in range n_topics
begin
set coded_reviews_df at string topic_ + string i = cat_array at tuple slice : : ... | def restaurantSummary(lda_imlementation, vectorized_coded_revs, column,
best_tops, coded_reviews_df, threshold):
cat_array = lda_imlementation.transform(vectorized_coded_revs)
topic_array = []
for i in range(lda_imlementation.n_topics):
coded_reviews_df['topic_'+str(i)] = cat_... | Python | nomic_cornstack_python_v1 |
import os
import shutil
import glob
function get_file_list rundir file_type
begin
set logdir = join path rundir string meta string logs
set file_pattern = join path logdir format string {}_* file_type
set file_list = sorted glob glob file_pattern
return file_list
end function
function concat_files infile_list outfile m... | import os
import shutil
import glob
def get_file_list(rundir, file_type):
logdir = os.path.join(rundir, 'meta', 'logs')
file_pattern = os.path.join(logdir, '{}_*'.format(file_type))
file_list = sorted(glob.glob(file_pattern))
return file_list
def concat_files(infile_list, outfile, mode='wb'):
wi... | Python | zaydzuhri_stack_edu_python |
comment Std
import os
comment Mine
import filesystem.files_aux as files_aux
import modelica_interface.run_omc as run_omc
from modelica_interface.compiled_model import CompiledModelicaModel
class ModelicaModelBuilder
begin
set mos_script_skeleton = string print("Loading Modelica"); loadModel(Modelica);getErrorString(); ... | # Std
import os
# Mine
import filesystem.files_aux as files_aux
import modelica_interface.run_omc as run_omc
from modelica_interface.compiled_model import CompiledModelicaModel
class ModelicaModelBuilder():
mos_script_skeleton = \
(
# This shouldn't be the responsibility of the builder, but for now we... | Python | zaydzuhri_stack_edu_python |
class Person
begin
string An example of class to hold person's name and age
comment Keeps a count of how many instances are created
set instance_count = 0
decorator classmethod
function increment_instance_count cls
begin
set instance_count = instance_count + 1
end function
function __init__ self name age
begin
set inst... | class Person:
"""An example of class to hold person's name and age"""
instance_count = 0 # Keeps a count of how many instances are created
@classmethod
def increment_instance_count(cls):
cls.instance_count += 1
def __init__(self, name, age):
Person.instance_count += 1
self... | Python | zaydzuhri_stack_edu_python |
set A = list comprehension 1 / x for x in range 1 11
print A
set B = list comprehension 2 ^ y for y in range 11
print B
set C = list comprehension x for x in B if x % 4 == 0
print C | A = [1/x for x in range(1, 11)]
print(A)
B = [2**y for y in range(11)]
print(B)
C = [x for x in B if x % 4 == 0]
print(C)
| Python | zaydzuhri_stack_edu_python |
function disable_hits self
begin
set hits = list call get_hits
set hit_ids = list comprehension HITId for hit in hits
call parallel_call disable_hit hit_ids
end function | def disable_hits(self):
hits = list(self.get_hits())
hit_ids = [hit.HITId for hit in hits]
parallel_call(self._mtc.disable_hit, hit_ids) | Python | nomic_cornstack_python_v1 |
string Leo는 카펫을 사러 갔다가 아래 그림과 같이 중앙에는 빨간색으로 칠해져 있고 테두리 1줄은 갈색으로 칠해져 있는 격자 모양 카펫을 봤습니다. image.png Leo는 집으로 돌아와서 아까 본 카펫의 빨간색과 갈색으로 색칠된 격자의 개수는 기억했지만, 전체 카펫의 크기는 기억하지 못했습니다. Leo가 본 카펫에서 갈색 격자의 수 brown, 빨간색 격자의 수 red가 매개변수로 주어질 때 카펫의 가로, 세로 크기를 순서대로 배열에 담아 return 하도록 solution 함수를 작성해주세요. 제한사항 갈색 격자의 수 brown은 8 이상 5,000 이하... | '''
Leo는 카펫을 사러 갔다가 아래 그림과 같이 중앙에는 빨간색으로 칠해져 있고
테두리 1줄은 갈색으로 칠해져 있는 격자 모양 카펫을 봤습니다.
image.png
Leo는 집으로 돌아와서 아까 본 카펫의 빨간색과 갈색으로 색칠된 격자의 개수는 기억했지만,
전체 카펫의 크기는 기억하지 못했습니다.
Leo가 본 카펫에서 갈색 격자의 수 brown, 빨간색 격자의 수 red가 매개변수로 주어질 때
카펫의 가로, 세로 크기를 순서대로 배열에 담아 return 하도록 solution 함수를 작성해주세요.
제한사항
갈색 격자의 수 brown은 8 이상 5,000... | Python | zaydzuhri_stack_edu_python |
function prime_numbers
begin
set primes = list 2
for num in range 3 101
begin
if all generator expression num % prime != 0 for prime in primes
begin
append primes num
end
end
print primes
end function
call prime_numbers | def prime_numbers():
primes = [2]
for num in range(3, 101):
if all(num % prime != 0 for prime in primes):
primes.append(num)
print(primes)
prime_numbers()
| Python | flytech_python_25k |
string python 沒有實際意義上的多行註解, 此為沒有被print或執行功能的字串
comment ASCII Code,用來檢查文字[a-z],[A-Z]
print ordinal string A
print ordinal string z
print ordinal string 9
print ordinal string 可
comment 預設sep為一個空格
print string Go string Home
print string Go string Home sep=string
set a = 10
set b = 3
print string %d除以%d得到%6.2f % tuple 10... | '''
python 沒有實際意義上的多行註解,
此為沒有被print或執行功能的字串
'''
print(ord('A')) #ASCII Code,用來檢查文字[a-z],[A-Z]
print(ord('z'))
print(ord('9'))
print(ord('可'))
print('Go','Home') #預設sep為一個空格
print('Go','Home', sep='')
a=10
b=3
print('%d除以%d得到%6.2f' %(10,3,10/3))
print('%d除以%d得到%.2f' %(a,b,a/b))
print('{}除以{}得到{:.2f}' .format(a,b,a/b... | Python | zaydzuhri_stack_edu_python |
function calculateArea r
begin
return 22 * r * r / 7
end function | def calculateArea(r):
return (22 * r * r)/7
| Python | zaydzuhri_stack_edu_python |
function test_entry_slug_collision2 self
begin
call super_user
set e1 = call create_entry blog1
set blog3 = call create keyword dict string title string b3 ; string slug string b3
set e2 = call create_entry blog2
set cat1 = call create_category blog1
add categories cat1
set cat2 = call create_category blog2
add categor... | def test_entry_slug_collision2(self):
self.super_user()
self.e1 = self.create_entry(self.blog1)
self.blog3 = Blog.objects.create(**{
'title': 'b3', 'slug': 'b3'})
self.e2 = self.create_entry(self.blog2)
self.cat1 = self.create_category(self.blog1)
self.e1.c... | Python | nomic_cornstack_python_v1 |
function problemOne self
begin
set hot_volt = call tolist
set pitot_vel = call tolist
comment Create interpolation function of FFT data for finding coefficients
set v_hot = call poly1d array cal_coeffs
comment Create string to print coefficients on plot
set print_coeffs = string Curve Coefficients:
set coeff_index = li... | def problemOne(self):
self.hot_volt = self.data['calibration']['hot volt'].tolist()
self.pitot_vel = self.data['calibration']['pitot vel'].tolist()
# Create interpolation function of FFT data for finding coefficients
self.v_hot = np.poly1d(np.array(self.cal_coeffs))
# Create stri... | Python | nomic_cornstack_python_v1 |
function run_all_experiments n_dimensions spinnaker=false runs_per_scale=30 runs_per_seed=1 filename=none use_spalloc=false
begin
comment Initialise the results as empty lists
set data = dict string n_dimensions list ; string seed list ; string times none ; string output list ; string magnitude list
if spinnaker
begin
... | def run_all_experiments(n_dimensions, spinnaker=False, runs_per_scale=30,
runs_per_seed=1, filename=None, use_spalloc=False):
# Initialise the results as empty lists
data = {"n_dimensions": list(),
"seed": list(),
"times": None,
"output": list(),
... | Python | nomic_cornstack_python_v1 |
import socket
import base64
import hashlib
class Frame
begin
set seq = b''
set data = b''
set checksum = b''
function __init__ self sequen dataFrame
begin
print dataFrame
set seq = bytes string sequen string utf-8
set data = bytes dataFrame string utf-8
set checksum = bytes hex digest md5 seq + data string utf-8
end fu... | import socket
import base64
import hashlib
class Frame:
seq = b''
data = b''
checksum = b''
def __init__(self, sequen, dataFrame):
print(dataFrame)
self.seq = bytes(str(sequen), 'utf-8')
self.data = bytes(dataFrame, 'utf-8')
self.checksum = bytes(hashlib.md5(self.seq+se... | Python | zaydzuhri_stack_edu_python |
function keys self
begin
return get pulumi self string keys
end function | def keys(self) -> Optional[Sequence['outputs.ObjectTypeKeyMap']]:
return pulumi.get(self, "keys") | Python | nomic_cornstack_python_v1 |
function front_back a b
begin
set a_split = length a // 2 + length a % 2
set b_split = length b // 2 + length b % 2
return a at slice : a_split : + b at slice : b_split : + a at slice a_split : : + b at slice b_split : :
end function | def front_back(a, b):
a_split = (len(a) // 2) + (len(a) % 2)
b_split = (len(b) // 2) + (len(b) % 2)
return a[:a_split] + b[:b_split] + a[a_split:] + b[b_split:] | Python | nomic_cornstack_python_v1 |
function get_data self save_data=false data_filter=none redownload=false max_threads=none raise_download_errors=true
begin
string Get requested data either by downloading it or by reading it from the disk (if it was previously downloaded and saved). :param save_data: flag to turn on/off saving of data to disk. Default ... | def get_data(self, *, save_data=False, data_filter=None, redownload=False, max_threads=None,
raise_download_errors=True):
"""
Get requested data either by downloading it or by reading it from the disk (if it
was previously downloaded and saved).
:param save_data: flag t... | Python | jtatman_500k |
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
set mail_content = string Hello world Simple email Thank You
set sender_address = string youremail
set sender_pass = string yourpassword
set receiver_address = string receipient
set message = call MIMEMultipart
set messag... | import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_content = '''
Hello world
Simple email
Thank You
'''
sender_address = 'youremail'
sender_pass = 'yourpassword'
receiver_address = 'receipient'
message = MIMEMultipart()
message['From'] = sender_address... | Python | zaydzuhri_stack_edu_python |
function list_to_csv_str input_list
begin
return call list_to_str input_list
end function | def list_to_csv_str(input_list: list) -> str:
return list_to_str(input_list) | Python | nomic_cornstack_python_v1 |
import random
import requests
from spellcheck import spellcheck
import re
import json
from pprint import pprint
import nltk
from nltk.corpus import wordnet as wn
from nltk.stem.porter import PorterStemmer
from nltk.stem import WordNetLemmatizer
from config import *
with open string knowledge_ontologies/OntologyToLemmas... | import random
import requests
from .spellcheck import spellcheck
import re
import json
from pprint import pprint
import nltk
from nltk.corpus import wordnet as wn
from nltk.stem.porter import PorterStemmer
from nltk.stem import WordNetLemmatizer
from .config import *
with open('knowledge_ontologies/OntologyToLemmas.... | Python | zaydzuhri_stack_edu_python |
function __init__ self vmax=none clip=false
begin
set vmax = vmax
set clip = clip
end function | def __init__(self, vmax=None, clip=False):
self.vmax = vmax
self.clip = clip | Python | nomic_cornstack_python_v1 |
import numpy as np
from dohvr import dohvr
from plothv import plothv
from tictoc import tic , toc
comment Parametros Programa
comment Lineas saltadas del archivo
set skip = 1
comment Ruta del archivo saf
set camino = string C:\Users\ccrem\Desktop\New folder (2)\Valparaiso\Valparaiso2010.saf
comment frecuencia de muestr... | import numpy as np
from dohvr import dohvr
from plothv import plothv
from tictoc import tic,toc
#####Parametros Programa
skip = 1# Lineas saltadas del archivo
camino = r'C:\Users\ccrem\Desktop\New folder (2)\Valparaiso\Valparaiso2010.saf'# Ruta del archivo saf
fmm = 200. #frecuencia de muestreo en Hz
TT = 10.0 #tiempo... | Python | zaydzuhri_stack_edu_python |
from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression , Ridge
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np
import matplotlib.pyplot as plt
import warnings
set boston = call load_boston
comment description of d... | from sklearn.datasets import load_boston
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import numpy as np
import matplotlib.pyplot as plt
import warnings
boston = load_boston()
# description of dataset
# prin... | Python | zaydzuhri_stack_edu_python |
from pandas import DataFrame , concat
from numpy import rot90
import subprocess
import os
import cv2
import sys
if __name__ == string __main__
begin
print string ------------------------------------------
print string ------------------------------------------
try
begin
set video_file_name = argv at 1
set video_name = ... | from pandas import DataFrame, concat
from numpy import rot90
import subprocess
import os
import cv2
import sys
if __name__ == "__main__":
print('------------------------------------------')
print('------------------------------------------')
try:
video_file_name = sys.argv[1]
video_name = o... | Python | zaydzuhri_stack_edu_python |
import json
import numpy as np
from log import *
function save_model saver sess
begin
set save_dir = log_dir + string /saved/
save sess save_dir + string model.ckpt
end function
function save_embs sess model train_x test_x train_y test_y train_names test_names
begin
set all_songs = concatenate list train_x test_x axis=... | import json
import numpy as np
from log import *
def save_model(saver, sess):
save_dir = log_dir + '/saved/'
saver.save(sess, save_dir+'model.ckpt')
def save_embs(sess, model, train_x, test_x, train_y, test_y, train_names, test_names):
all_songs = np.concatenate([train_x, test_x], axis=0)
all_labels... | Python | zaydzuhri_stack_edu_python |
function update self tier1_id segment_id port_id segment_port
begin
return call _invoke string update dict string tier1_id tier1_id ; string segment_id segment_id ; string port_id port_id ; string segment_port segment_port
end function | def update(self,
tier1_id,
segment_id,
port_id,
segment_port,
):
return self._invoke('update',
{
'tier1_id': tier1_id,
'segment_id': segment_id,
... | Python | nomic_cornstack_python_v1 |
function other_property_type self
begin
return none
end function | def other_property_type(self) -> RecordType:
return None | Python | nomic_cornstack_python_v1 |
function unique self list
begin
set seen = dict
set result = list
for item in list
begin
if item in seen
begin
continue
end
set seen at item = 1
append result item
end
return result
end function | def unique(self, list):
seen = {}
result = []
for item in list:
if item in seen: continue
seen[item] = 1
result.append(item)
return result | Python | nomic_cornstack_python_v1 |
import random
function main
begin
set secretNum = random integer 0 9
set guessedIt = false
print string I'm thinking of a number from 0 to 9. You have unlimited guesses!
set guesses = 0
while not guessedIt
begin
print string Guess + string guesses + 1
set guess = integer input string -- Input a number (0 - 9):
if guess... | import random
def main():
secretNum = random.randint(0, 9)
guessedIt = False
print("I'm thinking of a number from 0 to 9. You have unlimited guesses!")
guesses = 0
while not guessedIt:
print("Guess " + str(guesses + 1))
guess = int(input("-- Input a number (0 - 9): "))
if g... | Python | zaydzuhri_stack_edu_python |
from antlr4.ParserRuleContext import ParserRuleContext
from antlr4.Token import Token , CommonToken
import AutoQcmParser
class Location extends object
begin
function __init__ self ctx
begin
set firstToken = start
comment self.filename = self.firstToken.getTokenSource().getSourceName()
set line = line
set column = colum... | from antlr4.ParserRuleContext import ParserRuleContext
from antlr4.Token import Token, CommonToken
import AutoQcmParser
class Location(object):
def __init__(self, ctx:ParserRuleContext):
self.firstToken = ctx.start
#self.filename = self.firstToken.getTokenSource().getSourceName()
self.... | 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.