code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from selenium import webdriver
import time
function com_reg
begin
set msg = string My order was marked for return on July 1, and was picked from my residence on July 2. Since that day I have made numerous calls and emails to myntra.com to know more about the return request but was only told to wait a few more days. My ... | from selenium import webdriver
import time
def com_reg():
msg = "My order was marked for return on July 1, and was picked from my residence on July 2. Since that day I have made numerous calls and emails to myntra.com to know more about the return request but was only told to wait a few more days. My registered compl... | Python | zaydzuhri_stack_edu_python |
import string
set fi = open string final.tsv
set st = read fi
set list1 = split st string
remove list1 string
close fi
set list2 = list
for i in list1
begin
set buff = split i string
set buff1 = split buff at 7 string ,
for b in buff1
begin
append list2 b + string + buff at 8
end
end
set fi = open string genre.tsv st... | import string
fi=open('final.tsv')
st=fi.read()
list1=st.split('\n')
list1.remove('')
fi.close()
list2=[]
for i in list1:
buff=i.split('\t')
buff1=buff[7].split(',')
for b in buff1:
list2.append(b+'\t'+buff[8])
fi=open('genre.tsv','w')
for i in list2:
fi.write(i+'\n')
fi.close()
| Python | zaydzuhri_stack_edu_python |
comment //Step 1: reverse the entire array.
comment //Step 2: reverse each word.
comment //time: O(2n) ... O(N)
comment //space: O(1) ... linear.
comment public class ReverseWordsArray {
comment char[] reverseWords(char[] a) {
comment reverse(a, 0, a.length - 1); //step 1
comment int start = 0, end = 0;
comment while (... | # //Step 1: reverse the entire array.
# //Step 2: reverse each word.
# //time: O(2n) ... O(N)
# //space: O(1) ... linear.
# public class ReverseWordsArray {
# char[] reverseWords(char[] a) {
# reverse(a, 0, a.length - 1); //step 1
# int start = 0, end = 0;
# while (end < a.length) { //ste... | Python | zaydzuhri_stack_edu_python |
function run_test_case_session solution
begin
set test_cases = ordered dictionary list tuple string yyyyesss string match tuple string yyeeees string match tuple string yyss string match tuple string y string skip
set resultList = list
set solved = true
for case in test_cases
begin
set objective = test_cases at case
s... | def run_test_case_session(solution):
test_cases = OrderedDict([('yyyyesss', 'match'),
('yyeeees', 'match'),
('yyss', 'match'),
('y', 'skip')
]
)
resultList = []
... | Python | nomic_cornstack_python_v1 |
comment /usr/bin/env python
import unittest
import numpy
from numpy.testing import *
from import SimpleLineSearch , AdaptiveLastStepModifier
from function import Function
class test_AdaptiveLastStepModifier extends TestCase
begin
function test_call self
begin
set lineSearch = call AdaptiveLastStepModifier call SimpleL... | #/usr/bin/env python
import unittest
import numpy
from numpy.testing import *
from .. import SimpleLineSearch, AdaptiveLastStepModifier
from .function import Function
class test_AdaptiveLastStepModifier(unittest.TestCase):
def test_call(self):
lineSearch = AdaptiveLastStepModifier(SimpleLineSearch())
stat... | Python | zaydzuhri_stack_edu_python |
function setReadOnly self readOnlyFlag
begin
set readOnlyFlag = readOnlyFlag
comment Set the internal widgets as readonly or not depending on this flag.
call setReadOnly true
call setReadOnly true
call setEnabled not readOnlyFlag
call setEnabled not readOnlyFlag
call setEnabled not readOnlyFlag
call setEnabled not read... | def setReadOnly(self, readOnlyFlag):
self.readOnlyFlag = readOnlyFlag
# Set the internal widgets as readonly or not depending on this flag.
self.internalNameLineEdit.setReadOnly(True)
self.uuidLineEdit.setReadOnly(True)
self.xScalingDoubleSpinBox.setEnabled(not self.re... | Python | nomic_cornstack_python_v1 |
import re
from flask import Flask
set app = call Flask __name__
decorator call route string /temperature
function temperature
begin
set data = open string /sys/bus/w1/devices/28-01131b863d3e/w1_slave string r
set readdata = read data
set t = find all string t=.* readdata
set temperature = decimal strip t at 0 string t=... | import re
from flask import Flask
app = Flask(__name__)
@app.route('/temperature')
def temperature():
data = open("/sys/bus/w1/devices/28-01131b863d3e/w1_slave", "r")
readdata= data.read()
t = re.findall('t=.*', readdata)
temperature = float(t[0].strip('t='))/1000
data.close()
return str(temp... | Python | zaydzuhri_stack_edu_python |
function _values self
begin
string Getter for series values (flattened)
return list comprehension val at 1 for serie in series for val in if expression interpolate then interpolated else points if val at 1 is not none and not logarithmic or val at 1 > 0
end function | def _values(self):
"""Getter for series values (flattened)"""
return [
val[1] for serie in self.series for val in
(serie.interpolated if self.interpolate else serie.points)
if val[1] is not None and (not self.logarithmic or val[1] > 0)
] | Python | jtatman_500k |
function _get_long_path_name path
begin
string Returns the long path name for a Windows path, i.e. the properly cased path of an existing file or directory.
comment Thanks to http://stackoverflow.com/a/3694799/791713
set buf = call create_unicode_buffer length path + 1
set GetLongPathNameW = GetLongPathNameW
set res = ... | def _get_long_path_name(path):
"""
Returns the long path name for a Windows path, i.e. the properly cased
path of an existing file or directory.
"""
# Thanks to http://stackoverflow.com/a/3694799/791713
buf = ctypes.create_unicode_buffer(len(path) + 1)
GetLongPathNameW = ctypes.windll.kernel32.GetLongPat... | Python | jtatman_500k |
function add_table_row self table_name row ignore_missing=false
begin
if table_name not in tables
begin
raise exception string Table does not exist.
end
for column in tables at table_name
begin
if column in row
begin
append tables at table_name at column row at column
end
else
if ignore_missing
begin
append tables at t... | def add_table_row(self, table_name, row, ignore_missing=False):
if table_name not in self.tables:
raise Exception("Table does not exist.")
for column in self.tables[table_name]:
if column in row:
self.tables[table_name][column].append(row[column])
eli... | Python | nomic_cornstack_python_v1 |
string User Story 08 (US08) - Test File US08: Birth before marriage of parents @Author: David Tsu
import unittest , os , io , sys
from ssw555a_ged import GED_Repo
class Test_US08 extends TestCase
begin
string Tests that the check_bday function throws when expected.
function test_check_bday1 self
begin
string Tests that... | """
User Story 08 (US08) - Test File
US08: Birth before marriage of parents
@Author: David Tsu
"""
import unittest, os, io, sys
from ssw555a_ged import GED_Repo
class Test_US08(unittest.TestCase):
""" Tests that the check_bday function throws when expected. """
def test_check_bday1(self):
""" Tests t... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*-coding:utf-8-*-
import os
from time import localtime , strftime
from base64 import b64encode
from bencode import bdecode
function getInfo
begin
set torrNum = 0
set path = get current directory
set sep = sep
set torrentSet = list comprehension filename for filename in list directo... | #!/usr/bin/env python
# -*-coding:utf-8-*-
import os
from time import localtime, strftime
from base64 import b64encode
from bencode import bdecode
def getInfo():
torrNum = 0
path = os.getcwd()
sep = os.sep
torrentSet = [filename for filename in os.listdir(path) if filename.split('.')[-1] == 'torrent'... | Python | zaydzuhri_stack_edu_python |
function _identities_iter self
begin
set cc = coordinate_conversion
for prop in tuple string standard_name string grid_mapping_name
begin
set n = call get_parameter prop none
if n is not none
begin
yield string { prop } : { n }
end
end
set ncvar = call nc_get_variable none
if ncvar is not none
begin
yield string ncvar%... | def _identities_iter(self):
cc = self.coordinate_conversion
for prop in ("standard_name", "grid_mapping_name"):
n = cc.get_parameter(prop, None)
if n is not None:
yield f"{prop}:{n}"
ncvar = self.nc_get_variable(None)
if ncvar is not None:
... | Python | nomic_cornstack_python_v1 |
function visit_exercise_title_node_ self node
begin
raise NotImplemented
end function | def visit_exercise_title_node_(self, node):
raise NotImplemented | Python | nomic_cornstack_python_v1 |
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
set heart_train = read csv string heart_train.csv
set heart_test = read csv string heart_test.csv
set heart_train_norm = heart_train
set heart_test_norm = heart_test
set Y_train = values
set Y_test = values
set X_train = drop heart_train list string CAD... | import pandas as pd
from sklearn.preprocessing import MinMaxScaler
heart_train = pd.read_csv('heart_train.csv')
heart_test = pd.read_csv('heart_test.csv')
heart_train_norm = heart_train
heart_test_norm = heart_test
Y_train = heart_train.CAD_Yes.values
Y_test = heart_test.CAD_Yes.values
X_train = heart_train.drop(['... | Python | zaydzuhri_stack_edu_python |
function user_feedback df message
begin
print string ****************************
print message
call printSchema
print string ****************************
end function | def user_feedback(df, message):
print('****************************')
print(message)
df.printSchema()
print('****************************') | Python | nomic_cornstack_python_v1 |
function sha256sum filename
begin
set content = read open filename string rb
set sha256_obj = sha256 content
return hex digest sha256_obj
end function | def sha256sum(filename):
content = open(filename, 'rb').read()
sha256_obj = hashlib.sha256(content)
return sha256_obj.hexdigest() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment *-*coding:utf-8 *-*
string 29-4 主Game模块(Squish.py) 这个模块包括Squish游戏的主要游戏逻辑
import os , sys , pygame
from pygame.locals import *
import objects , config
class State
begin
string 泛型游戏的超类,可以处理事件并且在给定的表面上显示自身
function handle self event
begin
string 只处理退出事件的默认事件处理
if type == QUIT
begin
exit
en... | #!/usr/bin/python
# *-*coding:utf-8 *-*
"""
29-4 主Game模块(Squish.py)
这个模块包括Squish游戏的主要游戏逻辑
"""
import os, sys, pygame
from pygame.locals import *
import objects, config
class State:
"""泛型游戏的超类,可以处理事件并且在给定的表面上显示自身"""
def handle(self, event):
"""只处理退出事件的默认事件处理"""
if event.type == QUIT:
sys.exit()
if event.t... | Python | zaydzuhri_stack_edu_python |
function generate_google_host hostin hostout
begin
set platforms = list string linux string windows string darwin
set inouts = dictionary comprehension join path hostin plat string platform-tools : join path hostout format string {0}-x86 plat string bin for plat in platforms
for tuple infile outfile in items inouts
beg... | def generate_google_host(hostin, hostout):
platforms = ["linux", "windows", "darwin"]
inouts = {os.path.join(hostin, plat, "platform-tools"): os.path.join(hostout, "{0}-x86".format(plat), "bin") for plat in platforms}
for infile, outfile in inouts.items():
shutil.copytree(infile, outfile) | Python | nomic_cornstack_python_v1 |
function empty self
begin
return not pushStack and not popStack
end function | def empty(self):
return not self.pushStack and not self.popStack | Python | nomic_cornstack_python_v1 |
function chain annotations default=none
begin
function follow key
begin
for annot in annotations
begin
try
begin
set key = annot at key
end
except KeyError
begin
return default
end
end
return key
end function
return generator expression tuple key call follow key for key in annotations at 0
end function | def chain(annotations, default=None):
def follow(key):
for annot in annotations:
try:
key = annot[key]
except KeyError:
return default
return key
return ((key, follow(key)) for key in annotations[0]) | Python | nomic_cornstack_python_v1 |
function mol_fingerprint molobject fp=none
begin
set afp = call available_fingerprints
if toolkit not in afp
begin
print format string No fingerprint methods supported by toolkit {0} toolkit
return
end
if fp
begin
if fp not in afp at toolkit
begin
print format string Fingerprint methods {0} not supported by toolkit {1}... | def mol_fingerprint(molobject, fp=None):
afp = available_fingerprints()
if molobject.toolkit not in afp:
print('No fingerprint methods supported by toolkit {0}'.format(molobject.toolkit))
return
if fp:
if fp not in afp[molobject.toolkit]:
print('Fingerprint methods {0} ... | Python | nomic_cornstack_python_v1 |
import datetime
set k = list comprehension integer i for i in split input
set d1 = call date k at 0 k at 1 k at 2
set delta = time delta integer input
set d2 = d1 + delta
print string format time d2 string %Y %m %d | import datetime
k = [int(i) for i in input().split()]
d1 = datetime.date(k[0], k[1], k[2])
delta = datetime.timedelta(int(input()))
d2 = d1 + delta
print(d2.strftime("%Y %m %d")) | Python | zaydzuhri_stack_edu_python |
comment 유효한 애너그램
comment t가 s의 애너그램인지 판별하라.
from collections import Counter
class Solution extends object
begin
function isAnagram self s t
begin
string :type s: str :type t: str :rtype: bool
return sorted s == sorted t
end function
function isAnagram2 self s t
begin
set hash_table = dictionary counter s
set hash_table... | # 유효한 애너그램
# t가 s의 애너그램인지 판별하라.
from collections import Counter
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(s)==sorted(t)
def isAnagram2(self, s, t):
hash_table = dict(Coun... | Python | zaydzuhri_stack_edu_python |
function create_scotoma_fnc specifications dprime_fnc
begin
if length specifications < 1
begin
raise call ValueError string Too few arguments for scotoma mask
end
set delimiting_type = pop specifications 0
end function | def create_scotoma_fnc(specifications,dprime_fnc):
if len(specifications) < 1:
raise ValueError("Too few arguments for scotoma mask")
delimiting_type = specifications.pop(0) | Python | nomic_cornstack_python_v1 |
function write self file_name rk=none
begin
info string Writing NK correlations to %s file_name
set tuple xi varxi = call calculateXi rk
call gen_write file_name list string R_nom string <R> string <kappa> string sigma string weight string npairs list exp logr exp meanlogr xi square root varxi weight npairs
end functio... | def write(self, file_name, rk=None):
self.logger.info('Writing NK correlations to %s',file_name)
xi, varxi = self.calculateXi(rk)
self.gen_write(
file_name,
['R_nom','<R>','<kappa>','sigma','weight','npairs'],
[ numpy.exp(self.logr), numpy.exp(self.meanlogr)... | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
import math
set height = 1.75
set weight = 80.5
set bmi = weight / height * height
if bmi < 18.5
begin
print string 过轻
end
else
if 18.5 <= bmi < 25
begin
print string 正常
end
else
if 25 <= bmi < 28
begin
print string 过重
end
else
if 28 <= bmi < 32
begin
print string 肥胖
end
else
begin
print st... | # -*- coding:utf-8 -*-
import math
height = 1.75
weight = 80.5
bmi = weight/(height*height)
if bmi<18.5:
print('过轻')
elif 18.5<=bmi<25:
print('正常')
elif 25<=bmi<28:
print('过重')
elif 28<=bmi<32:
print('肥胖')
else:
print('严重肥胖') | Python | zaydzuhri_stack_edu_python |
comment pylint: disable=invalid-name
function save_and_restore self _func=none **config_values
begin
if not _func
begin
return partial save_and_restore keyword config_values
end
decorator wraps _func
function _saving_wrapper *args **kwargs
begin
set saved_config = dictionary _loaded_values
try
begin
call load_from_dict... | def save_and_restore(self, _func=None, **config_values): # pylint: disable=invalid-name
if not _func:
return functools.partial(self.save_and_restore, **config_values)
@functools.wraps(_func)
def _saving_wrapper(*args, **kwargs):
saved_config = dict(self._loaded_values)
try:
self.... | Python | nomic_cornstack_python_v1 |
function signature_version self
begin
return self at string Sns at string SignatureVersion
end function | def signature_version(self) -> str:
return self["Sns"]["SignatureVersion"] | Python | nomic_cornstack_python_v1 |
function compute_sensitivities_to self compute_sensitivities_to
begin
comment noqa: E501
set allowed_values = list string MAXIMIZE_FORCE string MINIMIZE_FORCE
comment noqa: E501
if client_side_validation and compute_sensitivities_to not in allowed_values
begin
raise call ValueError format string Invalid value for `comp... | def compute_sensitivities_to(self, compute_sensitivities_to):
allowed_values = ["MAXIMIZE_FORCE", "MINIMIZE_FORCE"] # noqa: E501
if self.local_vars_configuration.client_side_validation and compute_sensitivities_to not in allowed_values: # noqa: E501
raise ValueError(
"Inval... | Python | nomic_cornstack_python_v1 |
for i in range 1 n
begin
set s at i = s at i - 1 + integer input
end
set current = 0
set total_dis = 0
for _ in range m
begin
set a = integer input
set total_dis = total_dis + absolute s at current + a - s at current % mod
set current = current + a
end
print total_dis | for i in range(1, n):
s[i] = s[i-1] + int(input())
current = 0
total_dis = 0
for _ in range(m):
a = int(input())
total_dis = (total_dis + abs(s[current+a]-s[current])) % mod
current += a
print(total_dis) | Python | zaydzuhri_stack_edu_python |
from collections import deque
set N = integer input
set A = list map int split input
set Q = deque
for i in range 2 ^ N
begin
append Q list A at i i + 1
end
while length Q > 2
begin
set tuple rate1 num1 = call popleft
set tuple rate2 num2 = call popleft
if rate1 < rate2
begin
append Q list rate2 num2
end
else
begin
app... | from collections import deque
N = int(input())
A = list(map(int, input().split()))
Q = deque()
for i in range(2**N):
Q.append([A[i],i+1])
while len(Q) > 2:
rate1,num1 = Q.popleft()
rate2,num2 = Q.popleft()
if rate1 < rate2:
Q.append([rate2,num2])
else:
Q.append([rate1,num1])
rate1,... | Python | zaydzuhri_stack_edu_python |
function copy_tags tags read1 read2
begin
for tag in tags
begin
try
begin
set read1_tag = call get_tag tag with_value_type=true
call set_tag tag value=read1_tag at 0 value_type=read1_tag at 1
end
except KeyError
begin
pass
end
end
return read2
end function | def copy_tags(tags, read1, read2):
for tag in tags:
try:
read1_tag = read1.get_tag(tag, with_value_type=True)
read2.set_tag(tag, value=read1_tag[0], value_type=read1_tag[1])
except KeyError:
pass
return read2 | Python | nomic_cornstack_python_v1 |
import os
import base64
from PIL import Image
import os.path
try
begin
from StringIO import StringIO
end
except ImportError
begin
from io import StringIO
end
function image_as_base64 image_file format=string png
begin
string :param `image_file` for the complete path of image. :param `format` is format for image, eg: `p... | import os
import base64
from PIL import Image
import os.path
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
def image_as_base64(image_file, format='png'):
"""
:param `image_file` for the complete path of image.
:param `format` is format for image, eg: `png` or `jpg`.... | Python | zaydzuhri_stack_edu_python |
function acquire self needs_lock=true
begin
string Acquiring a file object from the manager. A new file is only opened if it has expired from the least-recently-used cache. This method uses a lock, which ensures that it is thread-safe. You can safely acquire a file in multiple threads at the same time, as long as the u... | def acquire(self, needs_lock=True):
"""Acquiring a file object from the manager.
A new file is only opened if it has expired from the
least-recently-used cache.
This method uses a lock, which ensures that it is thread-safe. You can
safely acquire a file in multiple threads at t... | Python | jtatman_500k |
function resample signal sampleRate newSampleRate
begin
set nbSamples = integer newSampleRate * size / sampleRate
set signal = call resample signal nbSamples
set signal = call int16 signal
return signal
end function | def resample(signal, sampleRate, newSampleRate):
nbSamples = int(newSampleRate*signal.size/sampleRate)
signal = sp.signal.resample( signal, nbSamples)
signal = np.int16(signal)
return signal | Python | nomic_cornstack_python_v1 |
string Sends and receives queries made to Google Maps Embed API & Google Geocode API File: MapHandler.py
from flask_googlemaps import Map
import googlemaps
class MapHandler
begin
function __init__ self location=string data=dict
begin
comment Default map of USA
if location is string
begin
set lat = 37.0902
set long = ... | """
Sends and receives queries made to
Google Maps Embed API & Google Geocode API
File: MapHandler.py
"""
from flask_googlemaps import Map
import googlemaps
class MapHandler():
def __init__(self, location="", data={}):
# Default map of USA
if location is "":
lat = 37.0902
l... | Python | zaydzuhri_stack_edu_python |
string Задание конволюционного блока: Конволюция -> Нормализация -> функция активации
function conv_bn_relu in_planes out_planes kernel=3 stride=1 padding=1
begin
set net = sequential conv 2d in_planes out_planes kernel_size=kernel stride=stride padding=1 call BatchNorm2d num_features=out_planes relu true
return net
en... | """ Задание конволюционного блока: Конволюция -> Нормализация -> функция активации """
def conv_bn_relu(in_planes, out_planes, kernel=3, stride=1, padding=1):
net = nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=kernel, stride=stride, padding=1),
nn.BatchNorm2d(num_features=ou... | Python | zaydzuhri_stack_edu_python |
from __future__ import division
import tensorflow as tf
import numpy as np
import math
from base import Layer
from import activations
from import initializations as init
from utils import print_activations
from config import BerryKeys
set __all__ = list string Flatten
class Flatten extends Layer
begin
string Flatten ... | from __future__ import division
import tensorflow as tf
import numpy as np
import math
from .base import Layer
from .. import activations
from .. import initializations as init
from ..utils import print_activations
from ..config import BerryKeys
__all__ = [
"Flatten"
]
class Flatten(Layer):
"""Flatten layer
... | Python | zaydzuhri_stack_edu_python |
function import_init self request
begin
for channel in channels
begin
call sync_channel channel
end
info string [IMPORT Completed
set importer = call Importer
return importer
end function | def import_init(self, request):
for channel in request.channels:
self.sync_channel(channel)
logging.info('[IMPORT Completed')
importer = Importer()
return importer | Python | nomic_cornstack_python_v1 |
function _to_units_container a registry=none
begin
if is instance a str and string = in a
begin
return tuple call to_units_container split a string = 1 at 1 true
end
return tuple call to_units_container a registry false
end function | def _to_units_container(a, registry=None):
if isinstance(a, str) and "=" in a:
return to_units_container(a.split("=", 1)[1]), True
return to_units_container(a, registry), False | Python | nomic_cornstack_python_v1 |
function get_py_obj_dtype obj
begin
if is instance obj tuple Type type
begin
return call pytype_to_dtype obj
end
return call pytype_to_dtype type obj
end function | def get_py_obj_dtype(obj):
if isinstance(obj, (typing.Type, type)):
return pytype_to_dtype(obj)
return pytype_to_dtype(type(obj)) | Python | nomic_cornstack_python_v1 |
function GetMeanDifference self
begin
return call itkComparisonImageFilterIUS3IUS3_GetMeanDifference self
end function | def GetMeanDifference(self) -> "double":
return _itkComparisonImageFilterPython.itkComparisonImageFilterIUS3IUS3_GetMeanDifference(self) | Python | nomic_cornstack_python_v1 |
function action_space self
begin
pass
end function | def action_space(self) -> List:
pass | Python | nomic_cornstack_python_v1 |
function merge_tags ls
begin
if not is instance ls list
begin
raise call TypeError string ``ls`` is not an instance from ``list``
end
if length ls == 0
begin
return dict
end
function recursion index retval memo
begin
comment basecase
if index >= length ls
begin
return retval
end
comment do stuff to retval and memo
set... | def merge_tags(ls):
if not isinstance(ls, list):
raise TypeError("``ls`` is not an instance from ``list``")
if len(ls) == 0:
return {}
def recursion(index, retval, memo):
# basecase
if index >= len(ls):
return retval
# do stuff to retval and memo
... | Python | nomic_cornstack_python_v1 |
function get_parent self **kwargs
begin
from canvasapi.course import Course
from canvasapi.group import Group
set response = call request string GET format string {}s/{} parent_type parent_id _kwargs=call combine_kwargs keyword kwargs
if parent_type == string group
begin
return call Group _requester json response
end
e... | def get_parent(self, **kwargs):
from canvasapi.course import Course
from canvasapi.group import Group
response = self._requester.request(
"GET",
"{}s/{}".format(self.parent_type, self.parent_id),
_kwargs=combine_kwargs(**kwargs),
)
if self.pa... | Python | nomic_cornstack_python_v1 |
from functools import reduce
from enum import Enum
import db
class ItemEvent extends Enum
begin
set Purchased = string Purchased
set Sold = string Sold
set Undo = string Undo
end class
function parse_purchase_history match_data timeline_data
begin
if match_data at string gameMode != string CLASSIC
begin
return
end
set ... | from functools import reduce
from enum import Enum
import db
class ItemEvent(Enum):
Purchased = 'Purchased'
Sold = "Sold"
Undo = "Undo"
def parse_purchase_history(match_data: dict, timeline_data: dict) -> dict:
if match_data['gameMode'] != 'CLASSIC':
return
players = {participant['partic... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
comment define the locations
set fileOpen = open string nodes.txt string r
set location = call splitlines
close fileOpen
print location
comment mapping into a graph
set G = call read_edgelist string edges_of_nodes.txt create_using=call Graph nodet... | import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
# define the locations
fileOpen = open("nodes.txt", "r")
location = fileOpen.read().splitlines()
fileOpen.close()
print(location)
# mapping into a graph
G = nx.read_edgelist("edges_of_nodes.txt", create_using=nx.Graph(), nodetype=str)... | Python | zaydzuhri_stack_edu_python |
comment if a > b: print("A is greater than b")
if expression a < b then print b string is greater than a else print a string is grater than b | # if a > b: print("A is greater than b")
print(b,"is greater than",a) if a<b else print(a,"is grater than",b) | Python | zaydzuhri_stack_edu_python |
function DeleteProduct self data selected
begin
if selected != string
begin
set cur = call cursor
execute cur string DELETE FROM products WHERE id = ' + string selected + string '
commit __connection
call setMessage string Delete was successful!
end
else
begin
call setMessage string Select a row!
end
end function | def DeleteProduct(self, data, selected):
if selected != "":
cur = self.__connection.cursor()
cur.execute("DELETE FROM products WHERE id = '" +
str(selected) + "'")
self.__connection.commit()
data.setMessage("Delete was successful!")
... | Python | nomic_cornstack_python_v1 |
comment -*-coding:utf-8-*-
set L = list tuple string Bob 75 tuple string Adam 92 tuple string Bart 66 tuple string Lisa 88
function by_name t
begin
return t at 0
end function
set L1 = sorted L key=by_name
print L1
function by_score t
begin
return t at 1
end function
set L2 = sorted L key=by_score reverse=true
print L2 | #-*-coding:utf-8-*-
L = [('Bob',75),('Adam',92),('Bart',66),('Lisa',88)]
def by_name(t):
return t[0]
L1 = sorted(L, key = by_name)
print(L1)
def by_score(t):
return t[1]
L2 = sorted(L, key = by_score , reverse = True)
print(L2)
| Python | zaydzuhri_stack_edu_python |
function post self args
begin
if string Private-Token not in headers
begin
call abort 401 string User Unauthorized
end
set user = dict string email args at string email ; string password args at string password ; string username args at string username ; string name args at string name
set token = headers at string Pri... | def post(self, args):
if 'Private-Token' not in request.headers:
abort(401, 'User Unauthorized')
user = {
'email': args['email'],
'password': args['password'],
'username': args['username'],
'name': args['name']
}
token = req... | Python | nomic_cornstack_python_v1 |
comment 24. Выполнить обработку элементов прямоугольной матрицы ,
comment имеющей n строк и m столбцов. Найти наименьшее значение среди
comment средних значений для каждой строки матрицы.
import numpy as np
import random
function mean a
begin
return sum a / length a
end function
set n = integer input string n =
set m =... | #24. Выполнить обработку элементов прямоугольной матрицы ,
#имеющей n строк и m столбцов. Найти наименьшее значение среди
#средних значений для каждой строки матрицы.
import numpy as np
import random
def mean(a):
return (sum(a)/len(a));
n = int(input('n = '));
m = int(input('m = '));
a = np.empty ((n, m), dtype... | Python | zaydzuhri_stack_edu_python |
function mean_squared_logarithmic_error y_true y_pred
begin
set y_pred = call convert_to_tensor_v2_with_dispatch y_pred
set y_true = call cast y_true dtype
set first_log = log call maximum y_pred call epsilon + 1.0
set second_log = log call maximum y_true call epsilon + 1.0
return mean backend call squared_difference f... | def mean_squared_logarithmic_error(y_true, y_pred):
y_pred = tensor_conversion.convert_to_tensor_v2_with_dispatch(y_pred)
y_true = math_ops.cast(y_true, y_pred.dtype)
first_log = math_ops.log(backend.maximum(y_pred, backend.epsilon()) + 1.)
second_log = math_ops.log(backend.maximum(y_true, backend.epsilon()) + ... | Python | nomic_cornstack_python_v1 |
class NoneDict extends dict
begin
function __getitem__ self key
begin
return get dict self key
end function
end class | class NoneDict(dict):
def __getitem__(self, key):
return dict.get(self, key)
| Python | jtatman_500k |
import numpy as np
from functools import partial
class Cover
begin
string Function that partitions numbers to overlapping intervals. Returns list of intervals (each interval is a pair of numbers - bounds).
function __init__ self cover_function=string linear **kwargs
begin
if cover_function == string linear
begin
set _c... | import numpy as np
from functools import partial
class Cover:
"""
Function that partitions numbers to overlapping intervals.
Returns list of intervals (each interval is a pair of numbers - bounds).
"""
def __init__(self, cover_function='linear', **kwargs):
if cover_function == 'linear':
... | Python | zaydzuhri_stack_edu_python |
function _write_data fil filedata
begin
set f = open fil string w
write f encode filedata string utf-8
close f
end function | def _write_data(fil, filedata):
f = open(fil, 'w')
f.write(filedata.encode('utf-8'))
f.close() | Python | nomic_cornstack_python_v1 |
function is_unknown cls
begin
return false
end function | def is_unknown(cls):
return False | Python | nomic_cornstack_python_v1 |
function steal_blockchain peer
begin
set response = get requests string http:// { peer } /api/blockchain/chain
if status_code == 200
begin
try
begin
return call from_json loads text
end
except Exception
begin
debug string [PEER] Failed fetching blockchain from peer { peer }
return none
end
end
return none
end function | def steal_blockchain(peer: Peer) -> Blockchain.BlockChain:
response = requests.get(f'http://{peer}/api/blockchain/chain')
if response.status_code == 200:
try:
return Blockchain.BlockChain.from_json(json.loads(response.text))
except Exception:
log.debug(f'[PEER] Failed fetching blockchain from ... | Python | nomic_cornstack_python_v1 |
function setUpModule
begin
comment pull in test environment as dict
global TestEnv
call get_test_env TestEnv
end function | def setUpModule():
# pull in test environment as dict
global TestEnv
get_test_env(TestEnv) | Python | nomic_cornstack_python_v1 |
import argparse , math
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.patches as mpatches
comment python3 ./MultiPlot.py -b 1 -e 0
comment python3 ./MultiPlot.py -e 0 -p 1
comment python3 ./MultiPlot.py -o "./Images/Multiplot/ExecutionTime/Prim_gnp.png" -p 1 -e 1
comment python3 ./MultiPlot.py -o... | import argparse, math
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.patches as mpatches
#python3 ./MultiPlot.py -b 1 -e 0
#python3 ./MultiPlot.py -e 0 -p 1
#python3 ./MultiPlot.py -o "./Images/Multiplot/ExecutionTime/Prim_gnp.png" -p 1 -e 1
#python3 ./MultiPlot.py -o "./Images/Multiplot/Execut... | Python | zaydzuhri_stack_edu_python |
import sys , webbrowser
set url = string https://www.google.com/maps/search/
if length argv > 1
begin
comment get address from cmd
set address = join string argv at slice 1 : :
open url + address
end | import sys, webbrowser
url = 'https://www.google.com/maps/search/'
if len(sys.argv) > 1:
# get address from cmd
address = ' '.join(sys.argv[1:])
webbrowser.open(url+address) | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
comment 借助百度的aip智能库,进行图片的文字识别。获取图片中的文字信息
from aip import AipOcr
function signUp
begin
string 你的 APPID AK SK
set APP_ID = string 10745268
set API_KEY = string 5gceIUGsak6t376e2MolshkL
set SECRET_KEY = string yRBjSyN0LpyveVP4WnpUkOhubpnMWIt1
set client = call AipOcr APP_ID API_KEY SECRET_KEY
... | #-*- coding:utf-8 -*-
#借助百度的aip智能库,进行图片的文字识别。获取图片中的文字信息
from aip import AipOcr
def signUp():
""" 你的 APPID AK SK """
APP_ID = '10745268'
API_KEY = '5gceIUGsak6t376e2MolshkL'
SECRET_KEY = 'yRBjSyN0LpyveVP4WnpUkOhubpnMWIt1'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
return client
def get_file_... | Python | zaydzuhri_stack_edu_python |
function set_sympy_forecolor self background_color=string dark
begin
if get environ string SPY_SYMPY_O == string True
begin
try
begin
from sympy import init_printing
if background_color == string dark
begin
call init_printing forecolor=string White ip=shell
end
else
if background_color == string light
begin
call init_p... | def set_sympy_forecolor(self, background_color='dark'):
if os.environ.get('SPY_SYMPY_O') == 'True':
try:
from sympy import init_printing
if background_color == 'dark':
init_printing(forecolor='White', ip=self.shell)
elif background_... | Python | nomic_cornstack_python_v1 |
string Created on Feb 16, 2015 @author: casey
from sklearn import linear_model
from sklearn.preprocessing import StandardScaler
function classify word word_classifiers objects
begin
string given a word, the word_classifiers, and the set of objects, this steps through each word in the utterance and each object and gets ... | '''
Created on Feb 16, 2015
@author: casey
'''
from sklearn import linear_model
from sklearn.preprocessing import StandardScaler
def classify(word, word_classifiers, objects):
'''
given a word, the word_classifiers, and the set of objects, this steps through each word in the utterance and each
object and ... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
set df = call read_excel string helpers/profiles.xlsx
set df_progress = call read_excel string helpers/09.04 ИС УРФУ (1).xlsx
comment df = pd.read_excel('profiles.xlsx')
comment df_progress = pd.read_excel('diagnostics.xlsx')
function get_profile username
begin
set user_frame = loc at lower str == l... | import pandas as pd
df = pd.read_excel('helpers/profiles.xlsx')
df_progress = pd.read_excel('helpers/09.04 ИС УРФУ (1).xlsx')
# df = pd.read_excel('profiles.xlsx')
# df_progress = pd.read_excel('diagnostics.xlsx')
def get_profile(username):
user_frame = df.loc[df['Username'].str.lower() == username.lower()]
... | Python | zaydzuhri_stack_edu_python |
function __add_customer self customer
begin
set customer_model = call to_model customer
save
return id
end function | def __add_customer(self, customer):
customer_model = Customer.to_model(customer)
customer_model.save()
return customer_model.id | Python | nomic_cornstack_python_v1 |
function lexDemo lex_file
begin
set lispReader = call LispReader lex_file
call lexAll
end function | def lexDemo(lex_file):
lispReader = LispReader(lex_file)
lispReader.lexAll() | Python | nomic_cornstack_python_v1 |
function _download url display_progress=false chunk_size=DOWNLOAD_CHUNK_SIZE
begin
set http = call PoolManager
set response = call request string GET url preload_content=false headers=dict string User-Agent string urllib3
if status not in tuple 200
begin
raise call ValueError string Failed to fetch data from { url } , ... | def _download(
url: str,
display_progress: bool = False,
chunk_size: int = DOWNLOAD_CHUNK_SIZE,
) -> Generator[bytes, None, None]:
http = urllib3.PoolManager()
response = http.request(
"GET", url, preload_content=False, headers={"User-Agent": "urllib3"}
)
if response.status not in (... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import requests
import zipfile
import io
function extract_zip_files zip_url directory
begin
set request = get requests zip_url
set zip_content = zip file call BytesIO content
extract all zip_content string data/ { directory } /
end function
function download_csvs
begin
for year in range 2009 2022
be... | import pandas as pd
import requests
import zipfile
import io
def extract_zip_files(zip_url, directory):
request = requests.get(zip_url)
zip_content = zipfile.ZipFile(io.BytesIO(request.content))
zip_content.extractall(f"data/{directory}/")
def download_csvs():
for year in range(2009, 2022):
... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
set n = integer input
set data = default dictionary list
for i in range n
begin
set student_name = input
set grade = decimal input
set data at student_name = data at student_name + list grade
end
set average_grade = dict
for tuple kay value in items data
begin
set average = sum valu... | from collections import defaultdict
n = int(input())
data = defaultdict(list)
for i in range(n):
student_name = input()
grade = float(input())
data[student_name] += [grade]
average_grade = {}
for kay, value in data.items():
average = sum(value) / len(value)
average_grade[kay] = average
if... | Python | zaydzuhri_stack_edu_python |
function test_datetime_pendulum_negative_non_dst self
begin
assert equal dumps list call datetime 2018 12 1 2 3 4 0 tzinfo=call timezone string America/New_York b'["2018-12-01T02:03:04-05:00"]'
end function | def test_datetime_pendulum_negative_non_dst(self):
self.assertEqual(
orjson.dumps(
[
datetime.datetime(
2018,
12,
1,
2,
3,
... | Python | nomic_cornstack_python_v1 |
if opcion == string D
begin
print format string La suma en euros es: {} cantidad * dolar_euro
end
if opcion == string L
begin
print format string La suma en euros es: {} cantidad * libra_euro
end
else
if opcion != string D or string L
begin
print string De momento el conversor solo trabaja con Libras y Dolares, proxima... | if opcion == "D":
print("La suma en euros es: {}".format(cantidad * dolar_euro))
if opcion == "L":
print("La suma en euros es: {}".format(cantidad * libra_euro))
elif opcion != "D" or "L":
print("De momento el conversor solo trabaja con Libras y Dolares, proximamente habrá actualizaciones con nuevas di... | Python | zaydzuhri_stack_edu_python |
function refill_lines lines width
begin
comment Try using GNU `fmt'.
import tempfile , os
set name = call mktemp
write open name string w join string lines string + string
set process = popen string fmt -cuw %d %s % tuple width name
set text = read process
remove os name
if close process is none
begin
return map expand... | def refill_lines(lines, width):
# Try using GNU `fmt'.
import tempfile, os
name = tempfile.mktemp()
open(name, 'w').write(string.join(lines, '\n') + '\n')
process = os.popen('fmt -cuw %d %s' % (width, name))
text = process.read()
os.remove(name)
if process.close() is None:
return... | Python | nomic_cornstack_python_v1 |
string Train the database to create a model for system
import random
import numpy as np
import sqlite3 as sq
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
string Path for saving the trained model
set model_path = string C:\... | """Train the database to create a model for system"""
import random
import numpy as np
import sqlite3 as sq
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
"""Path for saving the trained model"""
model_path = "C:\\Users\... | Python | zaydzuhri_stack_edu_python |
function get_dataset_files current_user
begin
set dataset_name = get args string dataset_id
set dataset_path = join path DATASETS_ROOT dataset_name
if exists path dataset_path
begin
set files_to_send = list dataset_name + string .csv string VMap.csv
if exists path join path dataset_path string Entities.csv
begin
append... | def get_dataset_files(current_user):
dataset_name = request.args.get('dataset_id')
dataset_path = os.path.join(DATASETS_ROOT, dataset_name)
if os.path.exists(dataset_path):
files_to_send = [dataset_name + ".csv", "VMap.csv"]
if os.path.exists(os.path.join(dataset_path, "Entities.csv")):
... | Python | nomic_cornstack_python_v1 |
function power_density ebeam_energy=6 peak_field=1 undulator_n_period=100 k=1.5 sr_current=0.2
begin
set G = 2 * call arctan k * pi / pi
return 10.84 * ebeam_energy ^ 4 * peak_field * undulator_n_period * sr_current * G
end function | def power_density(
ebeam_energy=6, peak_field=1, undulator_n_period=100, k=1.5, sr_current=0.2
):
G = 2 * np.arctan(k * np.pi) / np.pi
return 10.84 * ebeam_energy**4 * peak_field * undulator_n_period * sr_current * G | Python | nomic_cornstack_python_v1 |
function get_tb
begin
set result = string
try
begin
set result = call exc_info at 2
if not result
begin
set result = string Failed to get tb
end
end
except Exception as err
begin
exception err
end
finally
begin
return result
end
end function | def get_tb():
result = ""
try:
result = sys.exc_info()[2]
if not result:
result = "Failed to get tb"
except Exception as err:
logging.exception(err)
finally:
return result | Python | nomic_cornstack_python_v1 |
function is_ipv6_supported
begin
try
begin
set s = call socket AF_INET6 SOCK_STREAM
call bind tuple string ::1 0
call listen 128
set a = call getsockname
set s2 = call socket AF_INET6 SOCK_STREAM
call settimeout 1
call connect a
return true
end
except error
begin
return false
end
end function | def is_ipv6_supported():
try:
s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
s.bind(("::1", 0))
s.listen(128)
a = s.getsockname()
s2 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
s2.settimeout(1)
s2.connect(a)
return True
except sock... | Python | nomic_cornstack_python_v1 |
function read_namespaced_scale_scale self namespace name **kwargs
begin
set all_params = list string namespace string name string pretty
append all_params string callback
set params = locals
for tuple key val in call iteritems params at string kwargs
begin
if key not in all_params
begin
raise call TypeError string Got ... | def read_namespaced_scale_scale(self, namespace, name, **kwargs):
all_params = ['namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
... | Python | nomic_cornstack_python_v1 |
function parse_arguements
begin
set info = string Perform LLE on a given X matrix of data and optional Y labels
set parser = call ArgumentParser description=info
comment program arguments
call add_argument string -X string --X-data type=str required=true help=string Path to file containing X data
call add_argument stri... | def parse_arguements():
info = "Perform LLE on a given X matrix of data and optional Y labels"
parser = argparse.ArgumentParser(description=info)
# program arguments
parser.add_argument('-X', '--X-data',
type=str, required=True,
help='Path to fil... | Python | nomic_cornstack_python_v1 |
function copy_to self destination file_name=none maintain_name=true
begin
function _internal_copy source source_path target target_path maintain_flag
begin
string Internal function to copy content of one HDF5 file to another or copy a group within the same HDF5 file. Args: source (h5py.File): HDF5 File object source_pa... | def copy_to(self, destination, file_name=None, maintain_name=True):
def _internal_copy(source, source_path, target, target_path, maintain_flag):
"""
Internal function to copy content of one HDF5 file to another or copy a group within the same HDF5 file.
Args:
... | Python | nomic_cornstack_python_v1 |
from math import sqrt
class Problem
begin
function __init__ self file_name
begin
set __noTrainExamples = none
set __noFeatures = none
set __noOutputs = none
set __inTrainData = none
set __outTrainData = none
set tuple __noTrainExamples __noFeatures __noOutputs __inTrainData __outTrainData = call readData file_name
call... | from math import sqrt
class Problem:
def __init__(self, file_name):
self.__noTrainExamples = None
self.__noFeatures = None
self.__noOutputs = None
self.__inTrainData = None
self.__outTrainData = None
self.__noTrainExamples, self.__noFeatures, self.__noOutputs, self.... | Python | zaydzuhri_stack_edu_python |
function __init__ self num_layers input_dim hidden_dim output_dim
begin
call __init__
comment default is linear model
set linear_or_not = true
set num_layers = num_layers
set output_dim = output_dim
if num_layers < 1
begin
raise call ValueError string number of layers should be positive!
end
else
if num_layers == 1
beg... | def __init__(self, num_layers, input_dim, hidden_dim, output_dim):
super(MLP, self).__init__()
self.linear_or_not = True # default is linear model
self.num_layers = num_layers
self.output_dim = output_dim
if num_layers < 1:
raise ValueError("number of layers should ... | Python | nomic_cornstack_python_v1 |
function get_squares num
begin
return num * num
end function
comment if '__name__' == '__main__':
set l = list 3 5 7 11
set squares = list comprehension call get_squares item for item in l
print squares | def get_squares(num):
return (num * num)
#if '__name__' == '__main__':
l = [3, 5 , 7, 11]
squares = [get_squares(item) for item in l]
print(squares)
| Python | zaydzuhri_stack_edu_python |
from import npc
set npcList = dict string momo call NPC name=string Momo location=string start4 path=false desc=string A large, plushy, tuxedo cat named Momo stands here. He looks friendly enough to talk to! thanks=string Momo thanks you for the Gogurt and is now your friend. quest_type=string item required=list strin... | from . import npc
npcList = {
"momo" : npc.NPC(
name="Momo",
location="start4",
path = False,
desc = "A large, plushy, tuxedo cat named Momo stands here. He looks friendly enough to talk to!",
thanks = "Momo thanks you for the Gogurt and is now your friend.",
quest_type = "item",
required... | Python | zaydzuhri_stack_edu_python |
from Renderer import Renderer
from AStar import AStar
import pygame
from random import randint
set black = tuple 0 0 0
set white = tuple 255 255 255
set grey = tuple 125 125 125
set green = tuple 0 255 0
set red = tuple 128 0 0
set blue = tuple 0 0 128
set yellow = tuple 255 255 0
set orange = tuple 255 127 0
set purpl... | from Renderer import Renderer
from AStar import AStar
import pygame
from random import randint
black = (0, 0, 0)
white = (255, 255, 255)
grey = (125, 125, 125)
green = (0, 255, 0)
red = (128, 0, 0)
blue = (0, 0, 128)
yellow = (255, 255, 0)
orange = (255, 127, 0)
purple = (128, 0, 128)
class NNRenderer(Renderer, obj... | Python | zaydzuhri_stack_edu_python |
function get_time timestr
begin
set datestr = split timestr at 0
return call to_date string parse time datestr string %d/%b/%Y:%H:%M:%S
end function | def get_time(timestr):
datestr = timestr.split()[0]
return to_date(time.strptime(datestr, "%d/%b/%Y:%H:%M:%S")) | Python | nomic_cornstack_python_v1 |
function locking meth
begin
decorator wraps meth
async function wrapper oself *args **kwargs
begin
async_with lock
begin
return await call meth oself *args keyword kwargs
end
end function
return wrapper
end function | def locking(meth):
@wraps(meth)
async def wrapper(oself, *args, **kwargs):
async with oself.lock:
return await meth(oself, *args, **kwargs)
return wrapper | Python | nomic_cornstack_python_v1 |
import math
function pow_sumToDigit n
begin
while true
begin
set base = 9
set exp = 2
set x = power 9 exp
comment print(x)
set digitSum = x // 10 + x % 10
comment print(digitSum)
if digitSum and power digitSum 2
begin
return x
end
else
if exp < 4
begin
set base = base - 1
set exp = exp + 1
end
else
if exp >= 4
begin
se... | import math
def pow_sumToDigit(n):
while True:
base = 9
exp = 2
x = pow(9, exp)
#print(x)
digitSum = ((x // 10) + (x % 10))
#print(digitSum)
if digitSum and pow(digitSum, 2):
return x
else:
if exp < 4:
base -= 1... | Python | zaydzuhri_stack_edu_python |
import json
import tweepy
function send_tweet text
begin
with open string data.json string r as filename
begin
set auths = load json filename
end
set auth = call OAuthHandler auths at string API_KEY auths at string API_SECRET_KEY
call set_access_token auths at string access_token auths at string access_token_secret
set... | import json
import tweepy
def send_tweet(text):
with open("data.json", 'r') as filename:
auths = json.load(filename)
auth = tweepy.OAuthHandler(auths['API_KEY'], auths['API_SECRET_KEY'])
auth.set_access_token(auths['access_token'], auths['access_token_secret'])
api = tweepy.API(auth)
api... | Python | zaydzuhri_stack_edu_python |
function heading self
begin
set tuple current_x current_y = _orient
set result = round call atan2 current_y current_x * 180.0 / pi 10 % 360.0
set result = result / _degrees_per_au
return _angle_offset + _angle_orient * result % _fullcircle
end function | def heading(self):
current_x, current_y = self._orient
result = round(math.atan2(current_y, current_x)*180.0/math.pi, 10) % 360.0
result /= self._degrees_per_au
return (self._angle_offset + self._angle_orient*result) % self._fullcircle | Python | nomic_cornstack_python_v1 |
import os
set text_file = join path directory name path __file__ replace base name path __file__ string .py string .txt
set input_set = call splitlines
set input_set = set list comprehension integer item for item in input_set
function solution_one
begin
for x in input_set
begin
comment python's 'in' is crazy fast on se... | import os
text_file = os.path.join(
os.path.dirname(__file__),
os.path.basename(__file__).replace('.py','.txt')
)
input_set = open(text_file).read().splitlines()
input_set = set([int(item) for item in input_set])
def solution_one():
for x in input_set:
# python's 'in' is crazy fast on sets, not so much ... | Python | zaydzuhri_stack_edu_python |
function GetNumberOfObjects self
begin
return call itkLabelStatisticsImageFilterIF2IUS2_GetNumberOfObjects self
end function | def GetNumberOfObjects(self) -> "unsigned long long":
return _itkLabelStatisticsImageFilterPython.itkLabelStatisticsImageFilterIF2IUS2_GetNumberOfObjects(self) | Python | nomic_cornstack_python_v1 |
import socket
import sys
set BLOCK_SIZE = 128 // 2 // 8
class PaddingOracle
begin
string Interface to call the padding oracle
set server = tuple string localhost 5000
set template = string pad_oracle,0x{:016x},0x{:016x}
function __init__ self host port
begin
string initialize a padding oracle caller Arguments: host {st... | import socket
import sys
BLOCK_SIZE = 128 // 2 // 8
class PaddingOracle:
"""Interface to call the padding oracle"""
server = ("localhost", 5000)
template = "pad_oracle,0x{:016x},0x{:016x}\n"
def __init__(self, host: str, port: int):
"""initialize a padding oracle caller
Arguments:
... | Python | zaydzuhri_stack_edu_python |
function datetime_from_timestamp t
begin
return call utcfromtimestamp decimal t
end function | def datetime_from_timestamp(t: Union[Decimal, float]) -> datetime.datetime:
return datetime.datetime.utcfromtimestamp(float(t)) | Python | nomic_cornstack_python_v1 |
function scoreEvaluationFunction currentGameState
begin
return call getScore
end function | def scoreEvaluationFunction(currentGameState):
return currentGameState.getScore() | Python | nomic_cornstack_python_v1 |
from PIL import Image
import pyinsane.abstract as pyinsane
from time import sleep
import sys
class scanner
begin
string This class combines pyinsane abstract and image so the scanner automatically produces an iterating image of the scan frame by frame. It overlays the new image ontop of the old.
function __init__ self ... | from PIL import Image
import pyinsane.abstract as pyinsane
from time import sleep
import sys
class scanner():
'''
This class combines pyinsane abstract and image so the scanner automatically
produces an iterating image of the scan frame by frame. It overlays the new
image ontop of the old.
'''
... | Python | zaydzuhri_stack_edu_python |
function _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_network_accesses_vpn_network_access_status input_yang_obj translated_yang_obj=none
begin
set innerobj = call _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_network_accesses_vpn_network_access_status_admin_status admin_... | def _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_network_accesses_vpn_network_access_status(
input_yang_obj, translated_yang_obj=None):
innerobj = _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_network_accesses_vpn_network_access_status_admin_status(
... | Python | nomic_cornstack_python_v1 |
function __getitem__ self key
begin
if __pepth__ != 0
begin
return call call __getattr__ self string __getitem__ key
end
try
begin
if is instance key list and all isinstance int
begin
comment Don't pass root -- we are uprooting
return call plist list comprehension self at k for k in key
end
else
if is instance key slic... | def __getitem__(self, key):
if self.__pepth__ != 0:
return plist.__getattr__(self, '__getitem__')(key)
try:
if (isinstance(key, list)
and plist(key).all(isinstance, int)):
return plist([self[k] for k in key]) # Don't pass root -- we are uprooting
elif isinstance(key, slice):... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.