code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import keras
from keras.models import Model
from keras import Input
from keras import layers
import numpy as np
import myutils.performance_utils as performance_utils
call opitimize_cpu
set text_vocabulary_size = 10000
set question_vocabulary_size = 10000
set answer_vocabulary_size = 500
set text_tensor = input shape=tu... | import keras
from keras.models import Model
from keras import Input
from keras import layers
import numpy as np
import myutils.performance_utils as performance_utils
performance_utils.opitimize_cpu()
text_vocabulary_size = 10000
question_vocabulary_size = 10000
answer_vocabulary_size = 500
text_tensor = Input(shape=(... | Python | zaydzuhri_stack_edu_python |
from random import randint , shuffle
comment 2 конверта с наличкой в 100 и 200 валюты
set envelopes = list 200 100
comment счетчик выигрышей упертого игрока
set stubborn = 0
comment счетчик выигрышей переменчивого игрока
set unstable = 0
for i in range 1000
begin
comment перемешиваем конверты
shuffle envelopes
comment ... | from random import randint, shuffle
envelopes = [200, 100] # 2 конверта с наличкой в 100 и 200 валюты
stubborn = 0 # счетчик выигрышей упертого игрока
unstable = 0 # счетчик выигрышей переменчивого игрока
for i in range(1000):
shuffle(envelopes) # перемешиваем конверты
f = randint(0, 1) # генерируем выбор... | Python | zaydzuhri_stack_edu_python |
string Proof of Work POW is a way to improve cryptocurrency's secureness work must be invested to add a block to the blockchain so that it is easier to add a block than to try to modify previous blocks in the chain this is done by putting restrictions on the hash codes created from the transactions rewards are given to... | """
Proof of Work
POW is a way to improve cryptocurrency's secureness
work must be invested to add a block to the blockchain
so that it is easier to add a block than to try to
modify previous blocks in the chain
this is done by putting restrictions on the hash codes
created from the transactions
rewards are give... | Python | zaydzuhri_stack_edu_python |
import os
comment SSAFY지원자 폴더로 들어간다.
change directory string SSAFY지원자
comment SSAFY지원자 폴더로 들어간다.
change directory string SSAFY지원자
comment 내용 모두 출력
set files = list directory
print files
for f in files
begin
rename f replace f string SAMSUNG string SSAFY
end | import os
# SSAFY지원자 폴더로 들어간다.
os.chdir(r"SSAFY지원자")
# SSAFY지원자 폴더로 들어간다.
os.chdir(r"SSAFY지원자")
# 내용 모두 출력
files = os.listdir()
print(files)
for f in files:
os.rename(f, f.replace("SAMSUNG", "SSAFY"))
| Python | zaydzuhri_stack_edu_python |
async function set_avatar self avatar_id delay=0 lifespan=inf
begin
await call add_output format string |/avatar {} avatar_id delay=delay lifespan=lifespan
end function | async def set_avatar(self, avatar_id, delay=0, lifespan=math.inf):
await self.add_output(
"|/avatar {}".format(avatar_id), delay=delay, lifespan=lifespan
) | Python | nomic_cornstack_python_v1 |
import threading
import asyncio
import discord
set noGod = false
function term_commands
begin
global noGod
set responce = lower input string
if responce == string help
begin
print string *help ------- View terminal commands
print string *togs ------- Toggle voteskip command
end
else
if responce == string togs
begin
set... | import threading
import asyncio
import discord
noGod = False
def term_commands():
global noGod
responce = input("").lower()
if responce == "help":
print("*help ------- View terminal commands")
print("*togs ------- Toggle voteskip command")
elif responce == "togs":
noGod = not n... | Python | zaydzuhri_stack_edu_python |
comment Generate primes
comment Authoer : Michelle O'Connor
set primes = list
set upto = 100000
set candidates = range 2 upto + 1
print type candidates
for candidate in candidates
begin
print candidate end=string
set isPrime = true
comment check if it is a prime
for divisor in primes
begin
if candidate % divisor == 0
... | # Generate primes
# Authoer : Michelle O'Connor
primes = []
upto = 100000
candidates = range(2, upto+1)
print (type(candidates))
for candidate in candidates:
print(candidate, end= " ")
isPrime = True
# check if it is a prime
for divisor in primes:
if candidate % divisor == 0:
is... | Python | zaydzuhri_stack_edu_python |
import pprint
class DynatraceObject
begin
function __init__ self http_client headers raw_element
begin
set _http_client = http_client
set _headers = headers
set _raw_element = raw_element
call _create_from_raw_data raw_element
end function
function _create_from_raw_data self raw_element
begin
pass
end function
function... | import pprint
class DynatraceObject:
def __init__(self, http_client, headers, raw_element):
self._http_client = http_client
self._headers = headers
self._raw_element = raw_element
self._create_from_raw_data(raw_element)
def _create_from_raw_data(self, raw_element):
pas... | Python | zaydzuhri_stack_edu_python |
function create_description_files self jobs job_site
begin
set i = 0
for job in jobs
begin
set url = call get_job_url
set description_page = get requests url
comment Open a file
set file_name = string samples/ + job_site + string /descriptions/description + string i + string .html
set fo = open file_name string w
write... | def create_description_files(self, jobs, job_site):
i = 0
for job in jobs:
url = job.get_job_url()
description_page = requests.get(url)
# Open a file
file_name = "samples/" + job_site + "/descriptions/description" + str(i) + ".html"
fo... | Python | nomic_cornstack_python_v1 |
string ColumnConversion.py Author: Elliot Davis This file is responsible for converting the columns for each attribute we want to generalize.
import pandas as pd
import copy
from KValue import readFiles
set datasetDF = call readFiles
comment This function returns either the original data or a suppressed list depending ... | """
ColumnConversion.py
Author: Elliot Davis
This file is responsible for converting the columns for each attribute we want to generalize.
"""
import pandas as pd
import copy
from KValue import readFiles
datasetDF = readFiles()
# This function returns either the original data or a suppressed list depending on dim
... | Python | zaydzuhri_stack_edu_python |
function slope_style_score scores
begin
set minn = scores at 0
set maxx = scores at 0
set summ = 0
for i in scores
begin
if i < minn
begin
set minn = i
end
else
if i > maxx
begin
set maxx = i
end
end
for i in scores
begin
set summ = summ + i
end
set summ = summ - maxx - minn
set summ = decimal summ / length scores - 2
... | def slope_style_score(scores):
minn = scores[0]
maxx = scores[0]
summ = 0
for i in scores:
if i < minn:
minn = i
elif i > maxx:
maxx = i
for i in scores:
summ += i
summ = summ - maxx - minn
summ = float(summ / (len(scores) - 2))
return summ
| Python | zaydzuhri_stack_edu_python |
function palindrome_checker strings
begin
set is_palindrome = true
for string in strings
begin
if string != string at slice : : - 1
begin
set is_palindrome = false
break
end
end
return is_palindrome
end function
set strings = list string abba string bob string acca
print call palindrome_checker strings | def palindrome_checker(strings):
is_palindrome = True
for string in strings:
if string != string[::-1]:
is_palindrome = False
break
return is_palindrome
strings = ['abba', 'bob', 'acca']
print(palindrome_checker(strings))
| Python | flytech_python_25k |
function test_json_flat_json before_json_flat after_json_flat json_flat_res
begin
assert loads call gendiff before_json_flat after_json_flat == json_flat_res
end function | def test_json_flat_json(
before_json_flat,
after_json_flat,
json_flat_res: str,
):
assert json.loads(
gendiff(before_json_flat, after_json_flat),
) == json_flat_res | Python | nomic_cornstack_python_v1 |
function get_preptools_version
begin
try
begin
set version = version
end
except DistributionNotFound
begin
set version_path = join path PROJECT_ROOT_PATH string VERSION
with open version_path mode=string r as version_file
begin
set version = read version_file
end
end
except any
begin
set version = string unknown
end
re... | def get_preptools_version() -> str:
try:
version = pkg_resources.get_distribution('preptools').version
except pkg_resources.DistributionNotFound:
version_path = os.path.join(PROJECT_ROOT_PATH, 'VERSION')
with open(version_path, mode='r') as version_file:
version = version_fil... | Python | nomic_cornstack_python_v1 |
string Created on Abr 6, 2016 Validate the DIVA agent used for the Epirob 2017's paper but using divapy @author: Juan Manuel Acevedo Valle
import numpy as np
import numpy.linalg as la
from exploration.systems.Diva2016a import Diva2016a as Divaml
from exploration.systems.Diva2016b import Diva2016b as Divapy
from explora... | """
Created on Abr 6, 2016
Validate the DIVA agent used for the Epirob 2017's paper
but using divapy
@author: Juan Manuel Acevedo Valle
"""
import numpy as np
import numpy.linalg as la
from exploration.systems.Diva2016a import Diva2016a as Divaml
from exploration.systems.Diva2016b import Diva2016b as Divapy
from explo... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment 阿里天池预测项目
import time
import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import ShuffleSplit
from sklearn import linear_model
from sklearn.tree import DecisionTreeCl... | #-*- coding: utf-8 -*-
#阿里天池预测项目
import time
import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import ShuffleSplit
from sklearn import linear_model
from sklearn.tree import DecisionTreeClassifier
from ... | Python | zaydzuhri_stack_edu_python |
function multithread_signal_alignment signal_align_arguments fast5_locations worker_count=1 forward_reference=none debug=false filter_reads_to_string_wrapper_funct=none
begin
comment don't modify the signal_align_arguments
set signal_align_arguments = dictionary keyword signal_align_arguments
if not forward_reference
b... | def multithread_signal_alignment(signal_align_arguments, fast5_locations, worker_count=1, forward_reference=None,
debug=False, filter_reads_to_string_wrapper_funct=None):
# don't modify the signal_align_arguments
signal_align_arguments = dict(**signal_align_arguments)
if not... | Python | nomic_cornstack_python_v1 |
function test_append_output_options self
begin
with call subTest msg=string should initially be []
begin
assert equal output_options list
end
set test_data = tuple tuple list list string [] ⇒ [] tuple list string foo list string foo string ["foo"] ⇒ ["foo"] tuple list string bar list string foo string bar string ["ba... | def test_append_output_options(self):
with self.subTest(msg="should initially be []"):
self.assertEqual(self.command.output_options, [])
test_data = (
([], [], "[] ⇒ []"),
(["foo"], ["foo"], '["foo"] ⇒ ["foo"]'),
(["bar"], ["foo", "bar"], '["bar"] ⇒ ["foo"... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string Test cases for testing the functionality of the array data structures Author: Alexander Roth Date: 2014-11-27
import unittest
from array_stack import ArrayStack
class TestArrayStackFunctions extends TestCase
begin
function setUp self
begin
set array_stack = call ArrayStack
end funct... | #!/usr/bin/env python3
''' Test cases for testing the functionality of the array data structures
Author: Alexander Roth
Date: 2014-11-27
'''
import unittest
from array_stack import ArrayStack
class TestArrayStackFunctions(unittest.TestCase):
def setUp(self):
self.array_stack = ArrayStack()
def tes... | Python | zaydzuhri_stack_edu_python |
import ESP8266WebServer
import network
import machine
comment Builtin led (D4)
set GPIO_NUM = 2
comment Get pin object for controlling builtin LED
set pin = call Pin GPIO_NUM OUT
comment Turn LED off (it use sinking input)
call on
comment Dictionary for template file
set ledData = dict string title string Remote LED ; ... | import ESP8266WebServer
import network
import machine
GPIO_NUM = 2 # Builtin led (D4)
# Get pin object for controlling builtin LED
pin = machine.Pin(GPIO_NUM, machine.Pin.OUT)
pin.on() # Turn LED off (it use sinking input)
# Dictionary for template file
ledData = {
"title":"Remote LED",
"color":"red",
"st... | Python | zaydzuhri_stack_edu_python |
function proj_sep_lite angular_separation R_comoving
begin
comment comoving rproj
set projected_separation = angular_separation * R_comoving
return projected_separation
end function | def proj_sep_lite( angular_separation, R_comoving):
projected_separation = angular_separation*R_comoving #comoving rproj
return projected_separation | Python | nomic_cornstack_python_v1 |
import unittest
from literki import contains
class literki extends TestCase
begin
function test_contains_letter self
begin
assert equal true call contains string word string w
assert equal true call contains string Word string W
assert equal false call contains string word string z
end function
function test_contains_u... | import unittest
from literki import contains
class literki(unittest.TestCase):
def test_contains_letter(self):
self.assertEqual(True, contains("word", "w"))
self.assertEqual(True, contains("Word", "W"))
self.assertEqual(False, contains("word", "z"))
def test_contains_uppercse(self):
... | Python | zaydzuhri_stack_edu_python |
from enumerable import Enumerable
from extensible import Extensible
class Collection extends Enumerable Extensible
begin
function __init__ self *args
begin
set _container = args
end function
function __iter__ self
begin
return iterate _container
end function
function __eq__ self other
begin
return list _container == li... | from enumerable import Enumerable
from extensible import Extensible
class Collection(Enumerable, Extensible):
def __init__(self, *args):
self._container = args
def __iter__(self):
return iter(self._container)
def __eq__(self, other):
return list(self._container) == list(other.__it... | Python | zaydzuhri_stack_edu_python |
comment findShortestUniqueSubstring
comment find shortest substring in arr which contain all unique characters
function findShortestUniqueSubstring arr
begin
comment sliding window: O(n), O(n)
if not arr
begin
return none
end
set stored = default dictionary int
set target = length set arr
set tuple left right = tuple 0... | #findShortestUniqueSubstring
## find shortest substring in arr which contain all unique characters
def findShortestUniqueSubstring(arr):
## sliding window: O(n), O(n)
if not arr: return None
stored=defaultdict(int)
target = len(set(arr))
left, right = 0, 0
out=arr
while right<len(arr)... | Python | zaydzuhri_stack_edu_python |
function triplet_sum_zero arr
begin
set triplet = list 0 0 0
set difference_map = dict
for i in arr
begin
set difference_map at 1 = string
end
for element in arr
begin
for i in arr
begin
if i == element
begin
continue
end
if - i + element in difference_map
begin
set triplet at 0 = element
set triplet at 1 = i
set tri... | def triplet_sum_zero(arr:list):
triplet = [0,0,0]
difference_map = {}
for i in arr:
difference_map[1] = ""
for element in arr:
for i in arr:
if i == element:
continue
if -(i + element) in difference_map:
triplet[0] = element
... | Python | nomic_cornstack_python_v1 |
function hey msg
begin
if call silence msg
begin
return string Fine. Be that way!
end
else
if call shouted_at msg
begin
return string Woah, chill out!
end
else
if call got_asked msg
begin
return string Sure.
end
return string Whatever.
end function
function got_asked msg
begin
return ends with msg string ?
end function... | def hey(msg):
if silence(msg):
return 'Fine. Be that way!'
elif shouted_at(msg):
return 'Woah, chill out!'
elif got_asked(msg):
return 'Sure.'
return 'Whatever.'
def got_asked(msg):
return msg.endswith('?')
def shouted_at(msg):
return msg.isupper()
def silence(msg):
... | Python | zaydzuhri_stack_edu_python |
string Crie um programa que o usuário possa digitar sete valores numéricos e cadastreas em uma - única lista que mantenha separados os valores ímpares e pares no final mostre os valores p- ares e ímpares em ordem crescente.
set impar = list
set par = list
set listão = list
for i in range 0 7
begin
set n = integer input... | """
Crie um programa que o usuário possa digitar
sete valores numéricos e cadastreas em uma -
única lista que mantenha separados os valores
ímpares e pares no final mostre os valores p-
ares e ímpares em ordem crescente.
"""
impar = list()
par = list()
listão = list()
for i in range(0,7):
n = int(input('Escreva um... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
import numpy as np
from astropy.io import fits
from scipy.signal import fftconvolve
import time
comment Fungsi utama untuk melakukan restorasi
function richardson_lucy image psf iterations=50
begin
set image = as type image float
set psf = as type psf float
se... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
from astropy.io import fits
from scipy.signal import fftconvolve
import time
# Fungsi utama untuk melakukan restorasi
def richardson_lucy(image, psf, iterations=50):
image = image.astype(np.float)
psf = psf.astype(np.float)
BG = np... | Python | zaydzuhri_stack_edu_python |
if w >= 380 and w < 450
begin
print string Violet
end
else
if w >= 450 and w < 495
begin
print string Blue
end
else
if w >= 495 and w < 570
begin
print string Green
end
else
if w >= 570 and w < 590
begin
print string Yellow
end
else
if w >= 590 and w < 620
begin
print string Orange
end
else
if w >= 620 and w < 750
begi... | if w>=380 and w<450:
print(f"Violet")
elif w>=450 and w<495:
print(f"Blue")
elif w>=495 and w<570:
print(f"Green")
elif w>=570 and w<590:
print(f"Yellow")
elif w>=590 and w<620:
print(f"Orange")
elif w>=620 and w<750:
print(f"Red")
else:
print("Outside of the visible spectrum")
| Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
comment class TreeNode(object):
comment def __init__(self, val=0, left=None, right=None):
comment self.val = val
comment self.left = left
comment self.right = right
class Solution extends object
begin
function isBalancedInner self root
begin
if root is none
begin
return 0
end
... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isBalancedInner(self, root):
if root is None:
return 0
ld = ... | Python | zaydzuhri_stack_edu_python |
function func l
begin
append l 1
if length l == 10
begin
return l
end
return call func l
end function
set l = list
print call func l length l
set a = list 0.8 0.85 0.9 0.95
set b = list 0.025 0.05 0.075 0.1
set l = list
for x in a
begin
for y in b
begin
print x y
append l tuple x y
end
end
print l | def func(l):
l.append(1)
if len(l)==10:
return l
return func(l)
l=[]
print(func(l),len(l))
a=[0.8,0.85,0.9,0.95]
b=[0.025,0.05,0.075,0.1]
l=[]
for x in a:
for y in b:
print(x,y)
l.append((x,y))
print(l)
| Python | zaydzuhri_stack_edu_python |
for i in setA
begin
if i not in setB
begin
add difference_set i
end
end
print difference_set
comment print(setA.difference(setB)) | for i in setA:
if i not in setB:
difference_set.add(i)
print(difference_set)
# print(setA.difference(setB)) | Python | zaydzuhri_stack_edu_python |
function dump_with_name self id_to_name
begin
return string id_to_name at player + string _num
end function | def dump_with_name(self, id_to_name):
return str(id_to_name[self.player]) + str(self._num) | Python | nomic_cornstack_python_v1 |
with open string 13.data as ff
begin
set vals = generator expression integer strip ll for ll in ff
print string sum vals at slice : 10 :
end | with open('13.data') as ff:
vals = (int(ll.strip()) for ll in ff)
print(str(sum(vals))[:10]) | Python | zaydzuhri_stack_edu_python |
comment x[depth, row, column]
from x import x
from w1 import w1
comment z1[row, column, depth]
from z1 import z1
set b1 = list - 0.0015993764 0.0015842086 0.00091546599 6.1487175e-05 - 0.00054973643 0.0027095852 0.0015602008 0.00073724525 8.3429677e-06 - 8.6893897e-06 0.00080423272 0.0034193427 0.0013294573 - 0.0042469... | from x import x # x[depth, row, column]
from w1 import w1
from z1 import z1 # z1[row, column, depth]
b1 = [-1.5993764e-03, 1.5842086e-03, 9.1546599e-04, 6.1487175e-05,
-5.4973643e-04, 2.7095852e-03, 1.5602008e-03, 7.3724525e-04,
8.3429677e-06, -8.6893897e-06, 8.0423272e-04, 3.4193427e-03,
... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python
comment Author : Ye Jinchang
comment Date : 2016-04-14 11:11:54
comment Title : 201 bitwise and of numbers range
comment Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
comment For example, given the range [5, 7], you should retu... | #!/bin/python
#
# Author : Ye Jinchang
# Date : 2016-04-14 11:11:54
# Title : 201 bitwise and of numbers range
# Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
#
# For example, given the range [5, 7], you should return 4.
#
# Cre... | Python | zaydzuhri_stack_edu_python |
function time self
begin
return time
end function | def time(self):
return self.d_time.time() | Python | nomic_cornstack_python_v1 |
function assign_images self images
begin
set images = images
end function | def assign_images(self, images):
self.images = images | Python | nomic_cornstack_python_v1 |
import time
from flask import Flask
from flask_cors import CORS
from qibullet import SimulationManager
set app = call Flask __name__
call CORS app
set simulation_manager = call SimulationManager
set client_id = call launchSimulation gui=true
comment Spawning a virtual Pepper robot, at the origin of the WORLD frame, and... | import time
from flask import Flask
from flask_cors import CORS
from qibullet import SimulationManager
app = Flask(__name__)
CORS(app)
simulation_manager = SimulationManager()
client_id = simulation_manager.launchSimulation(gui=True)
# Spawning a virtual Pepper robot, at the origin of the WORLD frame, and a
# groun... | Python | zaydzuhri_stack_edu_python |
string TESTCASE Python C Java Go Java PHP Python Java - python php python java rust php ruby - python - test TEST tesT Test
function count_str s
begin
set d = dict
for i in split s
begin
set default d i 0
set d at i = d at i + 1
end
return d
end function
set d = call count_str lower input
set cnt = sorted items d key=... | '''TESTCASE
Python C Java Go Java PHP Python Java
-
python php python java rust php ruby
-
python
-
test TEST tesT Test
'''
def count_str(s: str):
d = {}
for i in s.split():
d.setdefault(i, 0)
d[i] += 1
return d
d = count_str(input().lower())
cnt = sorted(d.items(), key=lambda x: x[0])
f... | Python | zaydzuhri_stack_edu_python |
comment Definisikan class Karyawan
class Karyawan
begin
set nama_perusahaan = string ABC
end class
comment Inisiasi object yang dinyatakan dalam variabel aksara dan senja
set aksara = call Karyawan
set senja = call Karyawan
comment Cetak nama perusahaan melalui penggunaan keyword __class__
comment pada class attribute ... | # Definisikan class Karyawan
class Karyawan:
nama_perusahaan = 'ABC'
# Inisiasi object yang dinyatakan dalam variabel aksara dan senja
aksara = Karyawan()
senja = Karyawan()
# Cetak nama perusahaan melalui penggunaan keyword __class__
# pada class attribute nama_perusahaan
print(aksara.__class__.nama_perusahaan)
# ... | Python | zaydzuhri_stack_edu_python |
function connect_logs self logs
begin
del logs at slice : :
if not controller_config at string logging_enabled
begin
return logs
end
for log_config in controller_config at string logs
begin
set logger = none
set log_type = log_config at string type
if log_type == MONGODB_LOG
begin
set logger = call MongoDBLogger log... | def connect_logs(self, logs):
del logs[:]
if not self.controller_config["logging_enabled"]:
return logs
for log_config in self.controller_config["logs"]:
logger = None
log_type = log_config["type"]
if log_type == constants.MONGODB_LOG:
... | Python | nomic_cornstack_python_v1 |
function getFloatingResult self
begin
return decimal numerator / denominator
end function | def getFloatingResult(self):
return float(self.numerator)/self.denominator | Python | nomic_cornstack_python_v1 |
import os
set currentZoomValue = integer read popen string uvcdynctrl -g "Zoom, Absolute"
if currentZoomValue < 180
begin
set newZoomValue = currentZoomValue + 20
end
else
begin
set newZoomValue = 180
end
set newZoomValueCommand = string uvcdynctrl -s "Zoom, Absolute" + string newZoomValue
call system newZoomValueComma... | import os
currentZoomValue = int(os.popen('uvcdynctrl -g "Zoom, Absolute"').read())
if currentZoomValue <180:
newZoomValue = currentZoomValue + 20
else:
newZoomValue = 180
newZoomValueCommand = 'uvcdynctrl -s "Zoom, Absolute" ' + str(newZoomValue)
os.system(newZoomValueCommand)
| Python | zaydzuhri_stack_edu_python |
function build_data self
begin
call fit_char_vectorizer
call fit_word_vectorizer
call fit_pos_vectorizer
call lexical_features
call coref_features
call voice_features
set authors = call DataFrame dict string author list comprehension author for d in documents
set X_ = concat list char_mat word_mat pos_mat lex_mat coref... | def build_data(self):
self.fit_char_vectorizer()
self.fit_word_vectorizer()
self.fit_pos_vectorizer()
self.lexical_features()
self.coref_features()
self.voice_features()
self.authors = pd.DataFrame({'author': [d.author for d in self.documents]})
self.X_ ... | Python | nomic_cornstack_python_v1 |
async function unhandled_response self pkt source
begin
if false
begin
yield none
end
end function | async def unhandled_response(self, pkt, source):
if False:
yield None | Python | nomic_cornstack_python_v1 |
function det_hts ht
begin
if string / in ht
begin
return 0
end
return integer ht
end function | def det_hts(ht):
if "/" in ht:
return 0
return int(ht) | Python | nomic_cornstack_python_v1 |
from tkinter import *
comment creando la raiz:
set root = call Tk
title root string Hola mundo
comment Resizable:
comment root.resizable(0,0) #asi no se podria hacer resize
comment root.resizable(0,1) # resizable verticalmente
comment root.resizable(1,0) # resizable horizontalmente
comment por defecto resizable en ambo... | from tkinter import *
##creando la raiz:
root = Tk()
root.title("Hola mundo")
## Resizable:
#root.resizable(0,0) #asi no se podria hacer resize
#root.resizable(0,1) # resizable verticalmente
#root.resizable(1,0) # resizable horizontalmente
root.resizable(1,1) # por defecto resizable en ambos lados.
root.iconbitmap('h... | Python | zaydzuhri_stack_edu_python |
function test_with_basic_algorithm self
begin
set odds : List at Ellipsis = list
for n in range 1 6
begin
if n % 2 == 0
begin
append odds n
end
end
call assertListEqual odds list 2 4
end function | def test_with_basic_algorithm(self) -> None:
odds: List[...] = list()
for n in range(1, 6):
if n % 2 == 0:
odds.append(n)
self.assertListEqual(odds, [2, 4]) | Python | nomic_cornstack_python_v1 |
import json
import base64
import issuer_helpers
import verify_helpers
comment Paths below can be modified, which is just for testing
set pdf_import_path = string ../PDFs
set json_export_path = string ../configuration/blockcert_certificates
set tools_conf = string ../configuration/cert_tools_conf.ini
set issuer_conf = s... | import json
import base64
import issuer_helpers
import verify_helpers
# Paths below can be modified, which is just for testing
pdf_import_path = '../PDFs'
json_export_path = '../configuration/blockcert_certificates'
tools_conf = '../configuration/cert_tools_conf.ini'
issuer_conf = '../configuration/cert_issuer_conf.... | Python | zaydzuhri_stack_edu_python |
function test_iterable_len self
begin
for tuple iterable_len expected_size in list tuple 5 5 tuple 150 100 tuple none 100
begin
with call subTest iterable_len=iterable_len
begin
set tuple iterable_of_args iterable_len_ chunk_size n_splits = call apply_numpy_chunking test_data_numpy iterable_len=iterable_len n_splits=1
... | def test_iterable_len(self):
for iterable_len, expected_size in [(5, 5), (150, 100), (None, 100)]:
with self.subTest(iterable_len=iterable_len):
iterable_of_args, iterable_len_, chunk_size, n_splits = apply_numpy_chunking(
self.test_data_numpy, iterable_len=iterab... | Python | nomic_cornstack_python_v1 |
while a < b
begin
print a
set a = a + 2
end
print string THis is end of Loop | while a<b:
print(a)
a+=2
print('THis is end of Loop') | Python | zaydzuhri_stack_edu_python |
from gazpacho import get , Soup
import time
from tqdm import tqdm
import pandas as pd
import numpy as np
import re
import datetime as DT
function get_pbp_links url
begin
set html = get url
set soup = call Soup html
set data = find soup string td dict string data-stat string date_game
set links = list comprehension find... | from gazpacho import get, Soup
import time
from tqdm import tqdm
import pandas as pd
import numpy as np
import re
import datetime as DT
def get_pbp_links(url):
html = get(url)
soup = Soup(html)
data = soup.find('td', {'data-stat': 'date_game'})
links = [l.find('a') for l in data]
pbp_links = ["http... | Python | zaydzuhri_stack_edu_python |
function read_user self username mount_point=DEFAULT_MOUNT_POINT
begin
set api_path = call format_url string /v1/auth/{mount_point}/users/{username} mount_point=mount_point username=username
return get _adapter url=api_path
end function | def read_user(self, username, mount_point=DEFAULT_MOUNT_POINT):
api_path = utils.format_url(
"/v1/auth/{mount_point}/users/{username}",
mount_point=mount_point,
username=username,
)
return self._adapter.get(
url=api_path,
) | Python | nomic_cornstack_python_v1 |
function _handleCheckMarkToggled self
begin
comment Go through all the musicalRatios in the widget, and set them
comment as enabled or disabled in the artifact, based on the check
comment state of the QCheckBox objects in self.checkBoxes.
for i in range length checkBoxes
begin
set oldValue = call isEnabled
set newValue... | def _handleCheckMarkToggled(self):
# Go through all the musicalRatios in the widget, and set them
# as enabled or disabled in the artifact, based on the check
# state of the QCheckBox objects in self.checkBoxes.
for i in range(len(self.checkBoxes)):
oldValue = self.artifact.... | Python | nomic_cornstack_python_v1 |
function allowed_ips self
begin
return call value_list_to_comma string AllowedIPs allowed_ips
end function | def allowed_ips(self):
return value_list_to_comma('AllowedIPs', self._peer.allowed_ips) | Python | nomic_cornstack_python_v1 |
function collect_sql_quarry_result self sql_code quarry_args=none num_of_rows=none filer_unique=true rows_dict=true decode_rows=true
begin
set prev_row_factory = row_factory
set l_func = __type_load
if rows_dict
begin
if decode_rows
begin
set row_factory = lambda r_cur row -> dictionary comprehension k : call l_func ca... | def collect_sql_quarry_result(self, sql_code, quarry_args=None, num_of_rows=None, filer_unique=True,
rows_dict=True, decode_rows=True):
prev_row_factory = self.db_cursor.row_factory
l_func = self.__type_load
if rows_dict:
if decode_rows:
... | Python | nomic_cornstack_python_v1 |
function test_command_line_entrypoint self
begin
try
begin
import hardest.command_line
assert true command_line
end
comment pragma: no cover
except ImportError
begin
set message = string command_line should imports, but fail
call fail message
end
end function | def test_command_line_entrypoint(self):
try:
import hardest.command_line
self.assertTrue(hardest.command_line)
except ImportError: # pragma: no cover
message = 'command_line should imports, but fail'
self.fail(message) | Python | nomic_cornstack_python_v1 |
function readDissimMat self
begin
if call system == string Windows
begin
set path_SNM = join path string lib string superNMotifWin
end
else
begin
set path_SNM = join path string lib string superNMotif
end
set path_matrix = join path path_SNM string resultMatrix + string userId string matDissim_SSbySS.csv
set path_matri... | def readDissimMat(self):
if platform.system() == 'Windows':
path_SNM = os.path.join('lib', 'superNMotifWin')
else:
path_SNM = os.path.join('lib', 'superNMotif')
path_matrix = path_matrix = os.path.join(path_SNM, 'resultMatrix' + str(self.userId), 'matDissim_SSbySS.csv')
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string @authors : Calbert Julien & Godfriaux Maxime
import numpy as np
comment This class defines the neuralNetworks
class NNetwork
begin
comment This function defines the Neural Network. p indicates if its the first
comment generation, NeuralNetworkArchitecture is an array representing th... | # -*- coding: utf-8 -*-
"""
@authors : Calbert Julien & Godfriaux Maxime
"""
import numpy as np
# This class defines the neuralNetworks
class NNetwork:
# This function defines the Neural Network. p indicates if its the first
# generation, NeuralNetworkArchitecture is an array representing the number
... | Python | zaydzuhri_stack_edu_python |
print string Enter the value of first number :
set intger1 = integer input
print string Enter the value of second number :
set integer2 = integer input
set division = intger1 / integer2
print string division of two numbers division | print("Enter the value of first number : ")
intger1=int(input());
print("Enter the value of second number : ")
integer2 = int(input());
division=intger1/integer2
print("division of two numbers ",division ) | Python | zaydzuhri_stack_edu_python |
import gzip
import os
function create_dummy_data input output output_path num_lines
begin
with open input string r as dummy
begin
set dummy_short_list = list comprehension next dummy for x in range num_lines
end
set dummy_short = compress join b'' dummy_short_list
if not exists path output_path
begin
make directories o... | import gzip
import os
def create_dummy_data(input, output,output_path, num_lines):
with gzip.open(input, 'r') as dummy:
dummy_short_list = [next(dummy)for x in range(num_lines)]
dummy_short = gzip.compress(b''.join(dummy_short_list))
if not os.path.exists(output_path):
os.makedirs(... | Python | zaydzuhri_stack_edu_python |
function _check_file_exists self
begin
if exists path string %s/media/dynamic/images/%s % tuple PROJECT_PATH file_path
begin
return true
end
else
begin
set test_path = string
for _dir in split file_path string / at slice : - 1 :
begin
set test_path = test_path + string /%s % _dir
comment Make sure site-directory fol... | def _check_file_exists(self):
if os.path.exists(
"%s/media/dynamic/images/%s" %
(settings.PROJECT_PATH, self.file_path)):
return True
else:
test_path = ''
for _dir in self.file_path.split('/')[:-1]:
test_path += "/%s" % _dir
... | Python | nomic_cornstack_python_v1 |
function argmin x axis=0
begin
set helper = call LayerHelper string arg_min keyword locals
set out = call create_variable_for_type_inference INT64
call append_op type=string arg_min inputs=dict string X x outputs=dict string Out list out attrs=dict string axis axis
return out
end function | def argmin(x, axis=0):
helper = LayerHelper("arg_min", **locals())
out = helper.create_variable_for_type_inference(VarDesc.VarType.INT64)
helper.append_op(
type='arg_min',
inputs={'X': x},
outputs={'Out': [out]},
attrs={'axis': axis})
return out | Python | nomic_cornstack_python_v1 |
for i in range n
begin
append trees list map int split input
end
set flags = list true * trees at - 1 at 0 + 1
set count = 2
for x in trees
begin
set flags at x at 0 = false
end
for i in range 1 length trees - 1
begin
if trees at i at 1 < trees at i at 0 and false not in flags at slice trees at i at 0 - trees at i at 1... | for i in range(n):
trees.append(list(map(int,input().split())))
flags = [True]*(trees[-1][0]+1)
count = 2
for x in trees:
flags[x[0]] = False
for i in range(1,len(trees)-1):
if trees[i][1]<trees[i][0] and False not in flags[trees[i][0]-trees[i][1]:trees[i][0]]:
count+=1
for j in range(trees[... | Python | zaydzuhri_stack_edu_python |
if command == string Even
begin
print sum even_list * length num_list
end
else
begin
print sum odd_list * length num_list
end | if command == 'Even':
print(sum(even_list) * len(num_list))
else:
print(sum(odd_list) * len(num_list))
| Python | zaydzuhri_stack_edu_python |
function test_rate_song_error self main
begin
comment setup
set tuple testapp songService = main
call mockRateSong songService false
comment test
set actual = post string /songs/rating data=dictionary rating=1 song_id=string any
comment verification
assert string <Response streamed [500 INTERNAL SERVER ERROR]> == strin... | def test_rate_song_error(self, main):
# setup
testapp, songService = main
self.mockRateSong(songService, False)
# test
actual = testapp.post('/songs/rating', data=dict(
rating=1,
song_id="any"
))
# verification
assert '<Response str... | Python | nomic_cornstack_python_v1 |
function source_list self
begin
return _source_list
end function | def source_list(self):
return self._source_list | Python | nomic_cornstack_python_v1 |
function add_word self word
begin
set word = lower strip word
if word in builtin_words
begin
return
end
if word not in word_count
begin
set word_count at word = 1
end
else
begin
set word_count at word = word_count at word + 1
end
end function | def add_word(self, word):
word = word.strip().lower()
if word in self.builtin_words:
return
if word not in self.word_count:
self.word_count[word] = 1
else:
self.word_count[word] += 1 | Python | nomic_cornstack_python_v1 |
import pickle
comment import flask
import data
import torch
from torch.utils.data import DataLoader
import pandas as pd
from model import *
import config
comment app = flask.Flask(__name__)
comment model = torch.load("model/rnn.pkl")
comment we have two model for training data: RNN, CNN
function output_sentiment senten... | import pickle
# import flask
import data
import torch
from torch.utils.data import DataLoader
import pandas as pd
from model import *
import config
# app = flask.Flask(__name__)
# model = torch.load("model/rnn.pkl")
# we have two model for training data: RNN, CNN
def output_sentiment(sentence, model, vocab):
"u... | Python | zaydzuhri_stack_edu_python |
import random
import string
set st = random sample ascii_letters 10
print string Cлучайная строка из 10 символов: st | import random
import string
st = random.sample(string.ascii_letters, 10)
print("Cлучайная строка из 10 символов: " , st)
| Python | zaydzuhri_stack_edu_python |
comment Import and Setup
from aoc import *
set DAY = call getDayFromFilepath __file__
set aoc = call AOC DAY
comment Initialization
set result1 = none
set result2 = none
comment Input
set file = call getFile
set area = dict
function a x y
begin
if tuple x y in area
begin
return area at tuple x y
end
return string #
en... | # Import and Setup
from aoc import *
DAY = AOC.getDayFromFilepath(__file__)
aoc = AOC(DAY)
# Initialization
result1 = None
result2 = None
# Input
file = aoc.getFile()
area = {}
def a(x,y):
if((x,y) in area):
return area[(x,y)]
return "#"
def show():
mx, my = [None, None], [None, None]
for k ... | Python | zaydzuhri_stack_edu_python |
string Read Gyro and Accelerometer by Interfacing Raspberry Pi with MPU6050 using Python http://www.electronicwings.com
comment import SMBus module of I2C
import smbus
import math
comment import
from time import sleep , time
comment some MPU6050 Registers and their Address
set PWR_MGMT_1 = 107
set SMPLRT_DIV = 25
set C... | '''
Read Gyro and Accelerometer by Interfacing Raspberry Pi with MPU6050 using Python
http://www.electronicwings.com
'''
import smbus #import SMBus module of I2C
import math
from time import sleep, time #import
#some MPU6050 Registers and their Address
PWR_MGMT_1 = 0x6B
SMPLRT_DIV = 0x19
CONFIG ... | Python | zaydzuhri_stack_edu_python |
string Write a program (using functions!) that asks the user for a long string containing multiple words. Print back to the user the same string, except with the words in backwards order. For example, say I type the string: My name is Michele Then I would see the string: Michele is name My shown back to me.
function re... | """
Write a program (using functions!) that asks the
user for a long string containing multiple words.
Print back to the user the same string, except
with the words in backwards order. For example,
say I type the string:
My name is Michele
Then I would see the string:
Michele is name My
shown back to me.
"""
de... | Python | zaydzuhri_stack_edu_python |
import os
from tkinter import *
from tkinter import messagebox
from Drive import *
from compress_using_zip import *
from typing import Final
from encrypting_file import *
from decrepting_file import *
from sort_using_extention import *
from New_file import *
from Open_a_File import *
from list_dirc import *
from Delete... | import os
from tkinter import *
from tkinter import messagebox
from Drive import *
from compress_using_zip import *
from typing import Final
from encrypting_file import *
from decrepting_file import *
from sort_using_extention import *
from New_file import *
from Open_a_File import *
from list_dirc import *
... | Python | zaydzuhri_stack_edu_python |
string Genetic Algorithm Tuning of a PID controller for offline optimisation of a Mass-Spring-Damper System.
import numpy as np
from scipy.integrate import solve_ivp , RK23 , odeint
from scipy.interpolate import PchipInterpolator
import pylab as pylab
from pylab import plot , xlabel , ylabel , title , legend , figure ,... | """ Genetic Algorithm Tuning of a PID controller
for offline optimisation of a Mass-Spring-Damper System. """
import numpy as np
from scipy.integrate import solve_ivp, RK23, odeint
from scipy.interpolate import PchipInterpolator
import pylab as pylab
from pylab import plot,xlabel,ylabel,title,legend,figure,subplots
i... | Python | zaydzuhri_stack_edu_python |
comment CORES NO TERMINAL CORES NO TERMINAL CORES NO TERMINAL CORES NO TERMINAL CORES NO TERMINAL
comment ('\033[STYLE; TEXT; BACKmOlá mundo!\033[m)
print string -=- * 15
print format string {:=^52} string [1m EXEMPLOS [m
print string -=- * 15
comment Exemplo (Com todos os campos):
print string [0;32mExemplo[m com ... | # CORES NO TERMINAL CORES NO TERMINAL CORES NO TERMINAL CORES NO TERMINAL CORES NO TERMINAL
# ('\033[STYLE; TEXT; BACKmOlá mundo!\033[m)
print('-=-' * 15)
print('{:=^52}'.format('\033[1m EXEMPLOS \033[m'))
print('-=-' * 15)
# Exemplo (Com todos os campos):
print('\033[0;32mExemplo\033[m com todos os campos ... | Python | zaydzuhri_stack_edu_python |
function gallery
begin
return call render string base.html
end function | def gallery():
return render('base.html') | Python | nomic_cornstack_python_v1 |
comment Given an array of N integers. Your task is to print the sum of all of the integers.
comment User function Template for python3
class Solution
begin
function getSum self arr n
begin
comment Your code goes here
return sum arr
end function
end class
comment {
comment Driver Code Starts
comment Initial Template for... | # Given an array of N integers. Your task is to print the sum of all of the integers.
# User function Template for python3
class Solution:
def getSum(self, arr, n):
# Your code goes here
return sum(arr)
# {
# Driver Code Starts
# Initial Template for Python 3
def main():
T = i... | Python | zaydzuhri_stack_edu_python |
function _set_eqns self problem
begin
debug string setting T1_z eqn
call add_equation string dz(T1) - T1_z = 0
debug string Setting energy equation
call add_equation string P*dz(T1_z) = dz(enth_flux_IVP - P*T0_z)
debug string Setting HS equation
call add_equation string dz(p1) - T1 = 0
end function | def _set_eqns(self, problem):
logger.debug('setting T1_z eqn')
problem.add_equation("dz(T1) - T1_z = 0")
logger.debug('Setting energy equation')
problem.add_equation(("P*dz(T1_z) = dz(enth_flux_IVP - P*T0_z)"))
logger.debug('Setting HS equation')
problem.add_equ... | Python | nomic_cornstack_python_v1 |
function pdf_to_png_and_save paper
begin
comment noinspection PyBroadException
try
begin
seek pdf 0 0
set pdf_byte = read pdf
set image = call convert_from_bytes pdf_byte last_page=1 dpi=100 at 0
set png_name = string uuid 4
save png_name string PNG
with open png_name string rb as f
begin
save replace name string .pdf ... | def pdf_to_png_and_save(paper):
# noinspection PyBroadException
try:
paper.pdf.seek(0, 0)
pdf_byte = paper.pdf.read()
image = pdf2image.convert_from_bytes(pdf_byte, last_page=1, dpi=100)[0]
png_name = str(uuid.uuid4())
image.save(png_name, 'PNG')
with open(png_nam... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
set num = count Device
set string = string
set string = string + string %d device(s) found: % num
for i in range num
begin
set string = string + string %d) %s (Id: %d) % tuple i + 1 call name i
set string = string + string Memory: %.2f GB % call total_memory / 1000000000.0
end
return strin... | def __repr__(self):
num = cuda.Device.count()
string = ""
string += ("%d device(s) found:\n"%num)
for i in range(num):
string += ( " %d) %s (Id: %d)\n"%((i+1),cuda.Device(i).name(),i))
string += (" Memory: %.2f GB\n"%(cuda.Device(i).total_memory()/1e9)... | Python | nomic_cornstack_python_v1 |
function new_value self pixel
begin
call new_value red
call new_value green
call new_value blue
call new_value red
call new_value green
call new_value blue
end function | def new_value(self, pixel):
self.color_entropy.new_value(pixel.red)
self.color_entropy.new_value(pixel.green)
self.color_entropy.new_value(pixel.blue)
self.red_entropy.new_value(pixel.red)
self.green_entropy.new_value(pixel.green)
self.blue_entropy.new_value(pixel.blue) | Python | nomic_cornstack_python_v1 |
comment codefights.com drilling the lists, twin score
function twinsScore b m
begin
return list generator expression x + y for tuple x y in zip b m
end function | ### codefights.com drilling the lists, twin score
def twinsScore(b, m):
return list(x + y for x, y in zip(b,m)) | Python | zaydzuhri_stack_edu_python |
function groupby self check_obj
begin
raise NotImplementedError
end function | def groupby(self, check_obj):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function add_argument self argument
begin
if argument
begin
append _arguments argument
end
else
begin
raise call ValueError string argument can not be null
end
end function | def add_argument(self, argument):
if argument:
self._arguments.append(argument)
else:
raise ValueError('argument can not be null') | Python | nomic_cornstack_python_v1 |
function create_optimizer self
begin
set d_optimizer = adam parameters D opti_lr list opti_beta1 opti_beta2
set g_optimizer = adam parameters G opti_lr list opti_beta1 opti_beta2
end function | def create_optimizer(self):
self.d_optimizer = optim.Adam(self.D.parameters(), self.opti_lr, [self.opti_beta1, self.opti_beta2])
self.g_optimizer = optim.Adam(self.G.parameters(), self.opti_lr, [self.opti_beta1, self.opti_beta2]) | Python | nomic_cornstack_python_v1 |
function is_fn self argno argc
begin
set t = arg_types at argno
if not is instance t FunctionType
begin
raise call XlsTypeError span t none format string Want argument {} to be a function; got {} argno t
end
if length params != argc
begin
raise call XlsTypeError span t none format string Want argument {} to be a functi... | def is_fn(self, argno: int, argc: int) -> '_Checker':
t = self.arg_types[argno]
if not isinstance(t, FunctionType):
raise XlsTypeError(
self.span, t, None,
'Want argument {} to be a function; got {}'.format(argno, t))
if len(t.params) != argc:
raise XlsTypeError(
se... | Python | nomic_cornstack_python_v1 |
function test_multiple_date_values self
begin
from dateutil.tz import tzutc
decorator intent_handler
function date_test date
begin
return tuple date
end function
set r = call create_request string TEST_CONTEXT date=list string 2100-12-31 string T13:00:00Z
assert equal tuple call datetime 2100 12 31 0 0 call datetime 21... | def test_multiple_date_values(self):
from dateutil.tz import tzutc
@intent_handler
def date_test(date: [datetime.datetime]):
return tuple(date)
r = create_request("TEST_CONTEXT", date=["2100-12-31", "T13:00:00Z"])
self.assertEqual(
(
date... | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
from Tkinter import *
set root = call Tk
set width = 300
set height = 240
set screenwidth = call winfo_screenwidth
set screenheight = call winfo_screenheight
set size = string %dx%d+%d+%d % tuple width height screenwidth - width / 2 screenheight - height / 2
call geometry size
call minsize 300 240
... | # coding:utf-8
from Tkinter import *
root = Tk()
width = 300
height = 240
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
size='%dx%d+%d+%d' % (width, height, (screenwidth-width)/2,(screenheight-height)/2)
root.geometry(size)
root.minsize(300, 240)
root.maxsize(600, 800)
w1 = Message... | Python | zaydzuhri_stack_edu_python |
comment python3
function compute_prefix p
begin
set s = list 0
set border = 0
for i in range 1 length p
begin
while border > 0 and p at i != p at border
begin
set border = s at border - 1
end
if p at i == p at border
begin
set border = border + 1
end
else
begin
set border = 0
end
append s border
end
return s
end functi... | #python3
def compute_prefix(p):
s = [0]
border = 0
for i in range(1, len(p)):
while border > 0 and p[i] != p[border]:
border = s[border - 1]
if p[i] == p[border]:
border += 1
else:
border = 0
s.append(border)
return s
def find_all_occ(p, T):
n = len(p)
S = p + '$' + T
s = compute_prefix(S)
re... | Python | zaydzuhri_stack_edu_python |
function scan_dir root_dir=b'/'
begin
set subdirs = list
set invalid_subdirs = list
function _create_a_subdir subdir_cls name path
begin
if is link path path
begin
return call subdir_cls name=name target=call readlink path
end
return call subdir_cls name=name
end function
for subdir in list directory root_dir
begin
c... | def scan_dir(root_dir=b'/'):
subdirs = []
invalid_subdirs = []
def _create_a_subdir(subdir_cls, name, path):
if os.path.islink(path):
return subdir_cls(name=name, target=os.readlink(path))
return subdir_cls(name=name)
for subdir in os.listdir(root_dir):
# Note(ivasi... | Python | nomic_cornstack_python_v1 |
import json
import urllib
import argparse
from imposm.parser import OSMParser
string func
class RoadExtractor extends object
begin
set roads = dictionary
set crossings = dictionary
set points = dictionary
function ways self ways
begin
for tuple osmid tags refs in ways
begin
if string highway in tags
begin
if string cro... | import json
import urllib
import argparse
from imposm.parser import OSMParser
'''func
'''
class RoadExtractor(object):
roads = dict()
crossings = dict()
points = dict()
def ways(self, ways):
for osmid, tags, refs in ways:
if 'highway' in tags:
if 'crossing' in tags:
if tags['cross... | Python | zaydzuhri_stack_edu_python |
function _mock_insert_word self word
begin
set ret_id = _mock_next_word_id
set _mock_next_word_id = _mock_next_word_id + 1
return ret_id
end function | def _mock_insert_word(self, word):
ret_id = self._mock_next_word_id
self._mock_next_word_id += 1
return ret_id | Python | nomic_cornstack_python_v1 |
function display_route self point1 point2
begin
set route = call get_route point1 point2
if route is none
begin
call output string No routes from point1 string to point2
end
else
begin
call output string Your trip from point1 string to point2 string includes route at string length - 1 string stops and will take route a... | def display_route(self, point1, point2):
route = self.router.get_route(point1, point2)
if route is None:
self.output('No routes from', point1, 'to', point2)
else:
self.output(
'Your trip from',
point1,
'to',
... | Python | nomic_cornstack_python_v1 |
comment !usr/bin/env python3
import hashlib
set db = dict string michael string e10adc3949ba59abbe56e057f20f883e ; string bob string 878ef96e86145580c38c87f0410ad153 ; string alice string 99b1c2188db85afee403b1536010c2c9
function calc_md5 password
begin
set md5 = md5
update md5 encode password string utf-8
print hex di... | #!usr/bin/env python3
import hashlib
db={
'michael':'e10adc3949ba59abbe56e057f20f883e',
'bob':'878ef96e86145580c38c87f0410ad153',
'alice':'99b1c2188db85afee403b1536010c2c9'
}
def calc_md5(password):
md5=hashlib.md5()
md5.update(password.encode('utf-8'))
print(md5.hexdigest())
return md5.hexd... | Python | zaydzuhri_stack_edu_python |
function _load_config self
begin
string load configuration from config/
debug string Listing per-account config subdirectories in %s _conf_dir
for acct_id in list directory _conf_dir
begin
set path = join path _conf_dir acct_id
comment skip if not a directory
if not is directory path path
begin
continue
end
comment ski... | def _load_config(self):
"""load configuration from config/"""
logger.debug(
'Listing per-account config subdirectories in %s', self._conf_dir
)
for acct_id in os.listdir(self._conf_dir):
path = os.path.join(self._conf_dir, acct_id)
# skip if not a dire... | Python | jtatman_500k |
import random
import turtle
set q = call Turtle
call speed 0
call colormode 255
call penup
call hideturtle
set dots_size = 20
set space_between = 50
set board_size = tuple 10 10
set colors1 = list list 245 243 238 list 246 242 244 list 202 164 110 list 240 245 241 list 236 239 243 list 149 75 50 list 222 201 136 list 5... | import random
import turtle
q = turtle.Turtle()
q.speed(0)
turtle.colormode(255)
q.penup()
q.hideturtle()
dots_size = 20
space_between = 50
board_size = (10, 10)
colors1 = [[245, 243, 238], [246, 242, 244],
[202, 164, 110], [240, 245, 241],
[236, 239, 243], [149, 75, 50],
... | Python | zaydzuhri_stack_edu_python |
function __init__ self treeView allActions isChildView=true parent=none
begin
call __init__ 0 2 parent
set treeView = treeView
set allActions = allActions
set isChildView = isChildView
set hideChildView = not genOptions at string InitShowChildPane
set prevHoverCell = none
set inLinkSelectActive = false
call setAcceptDr... | def __init__(self, treeView, allActions, isChildView=True,
parent=None):
super().__init__(0, 2, parent)
self.treeView = treeView
self.allActions = allActions
self.isChildView = isChildView
self.hideChildView = not globalref.genOptions['InitShowChildPane']
... | Python | nomic_cornstack_python_v1 |
function testSimpleAcquire self
begin
call _TryAcquire string my string 1234
call _TryAcquire string my string !@#%!@#$ resource_data=string some data
call _TryAcquire string my string 12-34 resource_data=string the quick brown fox jumped over the lazy dog detect_abandonment=true
end function | def testSimpleAcquire(self):
self._TryAcquire('my', '1234')
self._TryAcquire('my', '!@#%!@#$', resource_data='some data')
self._TryAcquire('my', '12-34', resource_data='the quick brown fox jumped over the lazy dog',
detect_abandonment=True) | 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.