code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Problem G
set num = input
set num_list = list
for i in range length num
begin
append num_list integer num at i
end
set myMod = 10 ^ 9 + 7
set length = length num_list
set f = list 0 * length + 1
set t = list 1 * length + 1
for i in range length
begin
set f at i + 1 = f at i * 10 + 1 % myMod
set t at i + 1 = t ... | # Problem G
num = input()
num_list = []
for i in range(len(num)):
num_list.append(int(num[i]))
myMod = (10 ** 9) + 7
length = len(num_list)
f = [0] * (length + 1)
t = [1] * (length + 1)
for i in range(length):
f[i+1] = (f[i] * 10 + 1) % myMod
t[i+1] = (t[i] * 10) % myMod
ans = 0
for i in range(1, 10):
dp... | Python | jtatman_500k |
function attention query key value casual_mask masked_bias dropout scale_attn_weights rng training attn_mask=none head_mask=none
begin
set query = as type query float32
set key = as type key float32
set attn_weights = matrix multiply query call swapaxes key - 1 - 2
if scale_attn_weights
begin
set attn_weights = attn_we... | def attention(query, key, value, casual_mask, masked_bias, dropout, scale_attn_weights, rng, training, attn_mask=None, head_mask=None):
query = query.astype(jnp.float32)
key = key.astype(jnp.float32)
attn_weights = jnp.matmul(query, jnp.swapaxes(key, -1, -2))
if scale_attn_weights:
attn_wei... | Python | nomic_cornstack_python_v1 |
function is_valid_number input_value
begin
try
begin
set number = integer input_value
return true
end
except ValueError
begin
return false
end
end function
function is_prime number
begin
if number < 2
begin
return false
end
for i in range 2 integer number ^ 0.5 + 1
begin
if number % i == 0
begin
return false
end
end
re... | def is_valid_number(input_value):
try:
number = int(input_value)
return True
except ValueError:
return False
def is_prime(number):
if number < 2:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
w... | Python | jtatman_500k |
function Hanoi n x y
begin
if n > 0
begin
call Hanoi n - 1 x y
print n x 2
call Hanoi n - 1 y x
print n 2 y
call Hanoi n - 1 y x
call Hanoi n - 1 x y
end
return tuple n x y
end function
set n = input
print call Hanoi n 1 3 | def Hanoi(n, x, y):
if n > 0:
Hanoi(n - 1, x, y)
print(n, x, 2)
Hanoi(n - 1, y, x)
print(n, 2, y)
Hanoi(n - 1, y, x)
Hanoi(n - 1, x, y)
return (n, x, y)
n = input()
print(Hanoi(n, 1, 3))
| Python | zaydzuhri_stack_edu_python |
if length A == 2
begin
set ans = string Yes
end
print ans | if len(A) == 2:
ans='Yes'
print(ans) | Python | zaydzuhri_stack_edu_python |
from collections import Counter , OrderedDict , defaultdict
from itertools import permutations , product
import math
import logging
from datetime import datetime
import os
from joblib import Parallel , delayed
import multiprocessing.dummy as mp
import numpy as np
from tqdm.auto import tqdm
import threading
set threadLo... | from collections import Counter, OrderedDict, defaultdict
from itertools import permutations, product
import math
import logging
from datetime import datetime
import os
from joblib import Parallel, delayed
import multiprocessing.dummy as mp
import numpy as np
from tqdm.auto import tqdm
import threading
threadLock = th... | Python | zaydzuhri_stack_edu_python |
function type self
begin
return get pulumi self string type
end function | def type(self) -> str:
return pulumi.get(self, "type") | Python | nomic_cornstack_python_v1 |
function __set__ self obj value
begin
pass
end function | def __set__(self, obj, value):
pass | Python | nomic_cornstack_python_v1 |
import json
import requests
import pandas as pd
import matplotlib.pyplot as plt
comment Got url from data.gov.in
set url = string https://api.data.gov.in/resource/9ef84268-d588-465a-a308-a864a43d0070?api-key=579b464db66ec23bdd000001cdd3946e44ce4aad7209ff7b23ac571b&format=json&offset=0&limit=1000
comment Requesting the ... | import json
import requests
import pandas as pd
import matplotlib.pyplot as plt
#Got url from data.gov.in
url = "https://api.data.gov.in/resource/9ef84268-d588-465a-a308-a864a43d0070?api-key=579b464db66ec23bdd000001cdd3946e44ce4aad7209ff7b23ac571b&format=json&offset=0&limit=1000"
#Requesting the server using GET type... | Python | zaydzuhri_stack_edu_python |
function generate_subkeys key
begin
set key = call P10 key
set key = call left_shift key ? 5 ? 5 + call left_shift key ? 31
set K1 = call P8 key
set key = call left_shift key ? 5 ? 5 + call left_shift key ? 31
set key = call left_shift key ? 5 ? 5 + call left_shift key ? 31
set K2 = call P8 key
return tuple K1 K2
end f... | def generate_subkeys(key):
key = P10(key)
key = ( left_shift(key >> 5) << 5 ) + ( left_shift(key & 0b11111) )
K1 = P8(key)
key = ( left_shift(key >> 5) << 5 ) + ( left_shift(key & 0b11111) )
key = ( left_shift(key >> 5) << 5 ) + ( left_shift(key & 0b11111) )
K2 = P8(key)
return (K1, K2) | Python | nomic_cornstack_python_v1 |
function test_delete_rule self
begin
pass
end function | def test_delete_rule(self):
pass | Python | nomic_cornstack_python_v1 |
function cluster embedding_matrix valid_chars
begin
info string Begin clustering
comment Predict cluster labels
set kmeans_model = fit k means n_clusters=6 embedding_matrix
set labels = predict kmeans_model embedding_matrix
comment Save to dataframe
set archetypes = sort values call DataFrame dict string Name valid_cha... | def cluster(embedding_matrix, valid_chars):
logging.info('Begin clustering')
# Predict cluster labels
kmeans_model = KMeans(n_clusters=6).fit(embedding_matrix)
labels = kmeans_model.predict(embedding_matrix)
# Save to dataframe
archetypes = pd.DataFrame({'Name': valid_chars,
... | Python | nomic_cornstack_python_v1 |
function test_position_management_page client auth
begin
from grad_fellow.admin.webconsole.position import block_title , url_prefix
set response = call get_page client auth url_prefix + string /
assert status_code == 200
assert block_title in string data
end function | def test_position_management_page(client, auth):
from grad_fellow.admin.webconsole.position import block_title, url_prefix
response = get_page(client, auth, url_prefix + '/')
assert response.status_code == 200
assert block_title in str(response.data) | Python | nomic_cornstack_python_v1 |
comment List of ball colors inside a box
set ball_colors = list string blue string blue string red string green string green string purple string white
comment Removing duplicates
set colors = list *{*ball_colors} | #List of ball colors inside a box
ball_colors = ['blue','blue','red','green','green','purple','white']
#Removing duplicates
colors = [*{*ball_colors}] | Python | zaydzuhri_stack_edu_python |
for item in a
begin
if item == 100
begin
set studs = studs + 1
end
end
set a = list comprehension x for x in a if x != 100
set mods = list comprehension tuple x % 10 i for tuple i x in enumerate a
sort mods reverse=true
for item in mods
begin
if k <= 0
begin
break
end
set old_a_item = a at item at 1
set a at item at 1 ... | for item in a:
if item == 100:
studs += 1
a = [x for x in a if x != 100]
mods = [(x % 10, i) for i, x in enumerate(a)]
mods.sort(reverse=True)
for item in mods:
if k <= 0:
break
old_a_item = a[item[1]]
a[item[1]] += min(k, 10 - item[0])
k -= min(k, 10 - item[0])
if a[item[1]] /... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Thu Sep 15 11:20:23 2016 @author: Justin
import numpy as np
comment Load
comment read_dictionary = np.load('my_file.npy').item()
comment print(read_dictionary['hello']) # displays "world" | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 15 11:20:23 2016
@author: Justin
"""
import numpy as np
## Load
#read_dictionary = np.load('my_file.npy').item()
#print(read_dictionary['hello']) # displays "world" | Python | zaydzuhri_stack_edu_python |
import sys
import os
from PIL import Image
import shutil
function generateCoronal blankDir genSize refFileNames
begin
print string Generating coronal images in %s % blankDir
for tuple root dirs files in walk blankDir
begin
comment i is 256
for i in range 0 length files
begin
set fn = root + string / + files at i
set im... | import sys
import os
from PIL import Image
import shutil
def generateCoronal(blankDir, genSize, refFileNames):
print("Generating coronal images in %s"%(blankDir))
for root, dirs, files in os.walk(blankDir):
for i in range(0, len(files)): # i is 256
fn = root + "/" + files[i]
... | Python | zaydzuhri_stack_edu_python |
function sine x
begin
if absolute x < 0.0001
begin
return x
end
else
begin
return 3 * call sine x / 3 - 4 * power call sine x / 3 3
end
end function | def sine(x):
if abs(x) < 0.0001:
return x
else:
return 3 * sine(x / 3) - 4 * pow(sine(x / 3), 3) | Python | nomic_cornstack_python_v1 |
from numpy import *
set arr = linear space 0 16
set arr1 = linear space 0 15 10
print arr dtype
print arr1 dtype | from numpy import *
arr = linspace(0,16)
arr1 = linspace(0, 15, 10)
print(arr, arr.dtype)
print(arr1, arr.dtype) | Python | zaydzuhri_stack_edu_python |
function removeRepeats inputString
begin
set seen = list
for x in call xrange length inputString
begin
if inputString at x not in seen
begin
append seen inputString at x
end
else
begin
continue
end
end
return seen
end function
set a = string abba | def removeRepeats(inputString):
seen = []
for x in xrange(len(inputString)):
if inputString[x] not in seen:
seen.append(inputString[x])
else:
continue
return seen
a = "abba" | Python | zaydzuhri_stack_edu_python |
function has_been_published self
begin
if is_published
begin
return true
end
else
if is_draft
begin
return publishing_linked_id is not none
end
comment pragma: no cover
raise call ValueError string Publishable object %r is neither draft nor published % self
end function | def has_been_published(self):
if self.is_published:
return True
elif self.is_draft:
return self.publishing_linked_id is not None
raise ValueError( # pragma: no cover
"Publishable object %r is neither draft nor published" % self) | Python | nomic_cornstack_python_v1 |
function pair_correlation_function_3D x y z S rMax dr
begin
from numpy import zeros , sqrt , where , pi , mean , arange , histogram
comment Find particles which are close enough to the cube center that a sphere of radius
comment rMax will not cross any face of the cube
set bools1 = x > rMax
set bools2 = x < S - rMax
se... | def pair_correlation_function_3D(x, y, z, S, rMax, dr):
from numpy import zeros, sqrt, where, pi, mean, arange, histogram
# Find particles which are close enough to the cube center that a sphere of radius
# rMax will not cross any face of the cube
bools1 = x > rMax
bools2 = x < (S - rMax)
bools... | Python | nomic_cornstack_python_v1 |
function _get_subfeeds_from_yaml self fname=none
begin
if fname is none
begin
set this_dir = directory name path real path path __file__
set fname = join path this_dir string ../gtfs-sources.yaml
end
set data = load yaml open fname
set sites = data at string sites
set location_to_subfeeds = dict
for tuple feed_name da... | def _get_subfeeds_from_yaml(self, fname=None):
if fname is None:
this_dir = os.path.dirname(os.path.realpath(__file__))
fname = os.path.join(this_dir, "../gtfs-sources.yaml")
data = yaml.load(open(fname))
sites = data['sites']
location_to_subfeeds = {}
fo... | Python | nomic_cornstack_python_v1 |
function make_epoch_batches self batch_size max_snapshot_size max_chrono_length limit=none delta_encoder=none
begin
if not delta_encoder
begin
set delta_encoder = call TanhLogDeltaEncoder
end
comment Shuffle chronologies
set chronologies = call permutation call chronologies
comment Determine the number of batches we wi... | def make_epoch_batches(self, batch_size, max_snapshot_size, max_chrono_length, limit=None,
delta_encoder=None):
if not delta_encoder:
delta_encoder = TanhLogDeltaEncoder()
# Shuffle chronologies
chronologies = np.random.permutation(self.chronologies())
... | Python | nomic_cornstack_python_v1 |
import pyautogui as AI
call hotkey string winleft string up | import pyautogui as AI
AI.hotkey('winleft', 'up')
| Python | flytech_python_25k |
import random
import matplotlib.pyplot as plt
import numpy as np
function bubble_sort rand_list
begin
set not_done = true
set fig = figure
set ax1 = call add_subplot 1 1 1
while not_done
begin
set not_done = false
set index = array range length rand_list
set v = 0
for tuple i value in enumerate rand_list
begin
if i == ... | import random
import matplotlib.pyplot as plt
import numpy as np
def bubble_sort(rand_list):
not_done = True
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
while not_done:
not_done = False
index = np.arange(len(rand_list))
v=0
for i,value in enumerate(ra... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from __future__ import unicode_literals
import scrapy
import datetime , os , re
import xlrd
from financecrawl.items import RongziItem , RongziMingxiItem
from dateutil import parser
from financecrawl.dataModels import get_max_trading_date , Financing , get_previous_trading_date , get_next_t... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import scrapy
import datetime, os, re
import xlrd
from financecrawl.items import RongziItem, RongziMingxiItem
from dateutil import parser
from financecrawl.dataModels import get_max_trading_date, Financing, get_previous_trading_date, get_next_trading_date... | Python | zaydzuhri_stack_edu_python |
function bytes2human size precision=2 max_unit=string TB
begin
string Parameters: size: Size in bytes (integer). precision: Convert floating point number to a certain precision. max_unit: Specify the max unit. e.g. 'MB' Returns: (size, unit), tuple format. e.g. (1.0, 'GB')
set suffixes = list string B string KB string ... | def bytes2human(size, precision=2, max_unit='TB'):
"""
Parameters:
size: Size in bytes (integer).
precision: Convert floating point number to a certain precision.
max_unit: Specify the max unit. e.g. 'MB'
Returns:
(size, unit), tuple format. e.g. (1.0, 'GB')
"""
suffi... | Python | zaydzuhri_stack_edu_python |
function test_bad_file self mock_input_folder
begin
set return_value = list non_existant_file
comment NB Can pass in None as input_folder is patched
assert raises FileNotFoundError run_analysis_pipeline none
end function | def test_bad_file(self, mock_input_folder):
mock_input_folder.return_value = [self.non_existant_file]
# NB Can pass in None as input_folder is patched
self.assertRaises(FileNotFoundError, main.run_analysis_pipeline, None) | Python | nomic_cornstack_python_v1 |
function HttpGet host
begin
comment Assume unencrypted.
set protocol = string http://
if string :// in host
begin
set parts = split host string ://
set tuple protocol host = parts
end
if protocol == string https
begin
set conn = call HTTPSConnection host timeout=1
end
else
begin
set conn = call HTTPConnection host time... | def HttpGet(host):
protocol = 'http://' # Assume unencrypted.
if '://' in host:
parts = host.split('://')
protocol, host = parts
if protocol == 'https':
conn = httplib.HTTPSConnection(host, timeout=1)
else:
conn = httplib.HTTPConnection(host, timeout=1) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Mon Jul 29 11:44:09 2019 标准库之Tkinter:创建GUI程序 @author: 10841
from tkinter import *
comment 若没有Tk实例,则创建控件时会创建Tk实例
set btn = call Button
comment 创建控件后需要使用布局管理器设置控件位置,否则控件不可见
call pack
comment 通过控件属性来修改外观和行为
set btn at string text = string Click me!
function clicked
begin
pri... | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 29 11:44:09 2019
标准库之Tkinter:创建GUI程序
@author: 10841
"""
from tkinter import *
btn = Button() # 若没有Tk实例,则创建控件时会创建Tk实例
btn.pack() # 创建控件后需要使用布局管理器设置控件位置,否则控件不可见
btn['text'] = 'Click me!' # 通过控件属性来修改外观和行为
def clicked():
print("I was clicked!")
btn['command'] = clicked ... | Python | zaydzuhri_stack_edu_python |
import threading
import time
class Ultrasonic extends Thread
begin
function __init__ self pin_trig pin_echo gpio
begin
call __init__
set trigPin = pin_trig
set echoPin = pin_echo
set gpio = gpio
set distance = 0
set run_flag = true
call setmode BCM
setup gpio trigPin OUT initial=LOW
setup gpio echoPin IN
print string 초... | import threading
import time
class Ultrasonic(threading.Thread):
def __init__(self, pin_trig, pin_echo, gpio):
super().__init__()
self.trigPin = pin_trig
self.echoPin = pin_echo
self.gpio = gpio
self.distance = 0
self.run_flag = True
self.gpio.setmode(gpio.B... | Python | zaydzuhri_stack_edu_python |
for _ in range n
begin
set tuple w v = map int split input
for x in range W - w - 1 - 1
begin
if dp at x > 0
begin
set dp at x + w = max dp at x + w dp at x + v
end
end
if dp at w == 0
begin
set dp at w = v
end
end
print max dp | for _ in range(n):
w, v = map(int, input().split())
for x in range(W - w, -1, -1):
if dp[x] > 0:
dp[x + w] = max(dp[x + w], dp[x] + v)
if dp[w] == 0:
dp[w] = v
print(max(dp)) | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon May 15 23:57:15 2017 @author: Aadila
import numpy as np
comment should we add offset, amp etc?
function sim_lorentzian t a=1 b=1 c=0
begin
set dat = a / b + t - c ^ 2
set dat = dat + randn size
return dat
end function
comment class Lorentzian:
comment def __init__(sel... | # -*- coding: utf-8 -*-
"""
Created on Mon May 15 23:57:15 2017
@author: Aadila
"""
import numpy as np
def sim_lorentzian(t,a=1,b=1,c=0): #should we add offset, amp etc?
dat=a/(b+(t-c)**2)
dat+=np.random.randn(t.size)
return dat
#class Lorentzian:
# def __init__(self, t,a=1,b=1... | Python | zaydzuhri_stack_edu_python |
function getcode self
begin
set url = tuple url at 0 call parse_query_string url at 1 url at 2
comment type: ignore[no-untyped-call]
set recipient_variable_0 = url at 1 at string recipient_variables at 0
comment Letting mypy know that the variable is of type str.
assert is instance recipient_variable_0 str
set url at 1... | def getcode(self) -> int:
self.url = (
self.url[0],
python_utils.parse_query_string(self.url[1]), # type: ignore[no-untyped-call]
self.url[2],
)
recipient_variable_0 = self.url[1]['recipient_variables'][0]
# Letting mypy kno... | Python | nomic_cornstack_python_v1 |
from itertools import starmap
function parse s
begin
set list r c pw = split s
return tuple tuple map int split r string - c at 0 pw
end function
function check ixs c pw
begin
return integer pw at ixs at 0 - 1 == c != pw at ixs at 1 - 1 == c
end function
with open string 2.txt as f
begin
print sum call starmap check ma... | from itertools import starmap
def parse(s):
[r, c, pw] = s.split()
return tuple(map(int, r.split('-'))), c[0], pw
def check(ixs, c, pw):
return int((pw[ixs[0]-1] == c) != (pw[ixs[1]-1] == c))
with open('2.txt') as f:
print(sum(starmap(check, map(parse, f))))
| Python | zaydzuhri_stack_edu_python |
from intvm import Intcode
function load
begin
with open string input/9 as f
begin
return read f
end
end function
function parse data
begin
return list comprehension integer d for d in split data string ,
end function
set ex1 = list 109 1 204 - 1 1001 100 1 100 1008 100 16 101 1006 101 0 99
set ex2 = list 1102 34915192 ... | from intvm import Intcode
def load():
with open('input/9') as f:
return f.read()
def parse(data):
return [int(d) for d in data.split(',')]
ex1 = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99]
ex2 = [1102,34915192,34915192,7,4,7,99,0]
ex3 = [104,1125899906842624,99]
vm = Intcode(parse(lo... | Python | zaydzuhri_stack_edu_python |
function cdecl inp
begin
set query_url = call get_cdecl_query_url
if not query_url
begin
return string cannot find CDECL query url
end
return get http query_url q=inp
end function | def cdecl(inp):
query_url = get_cdecl_query_url()
if not query_url:
return "cannot find CDECL query url"
return http.get(query_url, q=inp) | Python | nomic_cornstack_python_v1 |
function test_update_raises_if_json_parsing_fails
begin
set request = call Mock
comment Make accessing the request.json_body property raise ValueError.
set json_body = call PropertyMock side_effect=ValueError
with raises PayloadError
begin
update views call Mock request
end
end function | def test_update_raises_if_json_parsing_fails():
request = mock.Mock()
# Make accessing the request.json_body property raise ValueError.
type(request).json_body = mock.PropertyMock(side_effect=ValueError)
with pytest.raises(views.PayloadError):
views.update(mock.Mock(), request) | Python | nomic_cornstack_python_v1 |
function _GetQuickLog namespace key
begin
set namespaced_key = string %s__%s % tuple namespace key
set key = call Key string QuickLog namespaced_key
return get key
end function | def _GetQuickLog(namespace, key):
namespaced_key = '%s__%s' % (namespace, key)
key = ndb.Key('QuickLog', namespaced_key)
return key.get() | Python | nomic_cornstack_python_v1 |
function _step self w state action
begin
return step envs at w action
end function | def _step(self, w, state, action):
return self.envs[w].step(action) | Python | nomic_cornstack_python_v1 |
for t in range integer input
begin
set tuple battle p dp = tuple integer input decimal input list
for i in range battle + 1
begin
append dp copy list 0 * battle + 1
end
set dp at 0 at 0 = 1
for i in range battle + 1
begin
for j in range battle + 1
begin
if i > 0 and j < battle
begin
set dp at i at j = dp at i at j + p... | for t in range( int( input() ) ):
battle, p, dp = int( input() ), float( input() ), []
for i in range( battle + 1 ):
dp.append( ( [ 0 ] * ( battle + 1 ) ).copy() )
dp[ 0 ][ 0 ] = 1
for i in range( battle + 1 ):
for j in range( battle + 1 ):
if i > 0 and j < battle:
... | Python | zaydzuhri_stack_edu_python |
from ex059_calculadora import somar , subtrair , multiplicar , dividir , divisaoInt , exponenciacao , maior , menor
from validadores import leiaInt
set opcao = string
print string [1;33m<----------<<< CALCULADORA V.3.0 >>>-------------->[m
set numero1 = call leiaInt string Número 1:
set numero2 = call leiaInt string... | from ex059_calculadora import somar, subtrair, multiplicar, dividir, divisaoInt, exponenciacao, maior, menor
from validadores import leiaInt
opcao = ''
print('\033[1;33m<----------<<< CALCULADORA V.3.0 >>>-------------->\033[m')
numero1 = leiaInt('Número 1: ')
numero2 = leiaInt('Número 2: ')
while opcao != '10':
... | Python | zaydzuhri_stack_edu_python |
set i = 5
print i
set i = i + 1
print i | i = 5
print (i)
i = i + 1
print (i) | Python | zaydzuhri_stack_edu_python |
import numpy as np
import os
import _pickle as cPickle
from matplotlib import pyplot as plt
class CifarLoader extends object
begin
function __init__ self source_files
begin
set _source = source_files
set _i = 0
set images = none
set labels = none
end function
function load self
begin
set data = list comprehension call ... | import numpy as np
import os
import _pickle as cPickle
from matplotlib import pyplot as plt
class CifarLoader(object):
def __init__(self, source_files):
self._source = source_files
self._i = 0
self.images = None
self.labels = None
def load(self):
data = [unpickl... | Python | zaydzuhri_stack_edu_python |
function getUcarAffiliation self
begin
return call getAffiliation string University Corporation for Atmospheric Research (UCAR)
end function | def getUcarAffiliation (self):
return self.getAffiliation('University Corporation for Atmospheric Research (UCAR)') | Python | nomic_cornstack_python_v1 |
import codecs
import re
comment Create email regex.
set email_regex = compile string ( [a-zA-Z0-9._%+-]+ # username @ # @ symbol [a-zA-Z0-9.-]+ # domain name (\.[a-zA-Z]{2,4}){1,2} # dot-something ) VERBOSE
function extract_text_from_subtitle file_name
begin
set sub_title_contents = list
comment file = codecs.open("D:... | import codecs
import re
# Create email regex.
email_regex = re.compile(r'''(
[a-zA-Z0-9._%+-]+ # username
@ # @ symbol
[a-zA-Z0-9.-]+ # domain name
(\.[a-zA-Z]{2,4}){1,2} # dot-something
)''', re.VERBOSE)
def extract_text_from_subtitle(file_name):
sub_title_contents = []
# file = codecs.open("D:\... | Python | zaydzuhri_stack_edu_python |
function add self x y
begin
return x + y
end function | def add(self, x, y):
return x + y | Python | nomic_cornstack_python_v1 |
import httplib2
from simplejson import dumps as jsondumps
from werkzeug.exceptions import HTTPException , BadRequest , abort
from flask import current_app
from invenio.config import CFG_EPIC_USERNAME
from invenio.config import CFG_EPIC_PASSWORD
from invenio.config import CFG_EPIC_BASEURL
from invenio.config import CFG_... | import httplib2
from simplejson import dumps as jsondumps
from werkzeug.exceptions import HTTPException, BadRequest, abort
from flask import current_app
from invenio.config import CFG_EPIC_USERNAME
from invenio.config import CFG_EPIC_PASSWORD
from invenio.config import CFG_EPIC_BASEURL
from invenio.config import CFG_E... | Python | zaydzuhri_stack_edu_python |
function make_diff file_before file_after file_output_name
begin
if exists path file_output_name
begin
remove tree file_output_name
end
make directory os file_output_name
set psd_diff = diff file_before file_after
set diff_content = dict
for attr in list string header string layer
begin
set diff_content at attr = get ... | def make_diff(file_before, file_after, file_output_name):
if os.path.exists(file_output_name):
shutil.rmtree(file_output_name)
os.mkdir(file_output_name)
psd_diff = diff(file_before, file_after)
diff_content = {}
for attr in ["header", "layer"]:
diff_content[attr] = getattr(psd_diff,... | Python | nomic_cornstack_python_v1 |
from tkinter import *
comment Window
set root = call Tk
title root string Calculator
call geometry string 312x324
call resizable 0 0
comment Click Function
function click_btn item
begin
global expression
set expression = expression + string item
set expression
end function
comment Clear Function
function clear_btn
begi... | from tkinter import *
# Window
root = Tk()
root.title("Calculator")
root.geometry("312x324")
root.resizable(0, 0)
# Click Function
def click_btn(item):
global expression
expression = expression + str(item)
input_text.set(expression)
# Clear Function
def clear_btn():
global expression
expression... | Python | zaydzuhri_stack_edu_python |
import itertools as zz
comment выводит каждый аргумент с новой строки
for item in chain list 1 2 list string a string b
begin
print item
end
comment for it in zz.cycle([1, 2, 3]): # бесконечный итератор проходит по кругу по всем аргументам
comment print(it)
comment for kalk in zz.accumulate([1,3,5,7,9]): #Выводит пооче... | import itertools as zz
for item in zz.chain([1, 2], ['a', 'b']): #выводит каждый аргумент с новой строки
print(item)
#for it in zz.cycle([1, 2, 3]): # бесконечный итератор проходит по кругу по всем аргументам
#print(it)
#for kalk in zz.accumulate([1,3,5,7,9]): #Выводит поочередно каждый аргумент прибавляя ... | Python | zaydzuhri_stack_edu_python |
function rotate_point_cloud_by_angle self data rotation_angle
begin
set cosval = cos rotation_angle
set sinval = sin rotation_angle
set rotation_matrix = array list list cosval 0 sinval list 0 1 0 list - sinval 0 cosval
set rotated_data = dot data rotation_matrix
return rotated_data
end function | def rotate_point_cloud_by_angle(self, data, rotation_angle):
cosval = np.cos(rotation_angle)
sinval = np.sin(rotation_angle)
rotation_matrix = np.array([[cosval, 0, sinval],
[0, 1, 0],
[-sinval, 0, cosval]])
rotated_... | Python | nomic_cornstack_python_v1 |
function unpooling_zero_neighbours self updates dim
begin
set updates_shape = call shape updates
set shape = stack list 1 dim at 0 dim at 1 updates_shape at 3
set N = updates_shape at 1
set M = updates_shape at 2
set axis1 = call tile 2 * range N list M
set axis1 = reshape tf axis1 list M N
set axis1 = transpose tf axi... | def unpooling_zero_neighbours(self, updates, dim):
updates_shape = tf.shape(updates)
shape = tf.stack([1, dim[0], dim[1], updates_shape[3]])
N = updates_shape[1]
M = updates_shape[2]
axis1 = tf.tile(2*tf.range(N), [M])
axis1 = tf.reshape(axis1, [M,N])
axis1 = tf.transpose(axis1)
axis1 = tf.reshape(axis... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Jan 17, 2014 @author: alex
from mlbench import util
set info = dict string url string http://archive.ics.uci.edu/ml/datasets/Thyroid+Disease ; string name string Thyroid Disease ; string key string thyroid ; string y_type string enum ; string x_type none ; string preproce... | # -*- coding: utf-8 -*-
'''
Created on Jan 17, 2014
@author: alex
'''
from mlbench import util
info = {
"url" : "http://archive.ics.uci.edu/ml/datasets/Thyroid+Disease", # url of a web page for the dataset
"name": "Thyroid Disease", # full name of the dataset
"key":"thyroid", # short name of the dataset... | Python | zaydzuhri_stack_edu_python |
string Написал своими словами, чтоб было видно моё понимание о замыкание.
print string Замыкание - это функция, которая передала ссылку на свой обьект - другой переменной вне тела функции. Таким образом эта функция остаётся "живой" после завершения работы функции в которую она вложена.
function outer
begin
string Функц... | """ Написал своими словами, чтоб было видно моё понимание о замыкание. """
print("""
Замыкание - это функция, которая передала ссылку на свой обьект - другой
переменной вне тела функции. Таким образом эта функция остаётся "живой"
после завершения работы функции в которую она вложена.
""")
def outer():
""" Функция ... | Python | zaydzuhri_stack_edu_python |
function test_input_dish_size_floating_point self bp pp
begin
comment Edit dish size with a floating point number.
call show_env_settings
call edit_dish_cols string 10.5
call hide_env_settings
assert call check_size_cells_error
comment Add an organism to the experiment and try to run it.
call add_ancestor_to_dish
call ... | def test_input_dish_size_floating_point(self,
bp: BasePage,
pp: PopulationPage):
# Edit dish size with a floating point number.
pp.show_env_settings()
pp.edit_dish_cols("10.5")
pp.hide_env_settings()
assert pp.c... | Python | nomic_cornstack_python_v1 |
function get_resolution self
begin
return _resolution
end function | def get_resolution(self):
return self._resolution | Python | nomic_cornstack_python_v1 |
function _state_container_list_name self
begin
return _name_lower_plural
end function | def _state_container_list_name(self):
return self._name_lower_plural | Python | nomic_cornstack_python_v1 |
if u == s
begin
print format string {0} {1} a - 1 b
end
else
begin
print format string {0} {1} a b - 1
end | if u==s:
print("{0} {1}".format(a-1,b))
else:
print("{0} {1}".format(a,b-1)) | Python | zaydzuhri_stack_edu_python |
function shift_first_arrival self
begin
raise NotImplemented
end function | def shift_first_arrival(self) -> Optional[Arrival]:
raise NotImplemented | Python | nomic_cornstack_python_v1 |
from PIL import Image , ImageDraw
import threading
class maximineImageCreator
begin
function __init__ self width height directory
begin
set imageWidth = width
set imageHeight = height
set __coreColores = list string #e6194b string #3cb44b string #ffe119 string #4363d8 string #f58231 string #911eb4 string #46f0f0 string... | from PIL import Image, ImageDraw
import threading
class maximineImageCreator:
def __init__(self, width, height, directory):
self.imageWidth = width
self.imageHeight = height
self.__coreColores = ['#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf6... | Python | zaydzuhri_stack_edu_python |
comment Importing Libraries & Data
import pandas as pd
set train = read csv string C:/Users/17708/Documents/R/MLProject_train (1).csv
set valid = read csv string C:/Users/17708/Documents/R/MLProject_valid.csv
set test = read csv string C:/Users/17708/Documents/R/MLProject_test (1).csv
comment Make Z2 Numerical instead ... | #Importing Libraries & Data
import pandas as pd
train = pd.read_csv('C:/Users/17708/Documents/R/MLProject_train (1).csv')
valid = pd.read_csv('C:/Users/17708/Documents/R/MLProject_valid.csv')
test = pd.read_csv('C:/Users/17708/Documents/R/MLProject_test (1).csv')
#Make Z2 Numerical instead of a string
train["Z2"] = p... | Python | zaydzuhri_stack_edu_python |
comment Aims to push all heavy elements in the right side and lighier to the extreme left.
comment Best case : Ω(n)
comment Worst case : O(n^2)
function main
begin
comment array takes in space separated numbers from the user
set array = list map int split strip input string Enter the numbers separated with space: strin... | # Aims to push all heavy elements in the right side and lighier to the extreme left.
# Best case : Ω(n)
# Worst case : O(n^2)
def main():
# array takes in space separated numbers from the user
array = list(
map(int, input("Enter the numbers separated with space: ").strip().split(" ")))
output = b... | Python | zaydzuhri_stack_edu_python |
comment Problem 8 solution (part 1)
function run lines
begin
set accumulator = 0
set currentLine = 0
set visitedLines = list
while 0 <= currentLine < length lines and currentLine not in visitedLines
begin
append visitedLines currentLine
set opcode = split lines at currentLine string
if opcode at 0 == string nop
begin
... | #Problem 8 solution (part 1)
def run(lines):
accumulator = 0
currentLine = 0
visitedLines = []
while 0<=currentLine<len(lines) and currentLine not in visitedLines:
visitedLines.append(currentLine)
opcode = lines[currentLine].split(' ')
if opcode[0] == 'nop':
curren... | Python | zaydzuhri_stack_edu_python |
function _do_merge ext exts_other
begin
for ext_other in exts_other
begin
if not call is_duplicate ext_other
begin
return false
end
end
return true
end function | def _do_merge(ext, exts_other):
for ext_other in exts_other:
if not ext.is_duplicate(ext_other):
return False
return True | Python | nomic_cornstack_python_v1 |
function _get_acl_audit_roles
begin
return call _get_cache lambda -> dictionary comprehension name : id for role in all string acl_audit_roles
end function
comment Using like `Audit%` because all audit roles start with `Audit`
comment e.g. Auditors, Audit Captains, Audit Captains Mapped | def _get_acl_audit_roles():
return _get_cache(lambda: {
role.name: role.id for role in all_models.AccessControlRole.query.filter(
# Using like `Audit%` because all audit roles start with `Audit`
# e.g. Auditors, Audit Captains, Audit Captains Mapped
all_models.AccessControlRole.nam... | Python | nomic_cornstack_python_v1 |
comment Q7 럭키 스트레이트
set S = input
set left = 0
set right = 0
for i in range 0 length S // 2
begin
set left = left + integer S at i
end
for i in range length S // 2 length S
begin
set right = right + integer S at i
end
comment print(left)
comment print(right)
if left == right
begin
print string LUCYK
end
else
begin
prin... | #Q7 럭키 스트레이트
S=input()
left=0
right=0
for i in range(0,len(S)//2):
left += int(S[i])
for i in range(len(S)//2,len(S)):
right+= int(S[i])
# print(left)
# print(right)
if left==right:
print('LUCYK')
else:
print('READY') | Python | zaydzuhri_stack_edu_python |
function sanitize_json_and_store file
begin
with open file string r as read_file
begin
set data = load json read_file
end
pop data string numberOfModules none
set data at string children = pop data string modules
for module in data at string children
begin
pop module string SDF none
pop module string viewModule none
po... | def sanitize_json_and_store(file):
with open(file, 'r') as read_file:
data = json.load(read_file)
data.pop('numberOfModules', None)
data['children'] = data.pop('modules')
for module in data['children']:
module.pop('SDF', None)
module.pop('viewModule', None)
module.pop('de... | Python | nomic_cornstack_python_v1 |
function _report self msg
begin
info msg
call update_description string { msg } <br/>
end function | def _report(self, msg: str):
self.runtime.logger.info(msg)
jenkins.update_description(f'{msg}<br/>') | Python | nomic_cornstack_python_v1 |
function culaDeviceSposv upio n nrhs a lda b ldb
begin
set status = call culaDeviceSposv upio n nrhs integer a lda integer b ldb
call culaCheckStatus status
end function | def culaDeviceSposv(upio, n, nrhs, a, lda, b, ldb):
status = _libcula.culaDeviceSposv(upio, n, nrhs, int(a), lda, int(b),
ldb)
culaCheckStatus(status) | Python | nomic_cornstack_python_v1 |
from typing import *
from pylist import *
class Solution
begin
function reverseBetween self head left right
begin
set p = call ListNode - 1
set new_head = p
set next = head
for i in range left - 1
begin
set p = next
end
set q = next
set pre = p
set r = next
for i in range right - left
begin
set p = q
set q = r
set r = ... | from typing import *
from pylist import *
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
p=ListNode(-1)
new_head=p
p.next=head
for i in range(left-1):
p=p.next
q=p.next
pre=p
r=q.next
for i in ... | Python | zaydzuhri_stack_edu_python |
function main self
begin
import glob
from pylith.meshio.Xdmf import Xdmf
set xdmf = call Xdmf
for filenameHDF5 in call iglob filepattern
begin
write xdmf filenameHDF5 verbose=true
end
return
end function | def main(self):
import glob
from pylith.meshio.Xdmf import Xdmf
xdmf = Xdmf()
for filenameHDF5 in glob.iglob(self.filepattern):
xdmf.write(filenameHDF5, verbose=True)
return | Python | nomic_cornstack_python_v1 |
comment Radomir Fugiel
import sys
function is_anagram word1 word2
begin
set alpha = string abcdefghijklmnopqrstuvwxyz
for let in alpha
begin
set freq1 = count word1 let
set freq2 = count word2 let
if freq1 != freq2
begin
return false
end
end
return true
end function
for line in stdin
begin
set curr = list comprehension... | #Radomir Fugiel
import sys
def is_anagram(word1, word2):
alpha = 'abcdefghijklmnopqrstuvwxyz'
for let in alpha:
freq1 = word1.count(let)
freq2 = word2.count(let)
if freq1 != freq2:
return False
return True
for line in sys.stdin:
curr = [x for x in line.strip().split('"') if len(x)>0]
| Python | zaydzuhri_stack_edu_python |
function heuristic self root goal
begin
set dx = absolute row - row
set dy = absolute col - col
return dx + dy
end function | def heuristic(self, root, goal):
dx = abs(root.row - goal.row)
dy = abs(root.col - goal.col)
return dx + dy | Python | nomic_cornstack_python_v1 |
function check_transfer_log_path self transfer_log_path
begin
set rayvision_log_path = get environ TRANSFER_LOG string
if boolean transfer_log_path and exists path transfer_log_path
begin
set transfer_path = transfer_log_path
if rayvision_log_path != transfer_log_path
begin
update environ dict TRANSFER_LOG transfer_pat... | def check_transfer_log_path(self, transfer_log_path):
rayvision_log_path = os.environ.get(TRANSFER_LOG, "")
if bool(transfer_log_path) and os.path.exists(transfer_log_path):
transfer_path = transfer_log_path
if rayvision_log_path != transfer_log_path:
os.environ.u... | Python | nomic_cornstack_python_v1 |
function map_raw_field_data_type raw_field_data_type
begin
comment TODO mapping non sqlite to sqlite
set value = upper raw_field_data_type
set mapping = dict string INT string INT ; string INTEGER string INT ; string TINYINT string INT ; string SMALLINT string INT ; string MEDIUMINT string INT ; string BIGINT string IN... | def map_raw_field_data_type(raw_field_data_type: str) -> str:
# TODO mapping non sqlite to sqlite
value = raw_field_data_type.upper()
mapping = {'INT': 'INT',
'INTEGER': 'INT',
'TINYINT': 'INT',
'SMALLINT': 'INT',
'MEDIUMINT': 'INT',
... | Python | nomic_cornstack_python_v1 |
function singleNumber A
begin
string It constructs the element appearing once by attempting to set the 1 bits which appeared either once or four times (the only possibilities here)
set MAX_BITS = 64
set curBitPosition = 0
set ele = 0
while curBitPosition <= MAX_BITS
begin
set bit_val = 2 ^ curBitPosition
set total1s = ... | def singleNumber(A):
'''
It constructs the element appearing once by
attempting to set the 1 bits which appeared
either once or four times (the only possibilities here)
'''
MAX_BITS = 64
curBitPosition = 0
ele = 0
while curBitPosition <= MAX_BITS:
bit_val = 2... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Mar 4 15:32:38 2018 @author: Samuel Garcia Solución del Problema 5.1 del Libro "An Introduction to Computational Fluid Dynamics" de H K Versteeg and W Malalasekera con Metodo Upwind ---------------------------------- _____________________... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 4 15:32:38 2018
@author: Samuel Garcia
Solución del Problema 5.1 del Libro "An Introduction to Computational Fluid Dynamics"
de H K Versteeg and W Malalasekera con Metodo Upwind
----------------------------------
___________________... | Python | zaydzuhri_stack_edu_python |
function is_prime n
begin
if n < 2
begin
return false
end
for i in range 2 integer n ^ 0.5 + 1
begin
if n % i == 0
begin
return false
end
end
return true
end function
set product = 1
for i in range 80 101
begin
if call is_prime i
begin
set product = product * i
end
end
print product | def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
product = 1
for i in range(80, 101):
if is_prime(i):
product *= i
print(product)
| Python | flytech_python_25k |
function read_credentials self credential_file=HOMEDIR + string /.onedrive/credentials
begin
with open credential_file string r as credfile
begin
for line in credfile
begin
set tuple key_ val_ = split line at slice : 2 :
for key in tuple string redirect_uri string client_id string client_secret
begin
if lower key == ... | def read_credentials(self, credential_file=HOMEDIR + '/.onedrive/credentials'):
with open(credential_file, 'r') as credfile:
for line in credfile:
key_, val_ = line.split()[:2]
for key in ('redirect_uri', 'client_id', 'client_secret'):
if key.lower... | Python | nomic_cornstack_python_v1 |
from itertools import combinations
set people = split input string ,
set chairs = integer input
for combination in call combinations people chairs
begin
print join string , combination
end | from itertools import combinations
people = input().split(", ")
chairs = int(input())
for combination in combinations(people, chairs):
print(', '.join(combination))
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
from __future__ import print_function
comment set unbuffered output
import os
import sys
set stdout = call fdopen call fileno string w 0
print string processing cmd line args
import argparse
set parser = call ArgumentParser string filter tweets by Twitter assig... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
# set unbuffered output
import os
import sys
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
########################################
print('processing cmd line args')
import argparse
parser=argparse.ArgumentParser('filter tweet... | Python | zaydzuhri_stack_edu_python |
comment CS2770 - Nils Murrugarra
import re
import pandas as pd
import numpy as np
comment Read all lines from a file
function read_file in_file remove_enter=false flag_strip=false
begin
set file_ID = open in_file string r
comment all lines
set lines = list comprehension line for line in read lines file_ID
if remove_ent... | # CS2770 - Nils Murrugarra
import re
import pandas as pd
import numpy as np
# Read all lines from a file
def read_file(in_file, remove_enter=False, flag_strip=False):
file_ID = open(in_file, "r")
lines = [line for line in file_ID.readlines()] # all lines
if remove_enter:
lines = map(lambd... | Python | zaydzuhri_stack_edu_python |
function logging_context level=INFO logger=none
begin
if logger is none
begin
set logger = call getLogger
end
set previous_level = call getEffectiveLevel
call setLevel level
try
begin
yield
end
finally
begin
call setLevel previous_level
end
end function | def logging_context(level: int = logging.INFO, logger: Optional[logging.Logger] = None):
if logger is None:
logger = logging.getLogger()
previous_level = logger.getEffectiveLevel()
logger.setLevel(level)
try:
yield
finally:
logger.setLevel(previous_level) | Python | nomic_cornstack_python_v1 |
from nltk.corpus import stopwords
set stop = call words string english
set result_f = open string result.txt string a
with open string train_data_sample.txt string rw+ as f
begin
set sentence = read lines f
end | from nltk.corpus import stopwords
stop = stopwords.words('english')
result_f = open('result.txt', 'a')
with open("train_data_sample.txt", "rw+")as f:
sentence=f.readlines() | Python | zaydzuhri_stack_edu_python |
comment !/bin/python
import sys
set tuple a b c d e = split strip input string
set arr = list integer a integer b integer c integer d integer e
set tuple a b c d e = list integer a integer b integer c integer d integer e
set sum_1 = arr at 0 + arr at 1 + arr at 2 + arr at 3
set sum_2 = arr at 0 + arr at 1 + arr at 2 + ... | #!/bin/python
import sys
a,b,c,d,e = input().strip().split(' ')
arr = a,b,c,d,e = [int(a),int(b),int(c),int(d),int(e)]
sum_1 = arr[0] + arr[1] + arr[2] + arr[3]
sum_2 = arr[0] + arr[1] + arr[2] + arr[4]
sum_3 = arr[0] + arr[1] + arr[3] + arr[4]
sum_4 = arr[0] + arr[2] + arr[3] + arr[4]
sum_5 = arr[1] + arr[2] + arr... | Python | zaydzuhri_stack_edu_python |
set N = integer input
set E = N // 2
set O = N // 2 + N % 2
print E * O | N = int(input())
E = N//2
O = N//2 + N%2
print(E*O)
| Python | zaydzuhri_stack_edu_python |
function test_delete_data self
begin
set data_github = dict string version_control string github ; string scm_repo string test_delete ; string scm_branch string test_delete ; string scm_commit string test_delete ; string repo string test_delete1 ; string branch string test_delete1 ; string enabled 0
set data_git = dict... | def test_delete_data(self):
data_github = {
"version_control": "github",
"scm_repo": "test_delete",
"scm_branch": "test_delete",
"scm_commit": "test_delete",
"repo": "test_delete1",
"branch": "test_delete1",
"enabled": 0
... | Python | nomic_cornstack_python_v1 |
if a - 1 // 25 == 0
begin
print string Clasa A
end
else
if a - 1 // 25 == 1
begin
print string Clasa B
end
else
if a - 1 // 25 == 2
begin
print string Clasa C
end
else
if a - 1 // 25 == 3
begin
print string Clasa D
end
else
if a - 1 // 25 == 4
begin
print string Clasa E
end
else
begin
print string Au uitat despre Radu
... | if ((a-1)//25==0):
print("Clasa A")
elif ((a-1)//25==1):
print("Clasa B")
elif ((a-1)//25==2):
print("Clasa C")
elif ((a-1)//25==3):
print("Clasa D")
elif ((a-1)//25==4):
print("Clasa E")
else:
print("Au uitat despre Radu")
| Python | zaydzuhri_stack_edu_python |
function insertion_sort data
begin
for i in range 1 length list
begin
set j = i - 1
set next_element = data at i
while list at j > next_element and j >= 0
begin
set data at j + 1 = data at j
set j = j - 1
end
set data at j + 1 = next_element
end
return data
end function | def insertion_sort(data):
for i in range(1, len(list)):
j = i-1
next_element = data[i]
while(list[j] > next_element) and (j >= 0):
data[j+1] = data[j]
j = j - 1
data[j+1] = next_element
return data | Python | nomic_cornstack_python_v1 |
function loss_total self mask
begin
function loss y_true y_pred
begin
comment Compute predicted image with non-hole pixels set to ground truth
set y_comp = mask * y_true + 1 - mask * y_pred
comment Compute the vgg features.
if vgg_device
begin
with device vgg_device
begin
set vgg_out = call vgg y_pred
set vgg_gt = call... | def loss_total(self, mask):
def loss(y_true, y_pred):
# Compute predicted image with non-hole pixels set to ground truth
y_comp = mask * y_true + (1-mask) * y_pred
# Compute the vgg features.
if self.vgg_device:
with tf.device(self.vgg_device):... | Python | nomic_cornstack_python_v1 |
import os
import tempfile
import tarfile
from google.cloud import storage
set DATA_DIR = temporary directory suffix=none prefix=string steering_training
function get_archive bucket_name url
begin
print string Downloading storage object training/ { url } from bucket { bucket_name }
set storage_client = call Client
set b... | import os
import tempfile
import tarfile
from google.cloud import storage
DATA_DIR = tempfile.TemporaryDirectory(suffix=None, prefix='steering_training')
def get_archive (bucket_name, url):
print(f"Downloading storage object training/{url} from bucket {bucket_name}")
storage_client = storage.Client()
... | Python | zaydzuhri_stack_edu_python |
import string as s
comment split and capitalize each word first letter
print call capwords str1 sep=none
print call capwords string Python is one of the best programming languages sep=none
import re
set st1 = string Python 123
set regst = compile string
set st1_new = sub string st1
print st1_new
comment rewrite dates ... | import string as s
print(s.capwords(str1,sep = None)) # split and capitalize each word first letter
print(s.capwords('Python is one of the best programming languages',sep = None))
import re
st1 = 'Python 123'
regst = re.compile('')
st1_new = regst.sub('',st1)
print(st1_new)
#rewrite dates of the form “11/27/2012” as “... | Python | zaydzuhri_stack_edu_python |
function stime t
begin
return string format time string %d.%m.%Y %H:%M:%S call gmtime t
end function | def stime(t):
return strftime('%d.%m.%Y %H:%M:%S', gmtime(t)) | Python | nomic_cornstack_python_v1 |
comment Sum
print 2 + 1
comment Multiply
print 2 * 3
comment Subtraction
print 20 - 10
comment Division ( division always returns a floating point number )
print 17 / 3
comment floor division discards the fractional part
print 17 // 3
comment % will return remainder of the division
print 20 % 3
comment Squared
print 5 ... | print(2+1) # Sum
print(2*3) # Multiply
print(20-10) # Subtraction
print(17/3) # Division ( division always returns a floating point number )
print(17//3) # floor division discards the fractional part
print(20%3) # % will return remainder of the division
print(5**2) # Squar... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from tkinter import *
with open string blob_extractor.conf string r as config_file
begin
set configs = read lines config_file
for line in configs
begin
set config = right strip line string
if string server in line
begin
set server = config at slice index config string = + 1 : :
end
if st... | # -*- coding: utf-8 -*-
from tkinter import *
with open("blob_extractor.conf", "r") as config_file:
configs = config_file.readlines()
for line in configs:
config = line.rstrip("\n")
if "server" in line:
server = config[config.index("=") + 1:]
if "user" in line:
... | Python | zaydzuhri_stack_edu_python |
function data_filler_company self number_of_rows conn
begin
string creates and fills the table with company data
set cursor = call cursor
execute cursor string CREATE TABLE company(id TEXT PRIMARY KEY, name TEXT, sdate TEXT, email TEXT, domain TEXT, city TEXT)
commit conn
set multi_lines = list
try
begin
for i in rang... | def data_filler_company(self, number_of_rows, conn):
'''creates and fills the table with company data
'''
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE company(id TEXT PRIMARY KEY,
name TEXT, sdate TEXT, email TEXT, domain TEXT, city TEXT)
''')
c... | Python | jtatman_500k |
with open string 11.txt string r as tekst
begin
for regel in tekst
begin
print string i + string + regel
set i = i + 1
end
end | with open("11.txt","r") as tekst:
for regel in tekst:
print(str(i) + " " + regel)
i=i+1 | Python | zaydzuhri_stack_edu_python |
from inspect import indentsize
import os
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pandas as pd
from sklearn.tree import tree , plot_tree
change directory string Mycode\kaggle_Titanic
print string 現在の作業ディレクトリは { get current directory }
call set_option string display.max_rows none
set t... | from inspect import indentsize
import os
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pandas as pd
from sklearn.tree import tree,plot_tree
os.chdir('Mycode\kaggle_Titanic')
print(f"現在の作業ディレクトリは{os.getcwd()}")
pd.set_option('display.max_rows', None)
train = pd.read_csv("train.csv")
te... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.