code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function sort_version_aware versions
begin
from distutils2.version import NormalizedVersion
from projects.utils import mkversion
set fallback = call NormalizedVersion string 99999999.0 error_on_huge_major_num=false
return sorted versions key=lambda v -> call mkversion v or fallback reverse=true
end function | def sort_version_aware(versions):
from distutils2.version import NormalizedVersion
from projects.utils import mkversion
fallback = NormalizedVersion('99999999.0', error_on_huge_major_num=False)
return sorted(versions,
key=lambda v: (mkversion(v) or fallback),
re... | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
from matplotlib.font_manager import FontProperties
set FONTSTYLE = string serif
set FONTSIZE = 12
set hfont = dict string family FONTSTYLE ; string fontsize FONTSIZE
set fontP = call FontProperties
call set_family FONTSTYLE
call set_size string small
function get_halogen_spectra r... | import numpy as np
import pandas as pd
from matplotlib.font_manager import FontProperties
FONTSTYLE = 'serif'
FONTSIZE = 12
hfont = {'family':FONTSTYLE, 'fontsize': FONTSIZE}
fontP = FontProperties()
fontP.set_family(FONTSTYLE)
fontP.set_size('small')
def get_halogen_spectra(reference_file):
d = np.genfromtxt(r... | Python | zaydzuhri_stack_edu_python |
for i in range 1 T + 1
begin
set tuple R k N = list comprehension integer x for x in split call raw_input
set l = list comprehension integer x for x in split call raw_input
set Q = l
set boarded = list
set money = 0
for j in range 0 R
begin
comment print 'Q: ', Q
for x in Q
begin
if sum boarded + list x <= k
begin
app... | for i in range(1,T+1):
R, k, N = [ int(x) for x in raw_input().split() ]
l = [ int(x) for x in raw_input().split() ]
Q = l
boarded = []
money = 0
for j in range(0, R):
# print 'Q: ', Q
for x in Q:
if sum(boarded + [x]) <= k:
boarded.append(x)
... | Python | zaydzuhri_stack_edu_python |
function test_render_json self
begin
set response = call get_response string /r_json
assert equal 200 status_int
call assertDictEqual dict string rendered_as string json loads body
end function | def test_render_json(self):
response = wsgi.get_response('/r_json')
self.assertEqual(200, response.status_int)
self.assertDictEqual({'rendered_as': 'json'}, json.loads(response.body)) | Python | nomic_cornstack_python_v1 |
comment Definition for singly-linked list.
class ListNode
begin
function __init__ self x
begin
set val = x
set next = none
end function
end class
class Solution
begin
function detectCycle self head
begin
set save = dict
set save at head = 1
while head
begin
set next = next
if next
begin
if get save next
begin
return t... | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
save = {}
save[head] = 1
while head:
next = head.next
if next:
... | Python | zaydzuhri_stack_edu_python |
import time
import random
import sys
for x in range 5
begin
if x >= 1
begin
print string end=string
end
for x in range 25
begin
set this = random integer 0 1
print this end=string
flush stdout
sleep 0.0005
end
end
print string end=string | import time
import random
import sys
for x in range(5):
if x >= 1: print("\n", end='')
for x in range(25):
this = random.randint(0,1)
print(this, end='')
sys.stdout.flush()
time.sleep(.0005)
print("\n", end='')
| Python | zaydzuhri_stack_edu_python |
function _add_services self
begin
comment Services and relations which are present merely to satisfy
comment required_interfaces and workload status are not inspected.
comment Fix me. Inspect those too.
set this_service = dict string name string neutron-openvswitch
set other_services = list dict string name string nova... | def _add_services(self):
# Services and relations which are present merely to satisfy
# required_interfaces and workload status are not inspected.
# Fix me. Inspect those too.
this_service = {'name': 'neutron-openvswitch'}
other_services = [
{'name': 'nova-compute'},
... | Python | nomic_cornstack_python_v1 |
function GetUserBalances self plebs_only=false
begin
set user_balances = call GetSubkey _BALANCE_SUBKEY
comment pylint: disable=g-complex-comprehension
return dictionary comprehension user_id : call SafeCast balance int 0 for tuple user_id balance in user_balances if not plebs_only or user_id not in HYPECENTS and not s... | def GetUserBalances(self, plebs_only=False):
user_balances = self._store.GetSubkey(self._BALANCE_SUBKEY)
# pylint: disable=g-complex-comprehension
return {
user_id: util_lib.SafeCast(balance, int, 0)
for user_id, balance in user_balances
if (not plebs_only or user_id not in HYPECENTS... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
import logging
from path_helpers import path
import gst
import pandas as pd
import platform
if call system == string Linux
begin
set VIDEO_SOURCE_PLUGIN = string v4l2src
set DEVICE_KEY = string device
end
else
begin
set VIDEO_SOURCE_PLUGIN = string dshowvideosrc
set DEVICE_KEY = string device-name... | # coding: utf-8
import logging
from path_helpers import path
import gst
import pandas as pd
import platform
if platform.system() == 'Linux':
VIDEO_SOURCE_PLUGIN = 'v4l2src'
DEVICE_KEY = 'device'
else:
VIDEO_SOURCE_PLUGIN = 'dshowvideosrc'
DEVICE_KEY = 'device-name'
class DeviceNotFound(Exception):
... | Python | zaydzuhri_stack_edu_python |
function gen_query query
begin
set query_string = string /?
if string categories in query
begin
set query_string = query_string + string categories= + join string , query at string categories
set query_string = query_string + string &
end
set query_string = query_string + join string & list comprehension x + string = +... | def gen_query(query):
query_string = '/?'
if 'categories' in query:
query_string += 'categories=' + ','.join(query['categories'])
query_string += '&'
query_string += '&'.join([x + '=' + query[x][0] for x in query if query[x][0]!='' and x!='categories' and x!='submit_flag'])
query_string ... | Python | nomic_cornstack_python_v1 |
function sort_brackets self start end match_type bracket_id
begin
if if expression match_type then end <= center else start < center
begin
comment Sort bracket to left
append left at match_type call BracketEntry start end bracket_id
end
else
if if expression match_type then end > center else start >= center
begin
comme... | def sort_brackets(self, start, end, match_type, bracket_id):
if (end <= self.center if match_type else start < self.center):
# Sort bracket to left
self.left[match_type].append(BracketEntry(start, end, bracket_id))
elif (end > self.center if match_type else start >= self.center)... | Python | nomic_cornstack_python_v1 |
import random as ran
set ix = call randrange 1 101
set iy = call randrange 1 101
print ix
print iy
set loop = max ix iy
set gcd = list
for i in range 1 loop
begin
if ix % i == 0 and iy % i == 0
begin
append gcd i
end
else
if ix % i != 0 and iy % i != 0
begin
continue
end
end
print max gcd | import random as ran
ix = ran.randrange(1,101)
iy = ran.randrange(1,101)
print(ix)
print(iy)
loop = max(ix,iy)
gcd = []
for i in range(1, loop):
if ix%i == 0 and iy%i == 0:
gcd.append(i)
elif ix%i != 0 and iy%i != 0:
continue
print(max(gcd)) | Python | zaydzuhri_stack_edu_python |
function _model_default self
begin
return call NamingTreeModel
end function | def _model_default(self):
return NamingTreeModel() | Python | nomic_cornstack_python_v1 |
import environ
from users.models import User
set env = call Env DEBUG=tuple bool false DEFAULT_SU_LOGIN=tuple str string admin DEFAULT_SU_PASS=tuple str string admin DEFAULT_SU_EMAIL=tuple str string admin@admin.admin
comment set casting, default value
comment Reading .env file
comment Environment file is situated four... | import environ
from users.models import User
env = environ.Env(
# set casting, default value
DEBUG=(bool, False),
DEFAULT_SU_LOGIN=(str, 'admin'),
DEFAULT_SU_PASS=(str, 'admin'),
DEFAULT_SU_EMAIL=(str, 'admin@admin.admin')
)
# Reading .env file
base = environ.Path(__file__) - 4 # Environment fil... | Python | zaydzuhri_stack_edu_python |
function _load_modules self
begin
set modules = list
set agent_cls_list = call get_all_modules DashboardAgentModule
for cls in agent_cls_list
begin
info string Loading %s: %s __name__ cls
set c = call cls self
append modules c
end
info string Loaded %d modules. length modules
return modules
end function | def _load_modules(self):
modules = []
agent_cls_list = dashboard_utils.get_all_modules(
dashboard_utils.DashboardAgentModule
)
for cls in agent_cls_list:
logger.info(
"Loading %s: %s", dashboard_utils.DashboardAgentModule.__name__, cls
... | Python | nomic_cornstack_python_v1 |
if table_order > 8
begin
print string Sorry, but no places for you, you need to wait for sometime!
end
else
begin
print string You table is ready! Please come in!
end | if table_order > 8:
print("Sorry, but no places for you, you need to wait for sometime!")
else:
print("You table is ready! Please come in!") | Python | zaydzuhri_stack_edu_python |
import sys
import importlib
call reload sys
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager , PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal , LAParams
from pdfmin... | import sys
import importlib
importlib.reload(sys)
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParam... | Python | zaydzuhri_stack_edu_python |
comment Data types in python
comment Immutables (numbers, strings, tuples, frozensets)
comment None of the object types in the immutable category support in-place changes,
comment though we can always run expressions to make new objects and assign their results
comment to variables as needed.
comment Mutables (lists, d... | ## Data types in python
#Immutables (numbers, strings, tuples, frozensets)
#None of the object types in the immutable category support in-place changes,
#though we can always run expressions to make new objects and assign their results
#to variables as needed.
#Mutables (lists, dictionaries, sets)
#Conversely, the mut... | Python | zaydzuhri_stack_edu_python |
function delete_edge self node
begin
set index = call lookup node
delete index
end function | def delete_edge(self, node):
index = self.edges.lookup(node)
self.edges.delete(index) | Python | nomic_cornstack_python_v1 |
function _commands_to_set_connection_after_login self line
begin
if call _cmds_after_establish_connection_needed
begin
call _change_telnet_to_setting_commands
return true
end
return false
end function | def _commands_to_set_connection_after_login(self, line):
if self._cmds_after_establish_connection_needed():
self._change_telnet_to_setting_commands()
return True
return False | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import zipfile
import StringIO
import requests
set __author__ = string f0x11
function get_challenge url
begin
return content
end function
set z = zip file call StringIO call get_challenge string channel.zip
set index = string 90052
set z_list = list | # -*- coding: utf-8 -*-
import zipfile
import StringIO
import requests
__author__ = 'f0x11'
def get_challenge(url):
return requests.get("http://www.pythonchallenge.com/pc/def/" + url).content
z = zipfile.ZipFile(StringIO.StringIO(get_challenge('channel.zip')))
index = "90052"
z_list = [] | Python | zaydzuhri_stack_edu_python |
import yaml
from configparser import ConfigParser
class ReadFileData
begin
function __init__ self
begin
pass
end function
decorator staticmethod
function load_yaml file_path
begin
with open file_path encoding=string utf-8 as f
begin
set data = call safe_load f
end
return data
end function
decorator staticmethod
functio... | import yaml
from configparser import ConfigParser
class ReadFileData:
def __init__(self):
pass
@staticmethod
def load_yaml(file_path):
with open(file_path, encoding='utf-8') as f:
data = yaml.safe_load(f)
return data
@staticmethod
def load_ini(file_path):
... | Python | zaydzuhri_stack_edu_python |
function to_ole_le self
begin
set ts_type = ts_types at string ole_le
try
begin
set dt_obj = parse duparser timestamp
if has attribute tzinfo string _offset
begin
set dt_tz = call total_seconds
set dt_obj = parse duparser timestamp ignoretz=true
end
else
begin
set dt_tz = 0
end
set delta = call total_seconds - integer ... | def to_ole_le(self):
ts_type = self.ts_types['ole_le']
try:
dt_obj = duparser.parse(self.timestamp)
if hasattr(dt_obj.tzinfo, '_offset'):
dt_tz = dt_obj.tzinfo._offset.total_seconds()
dt_obj = duparser.parse(self.timestamp, ignoretz=True)
... | Python | nomic_cornstack_python_v1 |
function truthy self context
begin
raise call NotImplementedException string Cannot evaluate truthness on abstract Entity
return false
end function | def truthy(self, context: Dict[str, "Entity"]) -> bool:
raise NotImplementedException(
"Cannot evaluate truthness on abstract Entity")
return False | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import random
function build_normal_matrix m n
begin
seed 200
set A = call normal 0 1 tuple m n
comment A = np.random.uniform(0,1000,(m,n))
comment A每个行向量求向量的2范数即aj
set A_norm = norm A axis=1 ord=2
return tuple A reshape array A_norm m 1
e... | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import random
def build_normal_matrix(m,n):
np.random.seed(200)
A = np.random.normal(0, 1, (m,n))
#A = np.random.uniform(0,1000,(m,n))
A_norm = np.linalg.norm(A, axis=1, ord=2)#A每个行向量求向量的2范数即aj
return A, np.array(A_n... | Python | zaydzuhri_stack_edu_python |
function square num
begin
set bit_length = call bit_length
if bit_length % 2 == 0
begin
return 1 ? bit_length // 2
end
else
begin
return 1 ? bit_length + 1 // 2 - 1
end
end function
comment Output: 25
print call square 5
comment Output: 49
print call square 7
comment Output: 100
print call square 10 | def square(num):
bit_length = num.bit_length()
if bit_length % 2 == 0:
return 1 << (bit_length // 2)
else:
return 1 << ((bit_length + 1) // 2 - 1)
print(square(5)) # Output: 25
print(square(7)) # Output: 49
print(square(10)) # Output: 100
| Python | jtatman_500k |
for i in range 2 12 2
begin
print i
end
print string Googbye! | for i in range(2,12,2):
print (i)
print("Googbye!")
| Python | zaydzuhri_stack_edu_python |
class TreeNode
begin
function __init__ self val=0 left=none right=none
begin
set val = val
set left = left
set right = right
end function
end class
function is_binary_search_tree root
begin
function helper node lower=decimal string -inf upper=decimal string inf
begin
if not node
begin
return true
end
set val = val
if v... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def is_binary_search_tree(root):
def helper(node, lower=float('-inf'), upper=float('inf')):
if not node:
return True
val = node.val
if... | Python | jtatman_500k |
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
function f n k beta
begin
return k * n ^ beta
end function
if __name__ == string __main__
begin
comment Total words of each index
set N = list
comment Different words of each index
set D = list
set indexes = list string words.txt ... | import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
def f(n, k, beta):
return k*(n**beta);
if __name__ == '__main__':
N = [] # Total words of each index
D = [] # Different words of each index
indexes = ["words.txt", "words2.txt", "words3.txt", "words4.txt", "word... | Python | zaydzuhri_stack_edu_python |
from flask import Flask
from flask import render_template
from math import sqrt
from matplotlib import pyplot
import pandas as pd
import datetime
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Sequential , save_mo... | from flask import Flask
from flask import render_template
from math import sqrt
from matplotlib import pyplot
import pandas as pd
import datetime
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from tensorflow.keras.models import Sequential,... | Python | zaydzuhri_stack_edu_python |
function PatternCount text pattern
begin
set count = 0
for i in range 0 length text - length pattern + 1
begin
if text at slice i : i + length pattern : == pattern
begin
set count = count + 1
end
end
return count
end function | def PatternCount(text, pattern):
count = 0
for i in range(0, len(text)-len(pattern)+1):
if text[i:i+len(pattern)] == pattern:
count += 1
return count | Python | nomic_cornstack_python_v1 |
function __init__ self n_in n_out activation_func=sigmoid p_dropout=0.0
begin
set n_in = n_in
set n_out = n_out
set activation_func = activation_func
set p_dropout = p_dropout
comment Initialize the weights and biases
set w = call shared call asarray call normal loc=0.0 scale=square root 1.0 / n_out size=tuple n_in n_o... | def __init__(self, n_in, n_out, activation_func=sigmoid, p_dropout=0.0):
self.n_in = n_in
self.n_out = n_out
self.activation_func = activation_func
self.p_dropout = p_dropout
# Initialize the weights and biases
self.w = theano.shared(
np.asarray(
... | Python | nomic_cornstack_python_v1 |
comment create LargePersonGroup Person
import httplib , urllib , base64 , json
set headers = dict string Content-Type string application/json ; string Ocp-Apim-Subscription-Key string 135e49f7f9d24a2c808613544fd8ca3e
comment Request headers
set params = url encode dict string largePersonGroupId string lpgi
set data = d... | #create LargePersonGroup Person
import httplib, urllib, base64, json
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '135e49f7f9d24a2c808613544fd8ca3e',
}
params = urllib.urlencode({"largePersonGroupId": str(lpgi)})
data = {
'name': raw_input("Please en... | Python | zaydzuhri_stack_edu_python |
string Flair ORM model for the 'flair' table in the SaintsXCTF MySQL database. Author: Andrew Jarombek Date: 6/21/2019
from sqlalchemy import Column
from app import db
class Flair extends Model
begin
function __init__ self flair
begin
string Initialize a Flair object by passing in a dictionary. :param flair: A dictiona... | """
Flair ORM model for the 'flair' table in the SaintsXCTF MySQL database.
Author: Andrew Jarombek
Date: 6/21/2019
"""
from sqlalchemy import Column
from app import db
class Flair(db.Model):
def __init__(self, flair: dict) -> None:
"""
Initialize a Flair object by passing in a dictionary.
... | Python | zaydzuhri_stack_edu_python |
function spacy2Document spacy_output
begin
set d = call LingData
call setNLPID string spacy
comment generate the flat list of tokens in the document
for token in spacy_output
begin
set t = call toLingDataToken token
call addToken t
end
set fromTok = 0
for sentence in sents
begin
set s = call Sentence
comment set to tok... | def spacy2Document(spacy_output):
d = LingData()
d.setNLPID("spacy")
# generate the flat list of tokens in the document
for token in spacy_output:
t = toLingDataToken(token)
d.addToken(t)
fromTok = 0
for sentence in spacy_output.sents:
s = Sentence()
# set to t... | Python | nomic_cornstack_python_v1 |
from prompt_toolkit.widgets import Frame , TextArea , Label , Box
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.layout.controls import BufferControl , FormattedTextControl
from prompt_toolkit.key_binding import KeyBindings
from typing import ... | from prompt_toolkit.widgets import Frame,TextArea,Label,Box
from prompt_toolkit.buffer import Buffer
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.layout.controls import BufferControl, FormattedTextControl
from prompt_toolkit.key_binding import KeyBindings
from typing import Callabl... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
class Computer
begin
function __init__ self instructions_text
begin
set instructions = list comprehension call parse_instruction line for line in instructions_text
end function
function parse_instruction self instruction_text
begin
set tokens = split instruction_text string
return list tok... | #!/usr/bin/env python3
class Computer:
def __init__(self, instructions_text):
self.instructions = [self.parse_instruction(line) for line in instructions_text]
def parse_instruction(self, instruction_text):
tokens = instruction_text.split(" ")
return [tokens[0], int(tokens[1])]
de... | Python | zaydzuhri_stack_edu_python |
function disassembly_text self
begin
return call get_disassembly_text
end function | def disassembly_text(self):
return self.get_disassembly_text() | Python | nomic_cornstack_python_v1 |
import random
comment функция красиво распечатает матрицу
function pretty_print mas
begin
comment 10 раз тире
print string - * 10
comment оператор '*' делает распаковку списка, без запятых и квадратных скобок
list comprehension print *row for row in mas
comment 10 раз тире
print string - * 10
end function
comment функц... | import random
# функция красиво распечатает матрицу
def pretty_print(mas):
print('-' * 10) # 10 раз тире
[print(*row) for row in mas] # оператор '*' делает распаковку списка, без запятых и квадратных скобок
print('-' * 10) # 10 раз тире
# функция по номеру строки и столбца вернет порядковый номер ячейки от 1 до ... | Python | zaydzuhri_stack_edu_python |
function conditions self conditions
begin
if conditions is none
begin
comment noqa: E501
raise call ValueError string Invalid value for `conditions`, must not be `None`
end
set _conditions = conditions
end function | def conditions(self, conditions):
if conditions is None:
raise ValueError("Invalid value for `conditions`, must not be `None`") # noqa: E501
self._conditions = conditions | Python | nomic_cornstack_python_v1 |
import json
from django.contrib.auth.models import User
from django.urls import include , path
from rest_framework.test import APIClient , APITestCase , URLPatternsTestCase
class UserRegistrationAPITestCase extends APITestCase
begin
function setUp self
begin
set client = call APIClient
end function
function test_regist... | import json
from django.contrib.auth.models import User
from django.urls import include, path
from rest_framework.test import APIClient, APITestCase, URLPatternsTestCase
class UserRegistrationAPITestCase(APITestCase):
def setUp(self):
self.client = APIClient()
def test_registration(self):
reg... | Python | zaydzuhri_stack_edu_python |
comment АРГУМЕНТЫ ФУНКЦИИ #
function div9_2
begin
return 9 / 2
end function
function div_num val_1 val_2
begin
return val_1 / val_2
end function
comment ПОЗИЦИОННЫЕ/ИМЕНОВАННЫЕ #
comment позиционные
print call div_num 10 2
comment именованные
print call div_num val_1=10 val_2=2
comment именованные
print call div_num va... | #####################
# АРГУМЕНТЫ ФУНКЦИИ #
#####################
def div9_2():
return 9 / 2
def div_num(val_1, val_2):
return val_1 / val_2
###########################
# ПОЗИЦИОННЫЕ/ИМЕНОВАННЫЕ #
###########################
print(div_num(10, 2)) # позиционные
print(div_num(val_1=10, val_2=2)) # именованн... | Python | zaydzuhri_stack_edu_python |
function size self
begin
Ellipsis
end function | def size(self) -> int:
... | Python | nomic_cornstack_python_v1 |
function inline self
begin
return get pulumi self string inline
end function | def inline(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[str]]]]:
return pulumi.get(self, "inline") | Python | nomic_cornstack_python_v1 |
function create_file self path content executable=false
begin
set path = format string {}/{} _infrastructure_repository path
with open path string w as f
begin
write f content
end
if executable is true
begin
set mode = st_mode
comment copy R bits to X
set mode = mode ? mode ? 292 ? 2
call chmod path mode
end
end functi... | def create_file(self, path, content, executable=False):
path = "{}/{}".format(self._infrastructure_repository, path)
with open(path, 'w') as f:
f.write(content)
if executable is True:
mode = os.stat(path).st_mode
mode |= (mode & 0o444) >> 2 # copy R bits t... | Python | nomic_cornstack_python_v1 |
function __init__ self target_func num_cores=none
begin
if num_cores is none
begin
set num_cores = cpu count
end
set total_jobs = 0
set jobs = call JoinableQueue
set results = queue
set tup = tuple jobs results
set num_cores = num_cores
set p = list comprehension process target=target_func args=tup for i in range num_c... | def __init__(self, target_func, num_cores=None):
if num_cores is None:
num_cores = mp.cpu_count()
self.total_jobs = 0
self.jobs = mp.JoinableQueue()
self.results = mp.Queue()
tup = (self.jobs, self.results)
self.num_cores = num_cores
self.p = [mp.Pro... | Python | nomic_cornstack_python_v1 |
function fit self Z
begin
string Learn empirical variances from X. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) Sample vectors from which to compute variances. y : any Ignored. This parameter exists only for compatibility with sklearn.pipeline.Pipeline. Returns ------- self
set X... | def fit(self, Z):
"""Learn empirical variances from X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Sample vectors from which to compute variances.
y : any
Ignored. This parameter exists only for compatibility with... | Python | jtatman_500k |
import pandas as pd
import numpy as np
import utils as utils
from Decision_Tree import DecisionTree
import Decision_Stump as ds
import time as time
from multiprocessing import Pool , cpu_count
from functools import partial
function tree X y i
begin
set model = call DecisionTree max_depth=i stump_class=DecisionStumpErro... | import pandas as pd
import numpy as np
import utils as utils
from Decision_Tree import DecisionTree
import Decision_Stump as ds
import time as time
from multiprocessing import Pool, cpu_count
from functools import partial
def tree(X,y,i):
model = DecisionTree(max_depth=i, stump_class=ds.DecisionStumpErrorRate)
... | Python | zaydzuhri_stack_edu_python |
from threading import Thread
from network.network_ctrl import NetworkCtrl
from server.router import Router
from log.logger import Logger
class RouterInfo
begin
string The RouterInfo collects in a new Thread informations about the Routers
decorator staticmethod
function update router
begin
string Starts a thread for a r... | from threading import Thread
from network.network_ctrl import NetworkCtrl
from server.router import Router
from log.logger import Logger
class RouterInfo:
"""
The RouterInfo collects in a new Thread informations about the Routers
"""
@staticmethod
def update(router: Router):
"""
S... | Python | zaydzuhri_stack_edu_python |
function functions_with_args self
begin
return pkg_dict at string functions
end function | def functions_with_args(self) -> Dict[str, Dict[str, Any]]:
return self.pkg_dict["functions"] | Python | nomic_cornstack_python_v1 |
function get_default_cfg_directory self
begin
set user_directory = expand user path string ~
return call create_directory join path user_directory DEFAULT_CONFIG_DIR
end function | def get_default_cfg_directory(self):
user_directory = os.path.expanduser('~')
return create_directory(
os.path.join(user_directory, DEFAULT_CONFIG_DIR)) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string Script that lists all states from the database hbtn_0e_0_usa Arguments received: MySQL username, MySQL password, database name
if __name__ == string __main__
begin
import MySQLdb
import sys
set args = argv
set username = args at 1
set password = args at 2
set db_name = args at 3
set db ... | #!/usr/bin/python3
"""Script that lists all states from the database hbtn_0e_0_usa
Arguments received:
MySQL username, MySQL password, database name
"""
if __name__ == "__main__":
import MySQLdb
import sys
args = sys.argv
username = args[1]
password = args[2]
db_name = args[3]
db = MyS... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function maxProfit self prices
begin
set sum = 0
set is_buy = false
for tuple i v in enumerate prices at slice : - 1 :
begin
if v < prices at i + 1
begin
if not is_buy
begin
set is_buy = true
set sum = sum - v
end
end
else
if is_buy
begin
set is_buy = false
set sum = sum + v
end
end... | class Solution(object):
def maxProfit(self, prices):
sum = 0
is_buy = False
for i, v in enumerate(prices[:-1]):
if v<prices[i+1]:
if not is_buy:
is_buy = True
sum -= v
else:
if is_buy:
... | Python | zaydzuhri_stack_edu_python |
function main
begin
comment Get authorisation token from file:
call authorise
comment Get pnut.io username:
call getme
comment Display menu:
call menu
comment Begin command entry, exit on 'exit':
call commandentry
end function | def main():
# Get authorisation token from file:
authorise()
# Get pnut.io username:
getme()
# Display menu:
menu()
# Begin command entry, exit on 'exit':
commandentry() | Python | nomic_cornstack_python_v1 |
function new
begin
if method == string POST
begin
comment get parameters form form
set Description = form at string Description
set duedate = form at string Due_date
comment conncetion to the database
set conn = call connect string todo.db
set c = call cursor
comment create table if it is not EXISTS
execute conn string... | def new():
if request.method == "POST":
#get parameters form form
Description = request.form["Description"]
duedate = request.form["Due_date"]
#conncetion to the database
conn = sqlite3.connect("todo.db")
c = conn.cursor()
#create table if it is not EXISTS
... | Python | nomic_cornstack_python_v1 |
function get_access_key
begin
return get environ string HTTP_ACCESSKEY string
end function | def get_access_key():
return environ.get('HTTP_ACCESSKEY', '') | Python | nomic_cornstack_python_v1 |
function get_splunk_client self
begin
try
begin
if APP is not none and APP != string
begin
set service = call connect host=HOST port=PORT username=USERNAME password=PASSWORD app=APP
end
else
begin
set service = call connect host=HOST port=PORT username=USERNAME password=PASSWORD
end
end
except AuthenticationError
begi... | def get_splunk_client(self):
try:
if self.APP is not None and self.APP != "":
service = client.connect(
host=self.HOST,
port=self.PORT,
username=self.USERNAME,
password=self.PASSWORD,
... | Python | nomic_cornstack_python_v1 |
function run_upload video_file_path
begin
set upload_parameters = dict string file_path video_file_path ; string file_size st_size ; string file_name base name path video_file_path
try
begin
comment Setup API client
set jwplatform_client = call Client JW_API_KEY JW_API_SECRET
comment Make /videos/create API call with m... | def run_upload(video_file_path):
upload_parameters = {
'file_path': video_file_path,
'file_size': os.stat(video_file_path).st_size,
'file_name': os.path.basename(video_file_path)
}
try:
# Setup API client
jwplatform_client = Client(JW_API_KEY, JW_API_SECRET)
... | Python | nomic_cornstack_python_v1 |
function test_redirect browser logged_in_staff mocker settings
begin
comment Set ROOT_URLCONF to this modules path. This will cause the app to use the 'urlpatterns' value defined above
comment at the module level.
set ROOT_URLCONF = __name__
set dashboard_patch = patch string dashboard.views.UserDashboard.get return_va... | def test_redirect(browser, logged_in_staff, mocker, settings):
# Set ROOT_URLCONF to this modules path. This will cause the app to use the 'urlpatterns' value defined above
# at the module level.
settings.ROOT_URLCONF = __name__
dashboard_patch = mocker.patch('dashboard.views.UserDashboard.get', return_... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import sys
import json
print string <h1>Hello!</h1>
set request = loads read stdin
print format string <p>You're looking at {}.</p> request at string url | #!/usr/bin/env python3
import sys
import json
print("<h1>Hello!</h1>")
request = json.loads(sys.stdin.read())
print("<p>You're looking at {}.</p>".format(request['url']))
| Python | zaydzuhri_stack_edu_python |
function create_subscriber self
begin
try
begin
with connect_db
begin
set request = string CREATE TABLE IF NOT EXISTS subscriber( subscriber_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, datetime TEXT NOT NULL, size INTEGER NOT NULL, groups_id INTEGER NOT NULL, FOREIGN KEY (groups_id) REFERENCES groups(groups_id) ON D... | def create_subscriber(self):
try:
with self.connect_db:
request = """CREATE TABLE IF NOT EXISTS subscriber(
subscriber_id INTEGER PRIMARY KEY
AUTOINCREMENT NOT NULL,
datetime TEXT NOT NULL... | Python | nomic_cornstack_python_v1 |
function inputs source_data
begin
if not source_tf_records_file or not target_tf_records_file
begin
raise call ValueError string Please supply a tf_records_file
end
if source_data
begin
set tuple images labels = call inputs filename=source_tf_records_file batch_size=source_batch_size num_examples_per_epoch=NUM_EXAMPLES... | def inputs(source_data):
if not FLAGS.source_tf_records_file or not FLAGS.target_tf_records_file:
raise ValueError('Please supply a tf_records_file')
if source_data:
images, labels = data_loader.inputs(filename=FLAGS.source_tf_records_file,
batch_size=FLAGS.source_bat... | Python | nomic_cornstack_python_v1 |
function unique_datestrs self
begin
set jds = unique_jds
set datestrs = list comprehension call jd2datestr d for d in jds
return set datestrs
end function | def unique_datestrs(self):
jds = self.unique_jds
datestrs = [gpi_utils.jd2datestr(d) for d in jds]
return set(datestrs) | Python | nomic_cornstack_python_v1 |
import sys
import pyautogui as pag
from time import sleep
function main
begin
set file_name = argv at 1
comment holds each char of a text file
set chars = list
comment opens text file and puts every character into chars[]
with open file_name encoding=string utf8 as file
begin
for line in file
begin
for char in line
be... | import sys
import pyautogui as pag
from time import sleep
def main():
file_name = sys.argv[1]
# holds each char of a text file
chars = []
# opens text file and puts every character into chars[]
with open(file_name, encoding="utf8") as file:
for line in file:
for c... | Python | zaydzuhri_stack_edu_python |
function two_past_questions self
begin
set question1 = call create_question string Question 1 - 30
set question2 = call create_question string Question 2 - 20
set response = get client reverse string polls:index
call assertQuerysetEqual context at string latest_question_list list question1 question2
end function | def two_past_questions(self):
question1 = create_question("Question 1", -30)
question2 = create_question("Question 2", -20)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(response.context['latest_question_list'], [question1, question2]) | Python | nomic_cornstack_python_v1 |
function pink N depth=80
begin
set a = list
set s = call iterpink depth
for n in range N
begin
append a next
end
return a
end function | def pink(N, depth=80):
a = []
s = iterpink(depth)
for n in range(N):
a.append(s.next())
return a | Python | nomic_cornstack_python_v1 |
import random
import pandas as pd
import scipy.sparse as sps
comment reading the file data train with pandas library
set data = read csv string dataset/data_train.csv
set numberInteractions = 0
for _ in data at string row
begin
set numberInteractions = numberInteractions + 1
end
print string The number of total interac... | import random
import pandas as pd
import scipy.sparse as sps
data = pd.read_csv('dataset/data_train.csv') # reading the file data train with pandas library
numberInteractions = 0
for _ in data["row"]:
numberInteractions += 1
print("The number of total interactions is: ", numberInteractions)
userList = list(d... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment 整数の入力
set n = integer input
comment スペース区切りの整数の入力
set h = list map int split input
set baseHeight = h at 0
set canViewCnt = 1
for i in range 1 n
begin
set canView = true
for j in range i
begin
if h at i < h at j
begin
set canView = false
break
end
end
if canView == true
begin
set c... | # -*- coding: utf-8 -*-
# 整数の入力
n = int(input())
# スペース区切りの整数の入力
h = list(map(int, input().split()))
baseHeight = h[0]
canViewCnt = 1
for i in range(1,n):
canView = True
for j in range(i):
if h[i] < h[j]:
canView = False
break
if canView == True:
canViewCnt += 1
#... | Python | zaydzuhri_stack_edu_python |
function get_group_name self group_id
begin
set group = first filter by query group_id=group_id
return name
end function | def get_group_name(self, group_id):
group = self.table.query.filter_by(group_id=group_id).first()
return group.name | Python | nomic_cornstack_python_v1 |
function add_header r
begin
set headers at string Cache-Control = string no-cache, no-store, must-revalidate
set headers at string Pragma = string no-cache
set headers at string Expires = string 0
set headers at string Cache-Control = string public, max-age=0
return r
end function | def add_header(r):
r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
r.headers["Pragma"] = "no-cache"
r.headers["Expires"] = "0"
r.headers['Cache-Control'] = 'public, max-age=0'
return r | Python | nomic_cornstack_python_v1 |
function test_fftn self
begin
set x = random tuple 30 20 10 + 1j * random tuple 30 20 10
call assert_allclose fft fft fft x axis=2 axis=1 axis=0 call fftn x atol=1e-06
call assert_allclose call fftn x / square root 30 * 20 * 10 call fftn x norm=string ortho atol=1e-06
end function | def test_fftn(self):
x = (random((30, 20, 10)) + (1j * random((30, 20, 10))))
assert_allclose(np.fft.fft(np.fft.fft(np.fft.fft(x, axis=2), axis=1), axis=0), np.fft.fftn(x), atol=1e-06)
assert_allclose((np.fft.fftn(x) / np.sqrt(((30 * 20) * 10))), np.fft.fftn(x, norm='ortho'), atol=1e-06) | Python | zaydzuhri_stack_edu_python |
import os
import re
import requests
from bs4 import BeautifulSoup
from utils.artist import Artist
from utils.song import Song
class MelonCrawler
begin
function search_song self q
begin
string 곡 명으로 멜론에서 검색한 결과 리스트를 리턴 :param q: 검색할 곡 명 :return: 결과 dict리스트
string 1. http://www.melon.com/search/song/index.htm 에 q={q}, se... | import os
import re
import requests
from bs4 import BeautifulSoup
from utils.artist import Artist
from utils.song import Song
class MelonCrawler:
def search_song(self, q):
"""
곡 명으로 멜론에서 검색한 결과 리스트를 리턴
:param q: 검색할 곡 명
:return: 결과 dict리스트
"""
"""
1. http... | Python | zaydzuhri_stack_edu_python |
function caches self options=dict
begin
set query = url encode options
set url = string caches
if query != string
begin
set url = string %s?%s % tuple url query
end
set result = get client url
return list comprehension cache at string name for cache in result at string body
end function | def caches(self, options={}):
query = urllib.urlencode(options)
url = "caches"
if query != "":
url = "%s?%s" % (url, query)
result = self.client.get(url)
return [cache["name"] for cache in result["body"]] | Python | nomic_cornstack_python_v1 |
string Bubble Sort
function sort lst
begin
set n = length lst
set swap = false
for i in range n
begin
set swap = false
for j in range n - i - 1
begin
if lst at j > lst at j + 1
begin
set tuple lst at j lst at j + 1 = tuple lst at j + 1 lst at j
set swap = true
end
end
if swap == false
begin
break
end
end
end function
s... | ''' Bubble Sort '''
def sort(lst):
n=len(lst)
swap=False
for i in range(n):
swap=False
for j in range(n-i-1):
if(lst[j]> lst[j+1]):
lst[j],lst[j+1]=lst[j+1],lst[j]
swap=True
if (swap==False):
break
' list for sorting '
l... | Python | zaydzuhri_stack_edu_python |
function serialized self
begin
return __dict__
end function | def serialized(self):
return self.__dict__ | Python | nomic_cornstack_python_v1 |
function __init__ self data text_column min_instances_per_cluster=none num_clusters=none max_skillset_size=100 seed=1000 debug=false
begin
set start_time = time
seed seed
set prep = call Preprocessing
set __debug = debug
set max_skillset_size = max_skillset_size
set data = data
set __text_column = text_column
call __pr... | def __init__(self, data, text_column, min_instances_per_cluster=None, num_clusters=None, max_skillset_size=100, seed=1000, debug=False):
start_time = time.time()
rd.seed(seed)
self.prep = Preprocessing()
self.__debug = debug
self.max_skillset_size = max_skillset_si... | Python | nomic_cornstack_python_v1 |
function fire self name operation args=none **kwargs
begin
string Send a message without waiting for a reply @param name: name of destination service queue @param operation: name of service operation to invoke @param args: dictionary of keyword args to pass to operation. Use this OR kwargs. @param kwargs: additional ar... | def fire(self, name, operation, args=None, **kwargs):
"""Send a message without waiting for a reply
@param name: name of destination service queue
@param operation: name of service operation to invoke
@param args: dictionary of keyword args to pass to operation.
Use... | Python | jtatman_500k |
function available_max_width_on_screen_for_commands max_command_length max_output_length
begin
set id_length = 32
set max_status_length = 8
set date_length = 26
set table_buffer = 16
set tuple width _ = call get_terminal_size
set space_left = width - table_buffer - date_length - max_status_length - id_length
set half_s... | def available_max_width_on_screen_for_commands(max_command_length: int, max_output_length: int) -> Tuple[int, int]:
id_length = 32
max_status_length = 8
date_length = 26
table_buffer = 16
width, _ = get_terminal_size()
space_left = width - table_buffer - date_length - max_status_length - id_l... | Python | nomic_cornstack_python_v1 |
comment copy
set a = list 1 2 3 4
comment shallow copy
set b = a
comment [1, 2, 3, 4]
print b
comment b의 item 변경
set b at 2 = 100
comment [1, 2, 100, 4]
print b
comment [1, 2, 100, 4], a의 item도 수정됨!!
print a | #copy
a = [1, 2, 3, 4]
b = a # shallow copy
print(b) # [1, 2, 3, 4]
b[2] = 100 # b의 item 변경
print(b) # [1, 2, 100, 4]
print(a) # [1, 2, 100, 4], a의 item도 수정됨!!
| Python | zaydzuhri_stack_edu_python |
function replace self
begin
return get pulumi self string replace
end function | def replace(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "replace") | Python | nomic_cornstack_python_v1 |
import os
import subprocess as sb
from yattag import Doc , indent
import time
call system string clear
function aws
begin
while true
begin
print string press 1 : to config aws end=string
sleep 0.2
print string press 2 : to create key pair end=string
sleep 0.2
print string press 3 : to create sg end=string
sleep 0.2
pri... | import os
import subprocess as sb
from yattag import Doc,indent
import time
os.system('clear')
def aws():
while True:
print("""
press 1 : to config aws
""",end = '')
time.sleep(0.2)
print("""
press 2 : to create key pair
""",end = '')
time.sleep(0.2)
print("""
press 3 : to create sg
""",end = ''... | Python | zaydzuhri_stack_edu_python |
import numpy
import scipy
import scipy.sparse as sparse
import matplotlib.pylab as pylab
import my_graph_tool_add_ons as mygt
import graph_tool as gt
comment TASKS:
comment -change constructor to take only incidence matrix - DONE
comment -if coordinates provided, sparse matrix is built by a separate, static method - DO... | import numpy
import scipy
import scipy.sparse as sparse
import matplotlib.pylab as pylab
import my_graph_tool_add_ons as mygt
import graph_tool as gt
# TASKS:
# -change constructor to take only incidence matrix - DONE
# -if coordinates provided, sparse matrix is built by a separate, static method - DONE
# -add co-occu... | Python | zaydzuhri_stack_edu_python |
comment GETTING STARTED WITH PANDAS #######################################
import pandas as pd
from pandas import Series , DataFrame
comment INTRO TO PANDAS DATA STRUCTURES #####################################
comment Series
comment one-dimensional array-like object containing a sequence of values and an associated a... | # GETTING STARTED WITH PANDAS #######################################
import pandas as pd
from pandas import Series, DataFrame
# INTRO TO PANDAS DATA STRUCTURES #####################################
# Series
# one-dimensional array-like object containing a sequence of values and an associated array of data labels, ca... | Python | zaydzuhri_stack_edu_python |
string Simple directed graph implementation using Nodes
class Node
begin
function __init__ self value next
begin
set value = value
set next = next
end function
end class
set a = call Node string a call Node string b call Node string c none
comment Next of a is b
value
comment next of b is c
value
comment there is no no... | """
Simple directed graph implementation using Nodes"""
class Node():
def __init__(self,value,next):
self.value = value
self.next = next
a = Node("a",Node("b",Node("c",None)))
# Next of a is b
a.next.value
# next of b is c
a.next.next.value
# there is no node after the "c"
a.next.next.next is ... | Python | zaydzuhri_stack_edu_python |
import subprocess
import time
from picamera import PiCamera
from datetime import datetime
set fail_count = 0
set init_lat = 0.0
set init_long = 0.0
set camera = call PiCamera
set count = 0
comment array will store tuple of (long, lat, ns, ew, filepath, date_time)
set open_locations = list
while true
begin
set cmd = st... | import subprocess
import time
from picamera import PiCamera
from datetime import datetime
fail_count = 0
init_lat = 0.0
init_long = 0.0
camera = PiCamera()
count = 0
open_locations = [] # array will store tuple of (long, lat, ns, ew, filepath, date_time)
while(True):
cmd = 'timeout 1 stdbuf -o0 curl 172.20... | Python | zaydzuhri_stack_edu_python |
import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import re
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
set consumer_key = string 3II162EiHwgcNCSV17YW0Ykof
set consumer_secret ... | import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import re
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
consumer_key = "3II162EiHwgcNCSV17YW0Ykof"
consumer_secret = "CZonbTz3t... | Python | zaydzuhri_stack_edu_python |
import unittest , tab , music
import itertools as it
class TestBlankStaticBars extends TestCase
begin
function setUp self
begin
set bar = bar width=32
set staff = call Staff
set arr = call Arrangement width=32
end function
function test_null_bar self
begin
assert equal bar string | { string - * 32 } | * 6
end function
... | import unittest, tab, music
import itertools as it
class TestBlankStaticBars(unittest.TestCase):
def setUp(self):
self.bar = tab.Bar(width=32)
self.staff = tab.Staff()
self.arr = tab.Arrangement(width=32)
def test_null_bar(self):
self.assertEqual(self.bar, f"|{'-' * 32}|\n" * ... | Python | zaydzuhri_stack_edu_python |
from typing import List
function sum_two_smallest_numbers numbers
begin
string Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers. No floats or empty arrays will be passed. For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7. `... | from typing import List
def sum_two_smallest_numbers(numbers: List[int]) -> int:
"""
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 integers.
No floats or empty arrays will be passed.
For example, when an array is passed like [19, 5, 42, 2, 77], t... | Python | zaydzuhri_stack_edu_python |
function og_logo self
begin
comment first try fb logo
set uf = url_for
set img = call _get_image fb_image
if img is none
begin
set img = call _get_image logo
end
if img is none
begin
comment no url
return string
end
comment fb size
set v = get variants string facebook none
if v is none
begin
return string
end
return ... | def og_logo(self):
# first try fb logo
uf = self.app.url_for
img = self._get_image(self.barcamp.fb_image)
if img is None:
img = self._get_image(self.barcamp.logo)
if img is None:
return "" # no url
v = img.variants.get('facebook', None) # fb size
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding=utf-8
from PIL import Image , ImageDraw , ImageFont
import random
import math
import os
import argparse
function operation x op y mode
begin
string return equation string giving x, y, operator, within mode of 'chi' or 'en'
set lang_mapper = list string 零 string 壹 string 贰 str... | #!/usr/bin/env python
# coding=utf-8
from PIL import Image, ImageDraw, ImageFont
import random
import math
import os
import argparse
def operation(x, op, y, mode):
'''
return equation string giving x, y, operator, within mode of 'chi' or 'en'
'''
lang_mapper = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', ... | Python | zaydzuhri_stack_edu_python |
function calculate_hash_value string
begin
comment hash_value is calculated as ** unicode(A)*100 + unicode(h) **
return ordinal string at 0 * 100 + ordinal string at 1
end function | def calculate_hash_value(string):
# hash_value is calculated as ** unicode(A)*100 + unicode(h) **
return ord(string[0])*100+ord(string[1]) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from PIL import Image
comment СГЕНЕРИРОВАТЬ ТУМБ
function generate_thumb input size=tuple 100 100 output=none
begin
set image = open input
if not output
begin
set output = input + string _thumb
end
if mode not in tuple string L string RGB
begin
set image = call convert string RGB
end
set b... | # -*- coding: utf-8 -*-
from PIL import Image
#СГЕНЕРИРОВАТЬ ТУМБ
def generate_thumb(input, size=(100, 100), output=None):
image = Image.open(input)
if(not output):
output = input+'_thumb'
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
box = image.size[0] > image.size[1] and image.size[1... | Python | zaydzuhri_stack_edu_python |
function test_070_reset_data_for_later_test_runs self
begin
call delete_history id=string id
call delete_history id=string id
call delete_history id=string id
call delete_history id=string id
call delete_history id=string id
end function | def test_070_reset_data_for_later_test_runs( self ):
self.delete_history( id=str( history3.id ) )
self.delete_history( id=str( history4.id ) )
self.delete_history( id=str( history5.id ) )
self.delete_history( id=str( history6.id ) )
self.delete_history( id=str( history7.id ) ) | Python | nomic_cornstack_python_v1 |
function breakout_loop self
begin
while playing
begin
call handle_events
update self
if game_over
begin
set current_menu = fail_menu
set playing = false
call reset
end
call draw
end
end function | def breakout_loop(self):
while self.playing:
self.handle_events()
self.update()
if self.game_over:
self.current_menu = self.fail_menu
self.playing = False
self.reset()
self.draw() | Python | nomic_cornstack_python_v1 |
comment -*- coding=utf-8 -*-
import Tkinter as tk
import edit
import gui
import editor_status
class GuiCatalog extends BaseEditor
begin
function __init__ self root
begin
call __init__ self root
call pack
call pack
call bind string <o> toggle_node
call bind string <x> close_parent_node
call config cursor=string arrow in... | # -*- coding=utf-8 -*-
import Tkinter as tk
import edit
import gui
import editor_status
class GuiCatalog(gui.BaseEditor):
def __init__(self, root):
gui.BaseEditor.__init__(self, root)
self.t.pack()
self.pack()
self.t.bind("<o>", self.toggle_node)
self.t.bind("<x>", se... | Python | zaydzuhri_stack_edu_python |
function read_file fp defer_size=none stop_before_pixels=false force=false
begin
comment Open file if not already a file object
set caller_owns_file = true
if is instance fp basestring
begin
comment caller provided a file name; we own the file handle
set caller_owns_file = false
debug format string Reading file '{0}' f... | def read_file(fp, defer_size=None, stop_before_pixels=False, force=False):
# Open file if not already a file object
caller_owns_file = True
if isinstance(fp, basestring):
# caller provided a file name; we own the file handle
caller_owns_file = False
logger.debug(u"Reading file '{0}'"... | Python | nomic_cornstack_python_v1 |
function paths_prob_to_edges_flux paths_prob
begin
set edge_flux = dict
for tuple path prob in items paths_prob
begin
for i in range length path - 1
begin
comment Get edge
set edge = tuple path at i path at i + 1
comment Get path probability to edge.
if edge in edge_flux
begin
set edge_flux at edge = edge_flux at edge... | def paths_prob_to_edges_flux(paths_prob):
edge_flux = {}
for path, prob in paths_prob.items():
for i in range(len(path)-1):
# Get edge
edge = (path[i], path[i+1])
# Get path probability to edge.
if edge in edge_flux:
edge_flux[edge] += pr... | Python | nomic_cornstack_python_v1 |
function add_member self member
begin
append members member
end function | def add_member(self, member):
self.members.append(member) | Python | nomic_cornstack_python_v1 |
function grunt_build
begin
call local string cd {{ project_name }} && grunt build
end function | def grunt_build():
local('cd {{ project_name }} && grunt build') | Python | nomic_cornstack_python_v1 |
function private_link_resource_id self
begin
return get pulumi self string private_link_resource_id
end function | def private_link_resource_id(self) -> Optional[str]:
return pulumi.get(self, "private_link_resource_id") | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.