code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import sys
import tweepy
import pandas as pd
import csv
comment import os
from time import gmtime , strftime
set current_time = string format time string %Y-%m-%d %Hh%Mm call gmtime
comment os.environ['PYTHONIOENCODING'] = 'utf-8' #setting the sys environment, or we will get unicoden error
comment create empty datafram... | import sys
import tweepy
import pandas as pd
import csv
#import os
from time import gmtime, strftime
current_time=strftime("%Y-%m-%d %Hh%Mm", gmtime())
#os.environ['PYTHONIOENCODING'] = 'utf-8' #setting the sys environment, or we will get unicoden error
TwitterData=pd.DataFrame(columns=['User','Coordinates','Dat... | Python | zaydzuhri_stack_edu_python |
string ============================================================ http://projecteuler.net/problem=168 Consider the number 142857. We can right-rotate this number by moving the last digit (7) to the front of it, giving us 714285. It can be verified that 714285=5 x 142857. This demonstrates an unusual property of 14285... | '''
============================================================
http://projecteuler.net/problem=168
Consider the number 142857. We can right-rotate this number by moving the last digit (7) to the front of it, giving us 714285.
It can be verified that 714285=5 x 142857.
This demonstrates an unusual property of 142857:... | Python | zaydzuhri_stack_edu_python |
function start self
begin
set scraper = call PastebinScraper q out_q use_tor=use_tor
info string Starting PastebinScraper
call gen_start
end function | def start(self):
self.scraper = PastebinScraper(self.q, self.out_q, use_tor=self.use_tor)
logger.info('Starting PastebinScraper')
self.gen_start() | Python | nomic_cornstack_python_v1 |
function delRBVPNprefixlist **kwargs
begin
set proxy = kwargs at string proxy
set session_token = kwargs at string sessiontoken
if kwargs at string prefix_list_id is not none
begin
set prefix_list_id = kwargs at string prefix_list_id
end
else
begin
print string Please specify the prefix list ID to configure using --pre... | def delRBVPNprefixlist(**kwargs):
proxy = kwargs['proxy']
session_token = kwargs['sessiontoken']
if kwargs['prefix_list_id'] is not None:
prefix_list_id = kwargs['prefix_list_id']
else:
print("Please specify the prefix list ID to configure using --prefix-list-id. Use 'pyVMC.py rbvpn-pre... | Python | nomic_cornstack_python_v1 |
function read_csv self
begin
with open csv_file string rU as file_object
begin
set reader = reader file_object delimiter=delimiter
if has_header_row
begin
set header_row = next reader none
if has_duplicate_column_names
begin
set header_counts_dict = dictionary
set new_header_row = list
for each_header in header_row
be... | def read_csv(self):
with open(self.csv_file, 'rU') as file_object:
reader = csv.reader(file_object, delimiter=self.delimiter)
if self.has_header_row:
header_row = next(reader, None)
if self.has_duplicate_column_names:
header_counts_dict... | Python | nomic_cornstack_python_v1 |
function binary_to_decimal binary
begin
set decimal = 0
set power = 0
comment Iterate through each digit of the binary number, starting from the least significant bit
for bit in reversed binary
begin
if bit == string 1
begin
set decimal = decimal + 2 ^ power
end
set power = power + 1
end
return decimal
end function
set... | def binary_to_decimal(binary):
decimal = 0
power = 0
# Iterate through each digit of the binary number, starting from the least significant bit
for bit in reversed(binary):
if bit == '1':
decimal += 2 ** power
power += 1
return decimal
binary = "1101"... | Python | jtatman_500k |
comment Use Python packages
comment Using the math Package (Demo):
import math
call help math
square root 2.0
comment This is approx 1.41421....
call atan 1 * 4
comment This should produce pi
pi
comment Using time & datetime (Demo):
import time
import datetime
call help time
time
time
now
comment Using the sys Package ... | # Use Python packages
# Using the math Package (Demo):
import math
help(math)
math.sqrt(2.0)
# This is approx 1.41421....
math.atan(1) * 4
# This should produce pi
math.pi
# Using time & datetime (Demo):
import time
import datetime
help(time)
time.time()
time.time()
datetime.datetime.now()
# Using the sys Package (... | Python | zaydzuhri_stack_edu_python |
function terminate uuid new_time limit skip=false
begin
set driver = call driver NEO4J_URI auth=tuple NEO4J_USERNAME NEO4J_PASSWORD
with call session as session
begin
comment Attempt to locate environment by uuid
set env = call find_environment session uuid
comment If found, confirm termination
set msg = format string ... | def terminate(uuid, new_time, limit, skip=False):
driver = GraphDatabase.driver(
settings.NEO4J_URI,
auth=(settings.NEO4J_USERNAME, settings.NEO4J_PASSWORD)
)
with driver.session() as session:
# Attempt to locate environment by uuid
env = find_environment(session, uuid)
... | Python | nomic_cornstack_python_v1 |
function test_basic self
begin
call register_get_user_retire_response user
set headers = call build_jwt_headers superuser
set data = dict string username username
set response = post url data keyword headers
call assert_response_correct response 204 b''
end function | def test_basic(self):
self.register_get_user_retire_response(self.user)
headers = self.build_jwt_headers(self.superuser)
data = {'username': self.user.username}
response = self.client.post(self.url, data, **headers)
self.assert_response_correct(response, 204, b"") | Python | nomic_cornstack_python_v1 |
function run_one_step self
begin
pass
end function | def run_one_step(self):
pass | Python | nomic_cornstack_python_v1 |
function code0
begin
return dict
end function | def code0():
return {} | Python | nomic_cornstack_python_v1 |
async function reset self ctx
begin
set msg = await call send string Are you sure you want to reset the current Plague Game?
call start_adding_reactions msg YES_OR_NO_EMOJIS
set pred = call yes_or_no msg author
try
begin
await call wait_for string reaction_add check=pred timeout=60
end
except TimeoutError
begin
await c... | async def reset(self, ctx):
msg = await ctx.send(f"Are you sure you want to reset the current Plague Game?")
start_adding_reactions(msg, ReactionPredicate.YES_OR_NO_EMOJIS)
pred = ReactionPredicate.yes_or_no(msg, ctx.author)
try:
await self.bot.wait_for("reaction_add", check=... | Python | nomic_cornstack_python_v1 |
function has_terminated self
begin
return memory == string . * frames_total and all list comprehension t >= arrival_times at run + run_times at run for process in process_list for run in range length arrival_times
end function | def has_terminated(self):
return (self.memory == '.' * Mnemokinesis.frames_total and
all([self.t >= process.arrival_times[run] + process.run_times[run]
for process in self.process_list
for run in range(len(process.arrival_times))])) | Python | nomic_cornstack_python_v1 |
import medium_kite as mk
import medium_hamilton as mh
import medium_sparse as ms
import networkx as nx
import medium_known_optimal as mo
import matplotlib.pyplot as plt
import random
comment return a graph with 100 nodes of 4 different types with sharing node *57* -> soda, and its homes
function medium_graph
begin
set ... | import medium_kite as mk
import medium_hamilton as mh
import medium_sparse as ms
import networkx as nx
import medium_known_optimal as mo
import matplotlib.pyplot as plt
import random
# return a graph with 100 nodes of 4 different types with sharing node *57* -> soda, and its homes
def medium_graph():
G1 = mk.comb... | Python | zaydzuhri_stack_edu_python |
function applies self dataset
begin
string Determines whether the dim transform can be applied to the Dataset, i.e. whether all referenced dimensions can be resolved.
if is instance dimension dim
begin
set applies = call applies dataset
end
else
begin
set applies = call get_dimension dimension is not none
if is instanc... | def applies(self, dataset):
"""
Determines whether the dim transform can be applied to the
Dataset, i.e. whether all referenced dimensions can be
resolved.
"""
if isinstance(self.dimension, dim):
applies = self.dimension.applies(dataset)
else:
... | Python | jtatman_500k |
comment !/usr/bin/env python
comment Copyright 2016 PLanet Labs Inc.
import requests
import json
import pandas as pd
import pickle
import collections
import textwrap
import math
import itertools
from collections import defaultdict
set BASE_URL = string https://planet-labs-url.com/
set MAJORITY_SATS = 0.5
function flatt... | #!/usr/bin/env python
# Copyright 2016 PLanet Labs Inc.
import requests
import json
import pandas as pd
import pickle
import collections
import textwrap
import math
import itertools
from collections import defaultdict
BASE_URL = 'https://planet-labs-url.com/'
MAJORITY_SATS = 0.5
def flatten(d, parent_key='', sep=... | Python | zaydzuhri_stack_edu_python |
while length li > 0
begin
set cnt = cnt + n
set cnt = cnt % length li
append result pop li cnt
set cnt = cnt - 1
end
print string < end=string
print *result sep=string , end=string
print string > end=string | while len(li) > 0:
cnt += n
cnt = cnt%len(li)
result.append(li.pop(cnt))
cnt -= 1
print('<',end='')
print(*result,sep=', ',end='')
print('>',end='')
| Python | zaydzuhri_stack_edu_python |
import textblob
function detect_sentiment text
begin
set analysis = call TextBlob text
if polarity > 0
begin
return string positive
end
else
if polarity == 0
begin
return string neutral
end
else
begin
return string negative
end
end function | import textblob
def detect_sentiment(text):
analysis = textblob.TextBlob(text)
if analysis.sentiment.polarity > 0:
return 'positive'
elif analysis.sentiment.polarity == 0:
return 'neutral'
else:
return 'negative' | Python | iamtarun_python_18k_alpaca |
function add_to_io_map self inputs outputs
begin
if type inputs != list or type outputs != list
begin
raise call ValueError string Must feed in lists for inputs and outputs
end
if list inputs outputs not in io_mapping
begin
append io_mapping list inputs outputs
end
else
begin
debug string These inputs and outputs are a... | def add_to_io_map(self, inputs, outputs):
if type(inputs) != list or type(outputs) != list:
raise ValueError("Must feed in lists for inputs and outputs")
if [inputs,outputs] not in self.io_mapping:
self.io_mapping.append([inputs,outputs])
else:
self.logger.de... | Python | nomic_cornstack_python_v1 |
function get_facts pdb
begin
debug string querying facts
set res = dict
for fact in FACTS
begin
set res at fact = dict
set fact_vals = call facts fact
for val in fact_vals
begin
if value not in res at fact
begin
set res at fact at value = 0
end
set res at fact at value = res at fact at value + 1
end
end
debug string ... | def get_facts(pdb):
logger.debug("querying facts")
res = {}
for fact in FACTS:
res[fact] = {}
fact_vals = pdb.facts(fact)
for val in fact_vals:
if val.value not in res[fact]:
res[fact][val.value] = 0
res[fact][val.value] += 1
logger.debug("... | Python | nomic_cornstack_python_v1 |
import math
import time
function is_prime_v2 n
begin
string Return 'True' if 'n' is a prime number. False otherwise.
if n == 1
begin
comment 1 is not prime ,it's unit
return false
end
set max_divisor = floor square root n
for d in range 2 1 + max_divisor
begin
if n % d == 0
begin
return false
end
end
return true
end fu... | import math
import time
def is_prime_v2(n):
"""Return 'True' if 'n' is a prime number. False otherwise."""
if n == 1:
return False # 1 is not prime ,it's unit
max_divisor = math.floor(math.sqrt(n))
for d in range(2, 1 + max_divisor):
if n % d == 0:
return False
retur... | Python | zaydzuhri_stack_edu_python |
function download_to_file self filename chunk_size=DefaultPartSize verify_hashes=true retry_exceptions=tuple error
begin
set num_chunks = call _calc_num_chunks chunk_size
with open filename string wb as output_file
begin
call _download_to_fileob output_file num_chunks chunk_size verify_hashes retry_exceptions
end
end f... | def download_to_file(self, filename, chunk_size=DefaultPartSize,
verify_hashes=True, retry_exceptions=(socket.error,)):
num_chunks = self._calc_num_chunks(chunk_size)
with open(filename, 'wb') as output_file:
self._download_to_fileob(output_file, num_chunks, chun... | Python | nomic_cornstack_python_v1 |
comment @Title: 子集 II (Subsets II)
comment @Author: 2464512446@qq.com
comment @Date: 2019-11-29 17:54:41
comment @Runtime: 20 ms
comment @Memory: 11.5 MB
class Solution extends object
begin
function subsetsWithDup self nums
begin
string :type nums: List[int] :rtype: List[List[int]]
set size = length nums
comment 排序是为了处... | # @Title: 子集 II (Subsets II)
# @Author: 2464512446@qq.com
# @Date: 2019-11-29 17:54:41
# @Runtime: 20 ms
# @Memory: 11.5 MB
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
size = len(nums)
nums.sort() # 排序... | Python | zaydzuhri_stack_edu_python |
function master_yoda s
begin
set li = list
set li = split s
reverse li
for i in li
begin
print i + string
end
end function
call master_yoda string we are here | def master_yoda(s):
li=[]
li=s.split()
li.reverse()
for i in li:
print(i +"\t" )
master_yoda("we are here")
| Python | zaydzuhri_stack_edu_python |
import time
import re
comment Logistics
comment Throw error if praw library not installed. | import time
import re
#Logistics
#Throw error if praw library not installed. | Python | zaydzuhri_stack_edu_python |
function problem self identifier
begin
return json call _get string problems/%d % identifier
end function | def problem(self, identifier):
return self._get("problems/%d" % identifier).json() | Python | nomic_cornstack_python_v1 |
comment Pearson chi squared test
comment 251 trading days per year
from scipy.stats import chi2
import matplotlib.pyplot as plt
set sym_list = list string COHR
set start_date = string 2015-01-01
set end_date = string 2017-07-10
set sample_price = call get_pricing sym_list start_date=start_date end_date=end_date fields=... | #Pearson chi squared test
#251 trading days per year
from scipy.stats import chi2
import matplotlib.pyplot as plt
sym_list = ["COHR"]
start_date = '2015-01-01'
end_date = '2017-07-10'
sample_price= get_pricing(sym_list, start_date = start_date, end_date = end_date, fields = 'price')
sample_returns = sample_price.pct_... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set root = call TrieNode
end function | def __init__(self):
self.root = TrieNode() | Python | nomic_cornstack_python_v1 |
set num1 = input string Enter a number:
set num12 = input string Enter another number:
set result = integer num1 + integer num12
set result = decimal num1 + decimal num12
print result | num1 = input("Enter a number: ")
num12 = input("Enter another number: ")
result = int(num1) + int(num12)
result = float(num1) + float(num12)
print(result)
| Python | zaydzuhri_stack_edu_python |
function begin_delete_static_site_build self resource_group_name name environment_name **kwargs
begin
comment type: str
comment type: str
comment type: str
comment type: Any
comment type: (...) -> LROPoller[None]
comment type: Union[bool, PollingMethod]
set polling = pop kwargs string polling true
comment type: ClsType... | def begin_delete_static_site_build(
self,
resource_group_name, # type: str
name, # type: str
environment_name, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller[None]
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while true
begin
set rw = call RandomWalk
call fill_walk
comment 设置窗口大小
figure dpi=128 figsize=tuple 10 6
set point_numbers = list range num_points
plot x_values y_values linewidth=1
scatter plt 0 0 c=string green s=5
scatter plt x_values at - 1 y_value... | import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
rw=RandomWalk()
rw.fill_walk()
#设置窗口大小
plt.figure(dpi=128,figsize=(10,6))
point_numbers=list(range(rw.num_points))
plt.plot(rw.x_values,rw.y_values,linewidth=1)
plt.scatter(0,0,c='green',s=5)
plt.scatter(rw.x_values[-1],rw.y_values[-... | Python | zaydzuhri_stack_edu_python |
function __init__ self depths=list 64 128 256 512
begin
set depths = list 3 + depths
set reuse = false
end function | def __init__(self, depths=[64, 128, 256, 512]):
self.depths = [3] + depths
self.reuse = False | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
from matplotlib import rc
import numpy as np
from Network import Network
from collections import Counter
call rc string font keyword dict string family string serif ; string serif list string Times
call rc string font size=14
call rc string text usetex=true
function weight_histogram from... | import matplotlib.pyplot as plt
from matplotlib import rc
import numpy as np
from Network import Network
from collections import Counter
rc('font',**{'family':'serif','serif':['Times']})
rc('font', size=14)
rc('text', usetex=True)
def weight_histogram(from_file):
n = Network(from_file=from_file)
frequencies =... | Python | zaydzuhri_stack_edu_python |
comment -*- encoding: utf-8 -*-
string @Author : {YourName} @File : selection_sort.py @Time : 2019/3/16 11:35 @Desc :
import sys
import math
from util import random_util
function merge A=list p=0 q=0 r=0
begin
set n1 = q - p + 1
set n2 = r - q
set L = list
set R = list
for i in range 0 n1
begin
append L A at p + i
e... | # -*- encoding: utf-8 -*-
'''
@Author : {YourName}
@File : selection_sort.py
@Time : 2019/3/16 11:35
@Desc :
'''
import sys
import math
from util import random_util
def merge(A=[], p=0, q=0, r=0):
n1 = q - p + 1
n2 = r - q
L = []
R = []
for i in range(0, n1):
L.append(A[p +... | Python | zaydzuhri_stack_edu_python |
comment Practice Question 1:
comment Get 2 integers from the user
comment Write a function that takes the two integers x1 and x2 returns all the integers BETWEEN them.
comment Print 'Here are the numbers between:' then all of the numbers one per line between the 2 integers entered.
comment Add some data validation so t... | # Practice Question 1:
# Get 2 integers from the user
# Write a function that takes the two integers x1 and x2 returns all the integers BETWEEN them.
# Print 'Here are the numbers between:' then all of the numbers one per line between the 2 integers entered.
# Add some data validation so that if x2 is lower than x1 it ... | Python | zaydzuhri_stack_edu_python |
function copytodir src dstdir
begin
set dst = call pathjoin dstdir base name path src
copy src dst
end function | def copytodir(src, dstdir):
dst = pathjoin(dstdir, os.path.basename(src))
copy(src, dst) | Python | nomic_cornstack_python_v1 |
function update_collection self payload last_modified=none
begin
string Update a Zotero collection property such as 'name' Accepts one argument, a dict containing collection data retrieved using e.g. 'collections()'
set modified = payload at string version
if last_modified is not none
begin
set modified = last_modified... | def update_collection(self, payload, last_modified=None):
"""
Update a Zotero collection property such as 'name'
Accepts one argument, a dict containing collection data retrieved
using e.g. 'collections()'
"""
modified = payload["version"]
if last_modified is not ... | Python | jtatman_500k |
function parse_interpreter_variable self output
begin
return find all output at 0
end function | def parse_interpreter_variable(self, output):
return self.pair_map_regex.findall(output)[0] | Python | nomic_cornstack_python_v1 |
from typing import Iterable , List
function read fp n
begin
set i = 0
comment a buffer to cache lines
set lines = list
with open fp string r as f
begin
for line in f
begin
set i = i + 1
comment append a line
append lines strip line
if i >= n
begin
yield lines
comment reset buffer
set i = 0
clear lines
end
end
end
comm... | from typing import Iterable, List
def read(fp: str, n: int) -> Iterable[List[str]]:
i = 0
lines = [] # a buffer to cache lines
with open(fp, "r") as f:
for line in f:
i += 1
lines.append(line.strip()) # append a line
if i >= n:
yield lines
... | Python | zaydzuhri_stack_edu_python |
function areaTriangulo base altura
begin
return base * altura / 2
end function | def areaTriangulo(base,altura):
return (base*altura)/2 | Python | nomic_cornstack_python_v1 |
function suggestConcepts self prefix sources=list string concepts lang=string eng conceptLang=string eng page=1 count=20 returnInfo=call ReturnInfo **kwargs
begin
assert page > 0 msg string page parameter should be above 0
set params = dict string prefix prefix ; string source sources ; string lang lang ; string concep... | def suggestConcepts(self, prefix: str, sources: Union[str, list] = ["concepts"], lang: str = "eng", conceptLang: str = "eng", page: int = 1, count: int = 20, returnInfo: ReturnInfo = ReturnInfo(), **kwargs):
assert page > 0, "page parameter should be above 0"
params = { "prefix": prefix, "source": sourc... | Python | nomic_cornstack_python_v1 |
function update_callback sender **kwargs
begin
set t = kwargs at string t
if string force in kwargs
begin
set force = kwargs at string force
end
else
begin
set force = false
end
if force or t - last_update >= update_interval
begin
set z = z
call set_ydata absolute z
call set_title format string {} (t = {:0.2f}s) title ... | def update_callback(sender, **kwargs):
t = kwargs['t']
if 'force' in kwargs:
force = kwargs['force']
else:
force = False
if force or (t - self.last_update >= self.update_interval):
z = sender.z
self.line1.s... | Python | nomic_cornstack_python_v1 |
function after_rpc self cmd counter xpath kind
begin
set expect = list
set index = counter + xpath
set replay_type = kind at slice find kind string basic + 6 : :
if not cmd
begin
set cmd = string show running
end
if replay_type in list string create string replace string delete
begin
set cfg_pre = get common_cli_bas... | def after_rpc(self, cmd, counter, xpath, kind):
expect = []
index = counter + xpath
replay_type = kind[kind.find('basic ') + 6:]
if not cmd:
cmd = 'show running'
if replay_type in ['create', 'replace', 'delete']:
cfg_pre = self.common_cli_base.get(index,... | Python | nomic_cornstack_python_v1 |
function __setitem__ self key value
begin
pass
end function | def __setitem__(self, key, value):
pass | Python | nomic_cornstack_python_v1 |
for t in l1
begin
if t in l2
begin
remove l2 t
end
else
begin
append l2 t
end
end
for i in l2
begin
print i end=string
end | for t in l1:
if t in l2:
l2.remove(t)
else:
l2.append(t)
for i in l2:
print(i,end=' ')
| Python | zaydzuhri_stack_edu_python |
function add_dataset project_name dataset_name dataset_specs
begin
set data_dict = call get_default_specfile project_name
with open data_dict string r as f
begin
set spec = load yaml f Loader=Loader
end
set spec at dataset_name = dataset_specs
with open data_dict string w as f
begin
dump spec f Dumper=Dumper default_fl... | def add_dataset(project_name, dataset_name, dataset_specs):
data_dict = get_default_specfile(project_name)
with open(data_dict, "r") as f:
spec = yaml.load(f, Loader=Loader)
spec[dataset_name] = dataset_specs
with open(data_dict, "w") as f:
yaml.dump(spec, f, Dumper=Dumper, default_flow_... | Python | nomic_cornstack_python_v1 |
function diameter self
begin
set greatest_diameter = - inf
comment placeholders for max indices
set tuple i j k = tuple 0 0 1
for tuple c contour in enumerate contours
begin
set contour_array = call to_matrix at tuple slice : : slice : 2 : * pixel_spacing
comment There's some edge cases where the contour consists ... | def diameter(self):
greatest_diameter = -np.inf
i,j,k = 0,0,1 # placeholders for max indices
for c,contour in enumerate(self.contours):
contour_array = contour.to_matrix()[:,:2]*self.scan.pixel_spacing
# There's some edge cases where the contour consists only of
... | Python | nomic_cornstack_python_v1 |
function test_details_missing self
begin
set res = post string /api/v2/auth/register data=dumps dict string first_name string patrick ; string last_name string migot headers=dict string content-type string application/json
assert equal status_code 400
assert in string email or password missing string data
end function | def test_details_missing(self):
res = self.client().post(
'/api/v2/auth/register',
data=json.dumps({
"first_name": "patrick",
"last_name": "migot"
}),
headers={"content-type": 'application/json'}
)
self.asse... | Python | nomic_cornstack_python_v1 |
from __future__ import division
import numpy as np
comment np.seterr(invalid='ignore',divide='ignore')
comment <-------------------------IC Generators--------------------------------------->
function normal_ics nparticles pscale=1 vscale=1 masses=none
begin
string Generates `nparticles` particles with normally distribu... | from __future__ import division
import numpy as np
#np.seterr(invalid='ignore',divide='ignore')
#<-------------------------IC Generators--------------------------------------->
def normal_ics(nparticles,pscale=1,vscale=1,masses=None):
"""
Generates `nparticles` particles with normally distributed locations... | Python | zaydzuhri_stack_edu_python |
comment spark konfigurasyonunu ayaga kaldirmak ve spark contextini yuklemek
from pyspark import SparkContext , SparkConf
set sparkConf = call setAppName string Ugur Spark 1
set sc = call SparkContext conf=sparkConf
set depremRDD = call textFile string textfiles/depremler.txt
function processLine line
begin
set arr = sp... | #spark konfigurasyonunu ayaga kaldirmak ve spark contextini yuklemek
from pyspark import SparkContext, SparkConf
sparkConf = SparkConf().setMaster("local[*]").setAppName("Ugur Spark 1")
sc= SparkContext(conf=sparkConf)
depremRDD = sc.textFile("textfiles/depremler.txt")
def processLine(line):
arr = line.split("\t"... | Python | zaydzuhri_stack_edu_python |
function set_future_statement self
begin
call set_values start_phrase=string Futures Statements end_phrase=none start_with=2 end_until=- 1 prop_keys=future_statement_keys prop_name=string future_statement
set future_statement = map del_empty_keys future_statement
call convert_specific_type future_statement string trade... | def set_future_statement(self):
self.set_values(
start_phrase='Futures Statements',
end_phrase=None,
start_with=2,
end_until=-1,
prop_keys=self.future_statement_keys,
prop_name='future_statement'
)
self.future_statement = m... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment @Time : 2020/12/1 16:23
comment @Author : KevinHoo
comment @Site :
comment @File : main.py
comment @Software: PyCharm
comment @Email : hu.rui0530@gmail.com
comment 用于分析的库
import pandas as pd
import numpy as np
from sklearn import svm
comment 用于可视化的库
import matplotlib.pyplot as plt
... | # -*- coding: utf-8 -*-
# @Time : 2020/12/1 16:23
# @Author : KevinHoo
# @Site :
# @File : main.py
# @Software: PyCharm
# @Email : hu.rui0530@gmail.com
# 用于分析的库
import pandas as pd
import numpy as np
from sklearn import svm
# 用于可视化的库
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(font_scale=1.2) # ... | Python | zaydzuhri_stack_edu_python |
function get_entries_for self entry_category entry_status=none
begin
set meta_data_instances = list
if appointment
begin
set options = dict string registered_subject_id pk ; string appointment_id pk ; format string {0}__entry_category__iexact entry_attr entry_category
if entry_status
begin
update options dict string e... | def get_entries_for(self, entry_category, entry_status=None):
meta_data_instances = []
if self.appointment:
options = {
'registered_subject_id': self.registered_subject.pk,
'appointment_id': self.appointment.pk,
'{0}__entry_category__iexact'.forma... | Python | nomic_cornstack_python_v1 |
function vogais palavra
begin
set lista = string
set string = string aeiou
set contador = 0
set contando = length palavra
while contador < contando
begin
if palavra at contador in string
begin
set lista = lista + palavra at contador
end
set contador = contador + 1
end
return lista
end function
comment ________________... | def vogais(palavra):
lista = ""
string = "aeiou "
contador = 0
contando = len(palavra)
while contador < contando:
if palavra[contador] in string:
lista = lista + palavra[contador]
contador = contador + 1
return lista
#___________________________________________________________________________... | Python | zaydzuhri_stack_edu_python |
function subimage self x y w h center=none
begin
if xscale != 1.0 or yscale != 1.0
begin
call Logger string Can't subimage scaled sprites yet!
return none
end
if center
begin
set x = call X x - w / 2
set y = call Y y - h / 2
end
return call ScaledSprite image=call subsurface tuple x y w h rwidth=integer round w rheight... | def subimage(self, x, y, w, h, center=None):
if self.xscale != 1.0 or self.yscale != 1.0:
Logger("Can't subimage scaled sprites yet!\n")
return None
if center:
x = self.X(x) - (w/2)
y = self.Y(y) - (h/2)
return ScaledSprite(image=self.im.subsurface((x, y, w, h)),
rwidth=int(round(w)), rheight... | Python | nomic_cornstack_python_v1 |
from commons import *
class CBC_mode
begin
function __init__ self iv k
begin
set initialization_vector = iv
set key = k
end function
function encrypt self plaintext
begin
set ciphertext = b''
set iv = initialization_vector
while plaintext
begin
set block = plaintext at slice 0 : 16 :
comment padding if necessary
set b... | from commons import *
class CBC_mode:
def __init__(self, iv, k):
self.initialization_vector = iv
self.key = k
def encrypt(self, plaintext):
ciphertext = b''
iv = self.initialization_vector
while plaintext:
block = plaintext[0:16]
block = block +... | Python | zaydzuhri_stack_edu_python |
function init_dataset self
begin
comment makes sure that the zip actually exists.
assert is file path raw_path
print string Started initializing LISATL!
comment make subfolder inside INIT_FOLDER path.
make directories init_path exist_ok=true
comment unzips file into directory
with zip file raw_path string r as zip_ref
... | def init_dataset(self):
assert os.path.isfile(self.raw_path) # makes sure that the zip actually exists.
print("Started initializing LISATL!")
# make subfolder inside INIT_FOLDER path.
os.makedirs(self.init_path, exist_ok=True)
# unzips file into directory
... | Python | nomic_cornstack_python_v1 |
import csv
from os import read
with open string SOCR-HeightWeight.csv newline=string as f
begin
set reader = reader f
set file_data = list reader
end
pop file_data 0
set newData = list
for i in range length file_data
begin
set n_num = file_data at i at 2
append newData decimal n_num
end
comment print(i)
set n = length... | import csv
from os import read
with open("SOCR-HeightWeight.csv", newline = '') as f:
reader = csv.reader(f)
file_data = list(reader)
file_data.pop(0)
newData = []
for i in range (len(file_data)):
n_num = file_data[i][2]
newData.append(float(n_num))
#print(i)
n = len(newData)
newData.sort()
if n... | Python | zaydzuhri_stack_edu_python |
function find_next_binlog self
begin
set next_binlog = call find_next_binlog_from_lst_file
if next_binlog is none
begin
set next_binlog = call find_next_binlog_from_backup_store
end
if next_binlog is none
begin
set next_binlog = srv_binlog_first
info string No recorded last binlog in session, downloading all from sourc... | def find_next_binlog(self):
next_binlog = self.find_next_binlog_from_lst_file()
if next_binlog is None:
next_binlog = self.find_next_binlog_from_backup_store()
if next_binlog is None:
next_binlog = self.srv_binlog_first
logger.info('No recorded last binlog in... | Python | nomic_cornstack_python_v1 |
function __rmul__ self other
begin
if is instance other tuple
begin
return call transform_point other
end
if is instance other LinearTransformation
begin
return call right_composition other
end
else
begin
raise NotImplementedError
end
end function | def __rmul__(self, other):
if isinstance(other, tuple):
return self.transform_point(other)
if isinstance(other, LinearTransformation):
return self.right_composition(other)
else:
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
comment Container With Most Water
comment Problem Description
comment Given n non-negative integers A[0], A[1], ..., A[n-1] , where each represents a point at coordinate (i, A[i]).
comment N vertical lines are drawn such that the two endpoints of line i is at (i, A[i]) and (i, 0).
comment Find two lines, which together... | # Container With Most Water
# Problem Description
# Given n non-negative integers A[0], A[1], ..., A[n-1] , where each represents a point at coordinate (i, A[i]).
# N vertical lines are drawn such that the two endpoints of line i is at (i, A[i]) and (i, 0).
# Find two lines, which together with x-axis forms a containe... | Python | zaydzuhri_stack_edu_python |
comment 64ms
class Solution extends object
begin
function exclusiveTime self n logs
begin
string :type n: int :type logs: List[str] :rtype: List[int]
if not logs or logs == list
begin
return list 0 * n
end
set stack = list
set ans = list comprehension 0 for i in range n
set lastEnd = none
for i in range length logs
b... | class Solution(object): #64ms
def exclusiveTime(self, n, logs):
"""
:type n: int
:type logs: List[str]
:rtype: List[int]
"""
if not logs or logs == []:
return [0]*n
stack = []
ans = [0 for i in range(n)]
lastEnd = None
... | Python | zaydzuhri_stack_edu_python |
function reason self
begin
return get pulumi self string reason
end function | def reason(self) -> Optional[str]:
return pulumi.get(self, "reason") | Python | nomic_cornstack_python_v1 |
from datetime import datetime
import pickle
from tkinter import messagebox , ttk
from tkcalendar import DateEntry
from gui.parent_window import ParentWindow
class Create extends ParentWindow
begin
function __init__ self socket=none
begin
comment Attributi
set socket = socket
comment self.id_zone_lavoro_list = []
set id... | from datetime import datetime
import pickle
from tkinter import messagebox, ttk
from tkcalendar import DateEntry
from gui.parent_window import ParentWindow
class Create(ParentWindow):
def __init__(self, socket=None):
# Attributi
self.socket = socket
# self.id_zone_lavoro_list = []
... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
set _project = call CGTProject
call init_new_project
end function | def setUp(self):
self._project = CGTProject()
self._project.init_new_project() | Python | nomic_cornstack_python_v1 |
function test_fsspec_http httpserver
begin
set tree = dict string a 1
set af = call AsdfFile tree
set path = join path tmpdir string test
call write_to path
set fn = url + string test
with open fn as f
begin
set af = call open_asdf f
call assert_tree_match tree tree
end
end function | def test_fsspec_http(httpserver):
tree = {"a": 1}
af = AsdfFile(tree)
path = os.path.join(httpserver.tmpdir, "test")
af.write_to(path)
fn = httpserver.url + "test"
with fsspec.open(fn) as f:
af = open_asdf(f)
assert_tree_match(tree, af.tree) | Python | nomic_cornstack_python_v1 |
from __future__ import absolute_import
from flask import json
from bson import json_util , SON
from coati.core import BaseDocument , CustomQuerySet
comment dict of class/type -> func
set _type_map = dict
class RegisterError extends Exception
begin
string Raised if a (un)register operation cannot be performed.
end clas... | from __future__ import absolute_import
from flask import json
from bson import json_util, SON
from coati.core import BaseDocument, CustomQuerySet
# dict of class/type -> func
_type_map = {}
class RegisterError(Exception):
"""
Raised if a (un)register operation cannot be performed.
"""
class Transform... | Python | zaydzuhri_stack_edu_python |
function optimal_entry_interval_stop_loss self
begin
comment Checking if the sl level was allocated
if L is none
begin
raise exception string To use this function stop-loss level must be allocated.
end
comment Checking for the necessary condition
if not call _parameter_check
begin
raise exception string Please adjust y... | def optimal_entry_interval_stop_loss(self):
# Checking if the sl level was allocated
if self.L is None:
raise Exception("To use this function stop-loss level must be allocated.")
# Checking for the necessary condition
if not self._parameter_check():
rais... | Python | nomic_cornstack_python_v1 |
function has_flow_stats self
begin
return fields at string flow_stats at string enabled
end function | def has_flow_stats (self):
return self.fields['flow_stats']['enabled'] | Python | nomic_cornstack_python_v1 |
function create_trie strings
begin
set row_data = list
comment stores nodes for current word
set path = list 0
set last_s = call array_encode string
set node_count = 1
set records = dictionary
set depth = 0
for tuple record_id s_ in sorted enumerate strings key=lambda x -> x at 1
begin
set s = call array_encode s_
set... | def create_trie(strings):
row_data = []
path = [0] # stores nodes for current word
last_s = ut.array_encode('')
node_count = 1
records = numba.typed.Dict()
depth = 0
for record_id, s_ in sorted(enumerate(strings), key=lambda x: x[1]):
s = ut.array_encode(s_)
start = ut.comm... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Apr 1 23:14:09 2018 @author: Konrad
import tkinter as tk
import math
import random
class Particle
begin
function __init__ self canvas cWidth cHeight colour
begin
string Initialises the Particle object with specific parameters.
set radius ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 1 23:14:09 2018
@author: Konrad
"""
import tkinter as tk
import math
import random
class Particle():
def __init__(self, canvas, cWidth, cHeight, colour):
"""Initialises the Particle object with specific parameters."""
self.radi... | Python | zaydzuhri_stack_edu_python |
import os
import sys
import psutil
import time
function decrypt ciphertext key
begin
set plaintext = string
set i = 0
for ch in ciphertext
begin
set plaintext = plaintext + character ordinal ch ? ordinal key at i
set i = i + 1
set i = i % length key
end
return plaintext
end function
function edit file
begin
call start... | import os
import sys
import psutil
import time
def decrypt(ciphertext, key):
plaintext = ""
i=0
for ch in ciphertext:
plaintext += chr(ord(ch) ^ ord(key[i]))
i+=1
i=i%len(key)
return plaintext
def edit(file):
os.startfile(file)
i=False
while(i!=True):
i=True
for p in psutil.process_iter():
if(p.na... | Python | zaydzuhri_stack_edu_python |
from __future__ import print_function
function dec_sub c
begin
if c > 59
begin
if c > 90
begin
set res = c - 59
end
else
begin
set res = c - 53
end
end
else
begin
set res = c - 48
end
return res
end function
function decrypt script
begin
set result = string
set i = 0
while i < length script
begin
set dec = 0
set shift... | from __future__ import print_function
def dec_sub(c):
if c > 59:
if c > 90:
res = c - 59
else:
res = c - 53
else:
res = c - 48
return res
def decrypt(script):
result = ""
i = 0
while i < len(script):
dec = 0
shift = 0
whil... | Python | zaydzuhri_stack_edu_python |
function _plot_one_value data_matrix grid_metadata_dict colour_map_object min_colour_value max_colour_value plot_cbar_min_arrow plot_cbar_max_arrow log_scale=false
begin
set tuple figure_object axes_object = call subplots 1 1 figsize=tuple FIGURE_WIDTH_INCHES FIGURE_HEIGHT_INCHES
set tuple basemap_object basemap_x_matr... | def _plot_one_value(
data_matrix, grid_metadata_dict, colour_map_object, min_colour_value,
max_colour_value, plot_cbar_min_arrow, plot_cbar_max_arrow,
log_scale=False):
figure_object, axes_object = pyplot.subplots(
1, 1, figsize=(FIGURE_WIDTH_INCHES, FIGURE_HEIGHT_INCHES)
)
... | Python | nomic_cornstack_python_v1 |
import datetime
from django.test import TestCase
from django.utils import timezone
from catalog.forms import RenewBookForm
class RenewBookFormTest extends TestCase
begin
function test_renew_form_date_field_label self
begin
set form = call RenewBookForm
call assertEquals label string Nouvelle date de retour
end function... | import datetime
from django.test import TestCase
from django.utils import timezone
from catalog.forms import RenewBookForm
class RenewBookFormTest(TestCase):
def test_renew_form_date_field_label(self):
form = RenewBookForm()
self.assertEquals(
form.fields['renewal_date'].label,
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from scipy.interpolate import interp1d
from fit_blackbody import get_filter
import astropy.units as u
from astropy.table import Table
from scipy.ndimage.filters import gaussian_filter1d
from pysynphot import observation
from pysynphot import spectrum
function filter_flux tspectrum filtname minusepoin... | import numpy as np
from scipy.interpolate import interp1d
from fit_blackbody import get_filter
import astropy.units as u
from astropy.table import Table
from scipy.ndimage.filters import gaussian_filter1d
from pysynphot import observation
from pysynphot import spectrum
def filter_flux(tspectrum, filtname, minusepoint... | Python | zaydzuhri_stack_edu_python |
import os
from time import sleep
import json
from socket import socket , AF_INET , SOCK_STREAM
class Client
begin
function __init__ self host port name
begin
set sock = call socket AF_INET SOCK_STREAM
set ser_host = host
set ser_port = port
set name = name
set com_name = none
set score = string 0
set com_score = string... | import os
from time import sleep
import json
from socket import socket, AF_INET, SOCK_STREAM
class Client:
def __init__(self, host, port, name) -> None:
self.sock = socket(AF_INET, SOCK_STREAM)
self.ser_host = host
self.ser_port = port
self.name = name
self.com_name = None
... | Python | zaydzuhri_stack_edu_python |
function get_lxc_version
begin
set runner = partial check_output stderr=STDOUT universal_newlines=true
comment Old LXC had an lxc-version executable, and prefixed its result with
comment "lxc version: "
try
begin
set result = right strip call runner list string lxc-version
return call parse_version replace result strin... | def get_lxc_version():
runner = functools.partial(
subprocess.check_output,
stderr=subprocess.STDOUT,
universal_newlines=True,
)
# Old LXC had an lxc-version executable, and prefixed its result with
# "lxc version: "
try:
result = runner(['lxc-version']).rstrip()
... | Python | nomic_cornstack_python_v1 |
comment is the same as
set x = string John
set tuple x y z = tuple string Orange string Banana string Cherry
print x
print y
print z
set x = string Orange
set y = string Orange
set z = string Orange
print x
print y
print z
set fruits = list string apple string banana string cherry
set tuple x y z = fruits
print x
print... | # is the same as
x = 'John'
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
x = y = z = "Orange"
print(x)
print(y)
print(z)
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits
print(x)
print(y)
print(z)
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "aweso... | Python | zaydzuhri_stack_edu_python |
import base64
from email.mime.text import MIMEText
from email import errors
import os
import csv
from AsignacionArchivos import importar_archivos
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
set ARCHIVO_SECRET_CLIENT = string client_secret.json
set SCOPES = list string h... | import base64
from email.mime.text import MIMEText
from email import errors
import os
import csv
from AsignacionArchivos import importar_archivos
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
ARCHIVO_SECRET_CLIENT = 'client_secret.json'
SCOPES = [
'htt... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Jul 7 16:20:37 2020 @author: Administrator
import numpy as np
from sklearn.cluster import KMeans
import random
import itertools
import time
function geneticOp Pparent pc pm mu mum
begin
set Pchild = list
set max_var = 1
set min_var = 0
for i in range 0 length Pparent... | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 7 16:20:37 2020
@author: Administrator
"""
import numpy as np
from sklearn.cluster import KMeans
import random
import itertools
import time
def geneticOp(Pparent, pc, pm ,mu, mum):
Pchild = []
max_var = 1
min_var = 0
for i in range(0, len(Pparent), 2):
... | Python | zaydzuhri_stack_edu_python |
comment Given two grammars, do the initial checks on the difference sizes
comment on the root alternativess.
import CFG
import sys
comment def check_seq_sizes(seqs):
comment sizes = {}
comment for seq in seqs:
comment l = len(seq)
comment if sizes.has_key(l):
comment sizes[l] += sizes[l]
comment else:
comment sizes[l] ... | # Given two grammars, do the initial checks on the difference sizes
# on the root alternativess.
import CFG
import sys
#def check_seq_sizes(seqs):
# sizes = {}
# for seq in seqs:
# l = len(seq)
# if sizes.has_key(l):
# sizes[l] += sizes[l]
# else:
# sizes[l] = 1
#
# ... | Python | zaydzuhri_stack_edu_python |
function fiblen num_len
begin
set temp = 0
set temp2 = 1
set new_num = 0
set index = 0
while length string new_num < num_len
begin
set new_num = temp + temp2
set tuple temp2 temp = tuple temp new_num
set index = index + 1
end
return index
end function
print call fiblen 1000 | def fiblen(num_len):
temp = 0
temp2 = 1
new_num = 0
index = 0
while len(str(new_num)) < num_len:
new_num = temp + temp2
temp2, temp = temp, new_num
index += 1
return index
print(fiblen(1000)) | Python | zaydzuhri_stack_edu_python |
function select_action self suggested_action
begin
raise NotImplementedError
end function | def select_action(self, suggested_action):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function aws cluster
begin
set reservations = call get_all_instances filters=dict string tag:Cluster cluster ; string instance-state-name string running
set servers = dict string all list
set names = dictionary
for r in reservations
begin
for i in instances
begin
set name = public_dns_name
if string User in tags
begin
... | def aws(cluster):
reservations = ec2_conn.get_all_instances(
filters={
'tag:Cluster': cluster,
'instance-state-name': 'running'
})
servers = {'all': list()}
names = dict()
for r in reservations:
for i in r.instances:
... | Python | nomic_cornstack_python_v1 |
import plex
class ParseError extends Exception
begin
pass
end class
class MyParser
begin
function __init__ self
begin
set symbols = string string = string ( string )
set PRINT = string string print
set AND = string string and
set OR = string string or
set XOR = string string xor
set letter = range string azAZ
set digit... | import plex
class ParseError(Exception):
pass
class MyParser:
def __init__(self):
symbols = plex.Str('=', '(', ')')
PRINT = plex.Str("print")
AND = plex.Str('and')
OR = plex.Str('or')
XOR = plex.Str('xor')
letter = plex.Range('azAZ')
digit = plex.Range('09')
ID = letter+plex.Rep(letter|digit)
numb... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string @Time : 2021-11-13 15:03 @Auth : 一条咸鱼 @File :testDemo.py @IDE :PyCharm @Motto:ABC(Always Be Coding)
import unittest
import page
from page.main_page import MainPage
from tools.getdriver import GerDriver
from ddt import ddt , unpack , data
from tools.read_excel import Read_excel
class... | # -*- coding: utf-8 -*-
"""
@Time : 2021-11-13 15:03
@Auth : 一条咸鱼
@File :testDemo.py
@IDE :PyCharm
@Motto:ABC(Always Be Coding)
"""
import unittest
import page
from page.main_page import MainPage
from tools.getdriver import GerDriver
from ddt import ddt, unpack, data
from tools.read_excel import Read_excel
class ... | Python | zaydzuhri_stack_edu_python |
function print_data lines iline word msg nlines=20
begin
set msg = string word=%r %s % tuple word msg
set iline_start = iline - nlines
set iline_start = max iline_start 0
for iiline in range iline_start iline
begin
set msg = msg + lines at iiline
end
return msg
end function | def print_data(lines, iline, word, msg, nlines=20):
msg = 'word=%r\n%s\n' % (word, msg)
iline_start = iline - nlines
iline_start = max(iline_start, 0)
for iiline in range(iline_start, iline):
msg += lines[iiline]
return msg | Python | nomic_cornstack_python_v1 |
function with_artifact self name=none type_=none ext=none url=none configuration=none classifier=none
begin
set artifact = call Artifact name or name type_=type_ ext=ext url=url conf=configuration classifier=classifier
append artifacts artifact
return self
end function | def with_artifact(self, name=None, type_=None, ext=None, url=None, configuration=None,
classifier=None):
artifact = Artifact(name or self.name, type_=type_, ext=ext, url=url, conf=configuration,
classifier=classifier)
self.artifacts.append(artifact)
return se... | Python | nomic_cornstack_python_v1 |
comment pragma: no cover
function process_results self results=none **value
begin
return call default_result_processor results=results keyword value
end function | def process_results(self, results=None, **value): # pragma: no cover
return default_result_processor(results=results, **value) | Python | nomic_cornstack_python_v1 |
function cfngin indent output **_
begin
set content = call schema_json indent=indent
if output
begin
set file_path = call absolute
comment append empty line to end of file
call write_text content + string encoding=call getpreferredencoding do_setlocale=false
call success string output JSON schema to %s file_path
end
e... | def cfngin(indent: int, output: Optional[str], **_: Any) -> None:
content = CfnginConfigDefinitionModel.schema_json(indent=indent)
if output:
file_path = Path(output).absolute()
file_path.write_text( # append empty line to end of file
content + "\n", encoding=locale.getpreferredenco... | Python | nomic_cornstack_python_v1 |
function post_delete self *args **kw
begin
set pks = call get_primary_fields model
set d = dict
for tuple i arg in enumerate args
begin
set d at pks at i = arg
end
string extraer el idFase para poder retornar en el estado anterior
set idfase = first filter by query DBSession idFase id=d at string id
delete model d
cal... | def post_delete(self, *args, **kw):
pks = self.provider.get_primary_fields(self.model)
d = {}
for i, arg in enumerate(args):
d[pks[i]] = arg
"""extraer el idFase para poder retornar en el estado anterior """
idfase= DBSession.query(L... | Python | nomic_cornstack_python_v1 |
function first_win_symbol_inline symbol
begin
for i in range length paytable at symbol 0 - 1
begin
if paytable at symbol at i - 1 == 0
begin
set min_needed_symbols = i + 1
break
end
end
return min_needed_symbols
end function | def first_win_symbol_inline(symbol):
for i in range(len(paytable[symbol]), 0, -1):
if paytable[symbol][i - 1] == 0:
min_needed_symbols = i + 1
break
return min_needed_symbols | Python | nomic_cornstack_python_v1 |
function write_binary self write_in_position byte_format *data_to_write
begin
set write = call pack byte_format *data_to_write
end function | def write_binary(self, write_in_position, byte_format, *data_to_write):
write = struct.pack(byte_format, *data_to_write)
| Python | nomic_cornstack_python_v1 |
function time_12 value
begin
try
begin
set time = string parse time value string %H:%M
set new_time = string format time datetime time string %I:%M%p
return new_time
end
except ValueError
begin
return value
end
end function | def time_12(value):
try:
time = datetime.datetime.strptime(value, '%H:%M')
new_time = datetime.datetime.strftime(time, '%I:%M%p')
return new_time
except ValueError:
return value | Python | nomic_cornstack_python_v1 |
function extract_gest_age_from_note s reg_exps verbose=false
begin
comment We want to find the maximum reported value in the clinical note
set tuple match_str max_days_ga max_weeks_ga_round = tuple none 0 0
comment Reformat string to lowercase without new line characters
set s = lower replace s string string
comment F... | def extract_gest_age_from_note(s, reg_exps, verbose=False):
# We want to find the maximum reported value in the clinical note
match_str, max_days_ga, max_weeks_ga_round = None, 0, 0
# Reformat string to lowercase without new line characters
s = s.replace('\n', ' ').lower()
# Filter out false strin... | Python | nomic_cornstack_python_v1 |
comment bear and milky cookies
comment iterating till the range and taking the no of elements as input.
for i in range integer input
begin
comment takes interger input from the user
set n = integer input
comment This function helps in getting a multiple inputs from user. It breaks the given input by the specified separ... | #bear and milky cookies
#iterating till the range and taking the no of elements as input.
for i in range(int(input())):
#takes interger input from the user
n = int(input())
#This function helps in getting a multiple inputs from user. It breaks the given input by the specified separator. If a separator is no... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from Fullscrn import *
from tkinter import messagebox
import datetime
set now = now
set today = string format time now string %Y-%m-%d
import sqlite3
function donate a c
begin
set root2 = call Tk
call destroy
call geometry string 500x500+120+120
title root2 string Blood Bank
call geometry string 5... | from tkinter import *
from Fullscrn import *
from tkinter import messagebox
import datetime
now = datetime.datetime.now()
today=now.strftime("%Y-%m-%d")
import sqlite3
def donate(a,c):
root2 = Tk()
a.destroy()
root2.geometry("500x500+120+120")
root2.title("Blood Bank")
root2.geomet... | Python | zaydzuhri_stack_edu_python |
async function get_play_state self player_id
begin
set results = await call string player string get_play_state pid=player_id
if string state not in vars
begin
raise call InvalidResponse string Could not find "state" entry in response results
end
return call PlayState vars at string state
end function | async def get_play_state(self, player_id: int) -> models.player.PlayState:
results = await self._api.call('player', 'get_play_state', pid=player_id)
if 'state' not in results.header.vars:
raise InvalidResponse('Could not find "state" entry in response', results)
return models.player... | Python | nomic_cornstack_python_v1 |
from tkinter import *
from tkinter import scrolledtext
from tkinter import messagebox
from tkinter import filedialog
from tkinter.ttk import *
from time import sleep
import pandas as pd
function firstExample
begin
comment creates our window
set window = call Tk
comment titles it and shapes it
title window string Mercur... | from tkinter import *
from tkinter import scrolledtext
from tkinter import messagebox
from tkinter import filedialog
from tkinter.ttk import *
from time import sleep
import pandas as pd
def firstExample():
#creates our window
window=Tk()
#titles it and shapes it
window.title('Mercury Main Window')
... | 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.