code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment import re comment text = input() comment print(re.sub(r'(.)\1+', r'\1', text)) comment Itertools is a lot faster than regex apparently from itertools import groupby set text = input set s = join string generator expression ch for tuple ch _ in group by text print s
# import re # # text = input() # print(re.sub(r'(.)\1+', r'\1', text)) # Itertools is a lot faster than regex apparently from itertools import groupby text = input() s = ''.join(ch for ch, _ in groupby(text)) print(s)
Python
zaydzuhri_stack_edu_python
function test_result_str self begin set pdu = call A_ASSOCIATE_RJ decode pdu a_associate_rj set result = 0 with assert raises ValueError begin result_str end set result = 1 assert equal result_str string Rejected (Permanent) set result = 2 assert equal result_str string Rejected (Transient) set result = 3 with assert r...
def test_result_str(self): pdu = A_ASSOCIATE_RJ() pdu.Decode(a_associate_rj) pdu.result = 0 with self.assertRaises(ValueError): pdu.result_str pdu.result = 1 self.assertEqual(pdu.result_str, 'Rejected (Permanent)') pdu.result = 2 self.assertEqual(pdu.re...
Python
nomic_cornstack_python_v1
from collections import deque set tuple H W = map int split input set A = list comprehension input for _ in range H set inf = 10 ^ 6 set d = list comprehension list inf * W for _ in range H set q = deque for i in range H begin for j in range W begin if A at i at j == string # begin append q tuple i j 0 set d at i at j ...
from collections import deque H,W = map(int, input().split()) A = [input() for _ in range(H)] inf = 10**6 d = [[inf]*W for _ in range(H)] q = deque() for i in range(H): for j in range(W): if A[i][j] == "#": q.append((i, j, 0)) d[i][j] = 0 while q: temp = q.popleft()...
Python
zaydzuhri_stack_edu_python
function _reload self key=none **kwargs begin set data = query self key call _loadData data return self end function
def _reload(self, key=None, **kwargs): data = self.query(self.key) self._loadData(data) return self
Python
nomic_cornstack_python_v1
import unittest import sys import os append path absolute path path string .. from models.crawler import Crawler class CrawlerTests extends TestCase begin set TestUrls = list string http://www.google.com string http://www.markvelez.com string https://www.cia.gov/library/publications/the-world-factbook/geos/ag.html stri...
import unittest import sys import os sys.path.append(os.path.abspath('..')) from models.crawler import Crawler class CrawlerTests(unittest.TestCase): TestUrls = [ "http://www.google.com", "http://www.markvelez.com", "https://www.cia.gov/library/publications/the-world-factbook/geos/ag.html", "http://k2_7.asdf1234.net"...
Python
zaydzuhri_stack_edu_python
function __repr__ self begin return call __str__ end function
def __repr__(self): return self.__str__()
Python
nomic_cornstack_python_v1
function basic_info ITSs begin set py = list comprehension PY for i in ITSs comment XXX RESULT: the "A" part contributes more to correlation with PY comment than the "G" part of the pyrimidines for dg100, and much more for dg400. comment for DG400 correlation is significant starting at +4, dips at +5, and then comment ...
def basic_info(ITSs): py = [i.PY for i in ITSs] # XXX RESULT: the "A" part contributes more to correlation with PY # than the "G" part of the pyrimidines for dg100, and much more for dg400. # for DG400 correlation is significant starting at +4, dips at +5, and then # increases gradually to +11. Co...
Python
nomic_cornstack_python_v1
set R = integer input print 6.28 * R
R = int(input()) print(6.28*R)
Python
zaydzuhri_stack_edu_python
function files self state=none s3uri_prefix=none begin info string files generator set keys = list keys downloads sort keys for key in keys begin set download = downloads at key if not state or state and download at string state == state begin print download set s3uri = download at string s3_uri if s3uri_prefix is none...
def files(self, state=None, s3uri_prefix=None): self.log.info("files generator") keys = list(self.downloads.keys()) keys.sort() for key in keys: download = self.downloads[key] if not state or (state and download['state'] == state): print(download) ...
Python
nomic_cornstack_python_v1
function test_boundmethod self begin class Test begin string Test class. function test self begin string Test method. end function end class set test = call Test call annotation test set annotations = call get_annotations test assert true annotations end function
def test_boundmethod(self): class Test: """Test class.""" def test(self): """Test method.""" test = Test() self.annotation(test.test) annotations = Annotation.get_annotations(test.test) self.assertTrue(annotations)
Python
nomic_cornstack_python_v1
function neg A begin return call from_rep call neg end function
def neg(A): return A.from_rep(A.rep.neg())
Python
nomic_cornstack_python_v1
from src import EncryptionEngine set encryptor = call EncryptionEngine comment Update these all to have only function calls. Make the Encryption comment Engine do all the functionality, main should just run it function main begin set user_input = input string Welcome to the TI-89 Encryptor! Would you like to encode a s...
from src import EncryptionEngine encryptor = EncryptionEngine.EncryptionEngine() #Update these all to have only function calls. Make the Encryption #Engine do all the functionality, main should just run it def main(): user_input = input("Welcome to the TI-89 Encryptor! " "Would you like t...
Python
zaydzuhri_stack_edu_python
function current_azimuth self begin set setpoint = call getSetpoint return decimal setpoint - steer_enc_offset / STEER_COUNTS_PER_RADIAN end function
def current_azimuth(self): setpoint = self.steer_motor.getSetpoint() return float(setpoint - self.steer_enc_offset) / self.STEER_COUNTS_PER_RADIAN
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import csv comment save the json output as emp.json comment jsfile = file('/var/www/html/assets/probelog.json', 'w') set jsfile = call file string ../src/assets/probelog.json string w write jsfile string [ with open string ./probez.txt string r as f begin comment skip headings next f set re...
#!/usr/bin/env python import csv # save the json output as emp.json # jsfile = file('/var/www/html/assets/probelog.json', 'w') jsfile = file('../src/assets/probelog.json', 'w') jsfile.write('[\r\n') with open('./probez.txt','r') as f: next(f) # skip headings reader=csv.reader(f,delimiter='\t') uniqProb...
Python
zaydzuhri_stack_edu_python
function acquire_all_gifts self acquire_energy=false begin call go_to_inbox if call wait_until is_ui_element_on_screen ui_element=INBOX_GIFT_TAB begin comment Wait for animations call r_sleep 2 call click_button INBOX_GIFT_TAB call _acquire_gifts acquire_energy=acquire_energy end call go_to_main_menu end function
def acquire_all_gifts(self, acquire_energy=False): self.game.go_to_inbox() if wait_until(self.emulator.is_ui_element_on_screen, ui_element=ui.INBOX_GIFT_TAB): r_sleep(2) # Wait for animations self.emulator.click_button(ui.INBOX_GIFT_TAB) self._acquire_gifts(acquire_e...
Python
nomic_cornstack_python_v1
import sys call setrecursionlimit 30000 function palindromeprimes M N lst begin function pr_num point end=1 begin if end == point begin return true end else if point % end == 0 and end != 1 begin return false end else begin return call pr_num point end + 1 end end function function reverse sub_phrase begin if sub_phras...
import sys sys.setrecursionlimit(30000) def palindromeprimes(M, N, lst): def pr_num(point, end=1): if end == point: return True else: if point % end == 0 and end != 1: return False else: return pr_num(point, end + 1)...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment Author:0verWatch import string string 确保大小写正确转换,用了两个列表 set letter_list = ascii_uppercase set letter_list2 = ascii_lowercase function get_real_key begin string 获取列需要加的秘钥 print string 输入你的秘钥 comment 得确保都是英文 set key = input set tmp = list set flag = 0 for i in key begin if is alpha i...
# -*- coding: utf-8 -*- # Author:0verWatch import string """ 确保大小写正确转换,用了两个列表 """ letter_list = string.ascii_uppercase letter_list2 = string.ascii_lowercase def get_real_key(): """ 获取列需要加的秘钥 """ print("输入你的秘钥") key = input() #得确保都是英文 tmp = [] flag = 0 for i in key: if i...
Python
zaydzuhri_stack_edu_python
function Find_Set x begin if x == Parent at x begin return x end else begin return call Find_Set Parent at x end end function function Union x y begin set Parent at call Find_Set y = call Find_Set x end function for t in range 1 integer input + 1 begin set tuple N M = map int split input set case = list map int split i...
def Find_Set(x): if x == Parent[x]: return x else: return Find_Set(Parent[x]) def Union(x, y): Parent[Find_Set(y)] = Find_Set(x) for t in range(1, int(input()) + 1): N, M = map(int, input().split()) case = list(map(int, input().split())) Parent = [0] * (N + 1) for i in r...
Python
zaydzuhri_stack_edu_python
function mute_volume self mute begin call socket_command string 2F A0 12 01 3 + string _zone end function
def mute_volume(self, mute): self.socket_command("2F A0 12 01 3" + str(self._zone))
Python
nomic_cornstack_python_v1
from models import Machine class Machines begin function __init__ self begin set items = list return end function function loadSources self sources=none begin if sources == none begin raise exception string You must pass the path(s) to the source files to create the machines object. return end for source in sources be...
from models import Machine class Machines: def __init__(self): self.items = [] return def loadSources(self, sources=None): if sources == None: raise Exception( "You must pass the path(s) to the source files to create the machines object.") ...
Python
zaydzuhri_stack_edu_python
function getHost self begin return _host end function
def getHost(self): return self._host
Python
nomic_cornstack_python_v1
function parse_from_yaml ei begin set e = copy ei if kernels := pop e string kernels none is none begin return dict end comment type: ignore[assignment] set type_alias : Dict at tuple str List at str = pop e string type_alias dict comment type: ignore[assignment] set dim_order_alias : Dict at tuple str List at str = p...
def parse_from_yaml(ei: Dict[str, object]) -> Dict[ETKernelKey, BackendMetadata]: e = ei.copy() if (kernels := e.pop("kernels", None)) is None: return {} type_alias: Dict[str, List[str]] = e.pop("type_alias", {}) # type: ignore[assignment] dim_order_alias: Dict[str, List[str]] = e.pop("dim_ord...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python class ParseLastInfo extends object begin string Given a JSON block of text from last.fm, parse it and return it in a data structure. function __init__ self begin string ParseLastInfo is a class of helper functions that given a block of json text, will parse the json and put any relevant inf...
#!/usr/bin/env python class ParseLastInfo(object): """ Given a JSON block of text from last.fm, parse it and return it in a data structure. """ def __init__(self): """ ParseLastInfo is a class of helper functions that given a block of json text, will parse the json and put an...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function rob self nums begin string :type nums: List[int] :rtype: int set tuple prevNo prevYes = tuple 0 0 for n in nums begin set tmpPrevNo = prevNo set prevNo = max prevNo prevYes set prevYes = n + tmpPrevNo end return max prevYes prevNo end function end class
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ prevNo, prevYes = 0, 0 for n in nums: tmpPrevNo = prevNo prevNo = max(prevNo,prevYes) prevYes = n + tmpPrevNo return max(prevY...
Python
zaydzuhri_stack_edu_python
function cast obj begin return call itkConnectedComponentImageFilterIUS2IUL2_cast obj end function
def cast(obj: 'itkLightObject') -> "itkConnectedComponentImageFilterIUS2IUL2 *": return _itkConnectedComponentImageFilterPython.itkConnectedComponentImageFilterIUS2IUL2_cast(obj)
Python
nomic_cornstack_python_v1
function pick_one _lst begin if length _lst == 2 begin return if expression integer random 2 then _lst at 0 else _lst at 1 end else if length _lst == 3 begin return _lst at integer random 3 end end function
def pick_one(_lst): if len(_lst) == 2: return _lst[0] if int(random(2)) else _lst[1] elif len(_lst) == 3: return _lst[int(random(3))]
Python
nomic_cornstack_python_v1
function get_varmeta self begin if ref_ds is not none begin set ref_meta = tuple id call _names_from_attrs string all end else begin set ref_meta = none end if other_dss is not none begin set dss_meta = list comprehension tuple id call _names_from_attrs string all for ds in other_dss end else begin set dss_meta = none ...
def get_varmeta(self): if self.ref_ds is not None: ref_meta = (self.ref_ds.id, self.ref_ds._names_from_attrs('all')) else: ref_meta = None if self.other_dss is not None: dss_meta = [(ds.id, ds._names_from_attrs('all')) for ds in self.other_dss] else: ...
Python
nomic_cornstack_python_v1
import numpy as np class Irm extends object begin function __init__ self a=1 b=0 c=0 model=string b begin set b = b set a = a set c = c set model = model set threshold = 1e-05 set iters = 50 set lr = 0.02 end function function z self theta begin return exp a * b - theta end function function p self theta begin return 1...
import numpy as np class Irm(object): def __init__(self, a=1, b=0, c=0, model='b'): self.b = b self.a = a self.c = c self.model = model self.threshold = 1e-5 self.iters = 50 self.lr = 0.02 def z(self, theta): return np.exp(self.a * (self.b - the...
Python
zaydzuhri_stack_edu_python
comment Abstract Classes in Python comment An abstract class can be considered as a blueprint for other classes, allows you to create a set of methods that must be created within any child classes built from your abstract class. A class which contains one or abstract methods is called an abstract class. An abstract met...
################################################################ #Abstract Classes in Python #An abstract class can be considered as a blueprint for other classes, allows you to create a set of methods that must be created within any child classes built from your abstract class. A class which contains one or abstract m...
Python
zaydzuhri_stack_edu_python
function serve_asset self asset connection_request begin if image_location is none begin raise call RuntimeError string Cannot serve asset { asset } because it has no image end if starts with image_location string http: begin raise call RuntimeError string Refusing to serve remote asset { asset } end set job_id = call ...
def serve_asset( self, asset: Asset, connection_request: ConnectionRequest ) -> ConnectionInfo: if asset.image_location is None: raise RuntimeError( f'Cannot serve asset {asset} because it has no image') if asset.image_location.startswith('http:')...
Python
nomic_cornstack_python_v1
import unittest from app import app class TestSearch extends TestCase begin comment Ensure that Flask was set up correctly function test_index self begin set tester = call test_client self set response = get tester string /search.html set status_code = status_code assert equal status_code 200 end function comment Ensur...
import unittest from app import app class TestSearch(unittest.TestCase): # Ensure that Flask was set up correctly def test_index(self): tester = app.test_client(self) response = tester.get("/search.html") status_code = response.status_code self.assertEqual(status_code, 200) ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding=utf-8 import cv2 import platform if call system == string Linux begin from camera2 import Camera end else begin from camera import Camera end comment 参数0表示第一个摄像头 set camera = call VideoCapture 0 comment 判断视频是否打开 if call isOpened begin print string Open end else begin print st...
#!/usr/bin/env python # coding=utf-8 import cv2 import platform if platform.system()=="Linux": from camera2 import Camera else: from camera import Camera camera = cv2.VideoCapture(0) # 参数0表示第一个摄像头 # 判断视频是否打开 if (camera.isOpened()): print('Open') else: print('摄像头未打开') ca = Camera(camera) ca.run() # ...
Python
zaydzuhri_stack_edu_python
from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style import random function create_dataset entries variance step=2 correlation=false begin set val = 1 set ys = list for i in range entries begin set y = val + call randrange - variance variance append ys y if correl...
from statistics import mean import numpy as np import matplotlib.pyplot as plt from matplotlib import style import random def create_dataset(entries, variance, step=2, correlation=False): val = 1 ys = [] for i in range(entries): y = val + random.randrange(-variance, variance) ys.append(y) ...
Python
zaydzuhri_stack_edu_python
function failover self resource failback begin debug string VolumeReplication::failover %(vol)s dict string vol resource at string name set recovery_mgr = call get_recovery_mgr set remote_recovery_mgr = call get_remote_recovery_mgr return call _failover_resource resource recovery_mgr remote_recovery_mgr string vol fail...
def failover(self, resource, failback): LOG.debug("VolumeReplication::failover %(vol)s", {'vol': resource['name']}) recovery_mgr = self.get_recovery_mgr() remote_recovery_mgr = self.get_remote_recovery_mgr() return self._failover_resource(resource, recovery_mgr, ...
Python
nomic_cornstack_python_v1
function _03_merge_plant_status records **params begin set plant_names = list set list comprehension record at string Power Plant Name for record in records for plant_name in plant_names begin set plant_records = list comprehension record for record in records if record at string Power Plant Name == plant_name set plan...
def _03_merge_plant_status(records, **params): plant_names = list(set([record["Power Plant Name"] for record in records])) for plant_name in plant_names: plant_records = [record for record in records if record["Power Plant Name"] == plant_name] plant_statuses = list(set([record["Plant Status"] f...
Python
nomic_cornstack_python_v1
import requests from urllib.parse import urlparse import json import os import time from secrets import * import webbrowser comment ----Functions---- comment Authorize to Spotify API function auth begin set payload = dict string redirect_uri string http://localhost ; string client_id SPOTIFY_CLIENT_ID ; string client_s...
import requests from urllib.parse import urlparse import json import os import time from secrets import * import webbrowser #----Functions---- # Authorize to Spotify API def auth(): payload = {'redirect_uri':'http://localhost', 'client_id': SPOTIFY_CLIENT_ID, 'client_secret': SPOTIFY_CLIENT_SECRET} scopes_n...
Python
zaydzuhri_stack_edu_python
function __len__ self begin return length _entries end function
def __len__(self): return len(self._entries)
Python
nomic_cornstack_python_v1
function swap self i k begin set tmp = path at slice 0 : i : comment new_route'u tersiyle extend ediyor extend tmp reversed path at slice i : k + 1 : extend tmp path at slice k + 1 : : return tmp end function
def swap(self,i, k): tmp = self.path[0:i] tmp.extend(reversed(self.path[i:k + 1])) #new_route'u tersiyle extend ediyor tmp.extend(self.path[k+1:]) return tmp
Python
nomic_cornstack_python_v1
from saport.simplex.analyser import Analyser from saport.simplex.model import Model comment remember to print the dual model (just print()) and the analysis results (analyser.interpret_results(solution, analysis_results)) comment in case of doubt refer to examples 06 and 07 set primal = model string Zad1 set ss = call ...
from saport.simplex.analyser import Analyser from saport.simplex.model import Model # remember to print the dual model (just print()) and the analysis results (analyser.interpret_results(solution, analysis_results)) # in case of doubt refer to examples 06 and 07 primal = Model("Zad1") ss = primal.create_variable("SS...
Python
zaydzuhri_stack_edu_python
import random function findMaxProfit priceArray begin set priceDic = dict for time in range 0 length priceArray begin set priceDic at priceArray at time = time end set sortedPriceArray = sorted keys priceDic set minPointer = 0 set maxPointer = length sortedPriceArray - 1 set inIters = 0 set ouIters = 0 end function
import random def findMaxProfit( priceArray ): priceDic = {} for time in range( 0,len(priceArray) ): priceDic[ priceArray[ time ] ] = time sortedPriceArray = sorted(priceDic.keys()) minPointer = 0; maxPointer = ( len( sortedPriceArray ) - 1 ) inIters = 0 ouIters = 0
Python
zaydzuhri_stack_edu_python
function get_user_project_last_signature user_id project_id begin set user = call get_user_instance try begin load user string user_id end except DoesNotExist as err begin return dict string errors dict string user_id string err end set last_signature = call get_latest_signature string project_id if last_signature is n...
def get_user_project_last_signature(user_id, project_id): user = get_user_instance() try: user.load(str(user_id)) except DoesNotExist as err: return {'errors': {'user_id': str(err)}} last_signature = user.get_latest_signature(str(project_id)) if last_signature is not None: la...
Python
nomic_cornstack_python_v1
comment -*- coding:UTF-8 -*- from threading import Thread import time
# -*- coding:UTF-8 -*- from threading import Thread import time
Python
zaydzuhri_stack_edu_python
function login_required func begin function wrapper *args **kwargs begin set self = list args at 0 if __logged begin set response = call func *args keyword kwargs end else begin return tuple error_value at string NOT_CONNECTED dict string status string not connected end comment post if needed return response end functi...
def login_required(func): def wrapper(*args, **kwargs): self = list(args)[0] if self.__logged: response = func(*args, **kwargs) else: return (self.__class__.error_value["NOT_CONNECTED"], {"status": "not connected"}) # post if needed return response return wrapper
Python
nomic_cornstack_python_v1
class Vehicle begin function __init__ self company model year color begin set company = company set model = model set year = year set color = color end function function __repr__ self begin return format string {} {} {} {} company model year color end function end class
class Vehicle: def __init__(self, company, model, year, color): self.company = company self.model = model self.year = year self.color = color def __repr__(self): return "{} {} {} {}".format(self.company, self.model, self.year, self.color)
Python
zaydzuhri_stack_edu_python
string List Assessment Edit the functions until all of the doctests pass when you run this file. function print_indices items begin string Print each item in the list, followed by its index. Do this without using a "counting variable" --- that is, don't do something like this:: count = 0 for item in list: print(count) ...
"""List Assessment Edit the functions until all of the doctests pass when you run this file. """ def print_indices(items): """Print each item in the list, followed by its index. Do this without using a "counting variable" --- that is, don't do something like this:: count = 0 for item in list: ...
Python
zaydzuhri_stack_edu_python
set a = integer input string masukkan angka 1 nanda: set b = integer input string masukkan angka 2 anda: set jumlah = decimal a + decimal b print format string jumlah dari {} + {} adalah {} a b jumlah
a=int(input('masukkan angka 1 nanda:')) b=int(input('masukkan angka 2 anda:')) jumlah=float(a)+float(b) print('jumlah dari {} + {} adalah {}'.format(a,b,jumlah))
Python
zaydzuhri_stack_edu_python
import numpy as np comment import scipy from scipy import optimize from threading import Thread comment from scipy.optimize import fmin_tnc comment np.test() comment scipy.test() comment optimize.fmin_tnc() function loss x0 X n begin set summ = 0 set i = 0 for shift in X begin set n1 = n at i set i = i + 1 set vec = do...
import numpy as np ## import scipy from scipy import optimize from threading import Thread ## from scipy.optimize import fmin_tnc ## np.test() ## scipy.test() ## optimize.fmin_tnc() def loss(x0, X, n): summ = 0 i = 0 for shift in X: n1 = n[i] i += 1 vec = shift.dot(x0) vec...
Python
zaydzuhri_stack_edu_python
comment Using Collections module for counting and frequencies from collections import * import collections comment Making list to be used in comparison witn input user set vowels = list string a string e string i string o string u comment ----> for using later in frequency set result = list while true begin set user_i...
#Using Collections module for counting and frequencies from collections import * import collections # Making list to be used in comparison witn input user vowels = ["a" , "e" , "i" , "o" , "u"] result = [] # ----> for using later in frequency while True : user_input = input ("Enter the word : ") ...
Python
zaydzuhri_stack_edu_python
async function actualise_shop self begin set temp = call get_toy set new = list for i in temp begin if i not in ToyInShop begin append new temp at i end end set ToyInShop = temp info format string {} new toy and {} in total in shop length new length ToyInShop set for_database = list set actual_time = time for i in va...
async def actualise_shop(self): temp = self.get_toy() new = [] for i in temp: if i not in self.ToyInShop: new.append(temp[i]) self.ToyInShop = temp self.Logger.info("{} new toy and {} in total in shop".format(len(new), len(self.ToyInShop))) for...
Python
nomic_cornstack_python_v1
if word1 > word2 begin print 1 end else if word2 > word1 begin print - 1 end else if word1 == word2 begin print 0 end
if word1 > word2: print(1) elif word2 > word1: print(-1) elif word1 == word2: print(0)
Python
zaydzuhri_stack_edu_python
function reshape self x begin set x_shape = list size x at slice : - 1 : + list num_heads query_size set x = view x *x_shape return permute x 0 2 1 3 end function
def reshape(self, x): x_shape = list(x.size()[:-1]) + [self.num_heads, self.query_size] x = x.view(*x_shape) return x.permute(0, 2, 1, 3)
Python
nomic_cornstack_python_v1
import turtle import time call getscreen set t = call Turtle comment counter = int(input("HOW MANY CURVES DO YOU WANT IN YOUR PATTTERN? \n")) set counter = 5 call rt 90 while counter > 0 begin call circle 20 - 180 call circle - 20 - 180 set counter = counter - 1 end sleep 5 print string ~ WINDOW WILL CLOSE AUTOMATICLY ...
import turtle import time turtle.getscreen() t = turtle.Turtle() # counter = int(input("HOW MANY CURVES DO YOU WANT IN YOUR PATTTERN? \n")) counter = 5 t.rt(90) while counter > 0: t.circle(20, -180) t.circle(-20, -180) counter -= 1 time.sleep(5) print("~ WINDOW WILL CLOSE AUTOMATICLY ~") print("...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf-8 -*- comment _AUTHOR_ : zhujingxiu comment _DATE_ : 2018/1/22 function hash_md5 content begin string md5文本加密 :param content: :return: import hashlib set encrypt = md5 update encrypt bytes content encoding=string utf-8 return hex digest encrypt end function function c...
#!/usr/bin/env python # -*- coding:utf-8 -*- # _AUTHOR_ : zhujingxiu # _DATE_ : 2018/1/22 def hash_md5(content): """ md5文本加密 :param content: :return: """ import hashlib encrypt = hashlib.md5() encrypt.update(bytes(content, encoding='utf-8')) return encrypt.hexdigest() def c...
Python
zaydzuhri_stack_edu_python
import argparse import matplotlib import matplotlib.pyplot as plt import numpy as np import pickle from scipy import sparse from scipy.sparse import csr_matrix function load path begin return load pickle open path string rb end function function save path data begin with open path string wb as f begin dump data f HIGHE...
import argparse import matplotlib import matplotlib.pyplot as plt import numpy as np import pickle from scipy import sparse from scipy.sparse import csr_matrix def load(path): return pickle.load(open(path, "rb")) def save(path, data): with open(path, 'wb') as f: pickle.dump(data, f, pickle.HIGHEST_...
Python
zaydzuhri_stack_edu_python
import csv import datetime import json import os import random import string import time from pathlib import Path import allure comment import objectpath from allure_commons.types import AttachmentType function get_location_path my_folder begin set loc = get current directory return join path loc my_folder end function...
import csv import datetime import json import os import random import string import time from pathlib import Path import allure # import objectpath from allure_commons.types import AttachmentType def get_location_path(my_folder): loc = os.getcwd() return os.path.join(loc, my_folder) def get_location_based_...
Python
zaydzuhri_stack_edu_python
function linear_search arr val n begin for i in range n begin if arr at i == val begin return true end end return false end function
def linear_search(arr,val,n): for i in range(n): if(arr[i]==val): return(True) return(False)
Python
zaydzuhri_stack_edu_python
from tinydb import TinyDB , Query comment DBエンティティの作成 set db = call TinyDB string ongeki.json set data_tbl = call table string data_tbl set py_tbl = call table string py_tbl set que = query comment 初期化 set index_cnt = 0 set cnt_res = search last_insert_flg == string 1 if last_insert_flg == string 1 begin set index_cnt ...
from tinydb import TinyDB, Query # DBエンティティの作成 db = TinyDB('ongeki.json') data_tbl = db.table('data_tbl') py_tbl = db.table('py_tbl') que = Query() # 初期化 index_cnt = 0 cnt_res = data_tbl.search(que.last_insert_flg == '1') if cnt_res.last_insert_flg == '1': index_cnt = cnt_res.index cnt = py_tbl.s...
Python
zaydzuhri_stack_edu_python
print binary 1024 print round 5.23222 2 set s = string hello how are you Mary, are you feeling okay? print is lower s set s = string twywywtwywbwhsjhwuwshshwuwwwjdjdid print count s string w set set1 = set literal 2 3 1 5 6 8 set set2 = set literal 3 1 7 5 6 8 print difference set1 set2 print intersection set1 set2 pri...
print(bin(1024)) print(round(5.23222,2)) s = 'hello how are you Mary, are you feeling okay?' print(s.islower()) s = 'twywywtwywbwhsjhwuwshshwuwwwjdjdid' print(s.count('w')) set1 = {2,3,1,5,6,8} set2 = {3,1,7,5,6,8} print(set1.difference(set2)) print(set1.intersection(set2)) print({x:x**3 for x in range(5)}) l...
Python
zaydzuhri_stack_edu_python
class Solution begin function killProcess self pid ppid kill begin string bfs approach. pop(0) ppid is the parent node and pid is the child node. time O(n) | space O(n) if not pid or not ppid begin return end set graph = default dictionary list for tuple u v in zip ppid pid begin append graph at u v end comment bfs sta...
class Solution: def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]: ''' bfs approach. pop(0) ppid is the parent node and pid is the child node. time O(n) | space O(n) ''' if not pid or not ppid: return ...
Python
zaydzuhri_stack_edu_python
function test_delete_rule_statistics_collision self begin set extra_rule = call Series dict string A string high ; string B call Bounds lower=0.1 upper=1 ; string C call Bounds lower=1 upper=2 ; string Class string apple name=4 set rules = list extra_rule call Series dict string A string low ; string B call Bounds lowe...
def test_delete_rule_statistics_collision(self): extra_rule = pd.Series({"A": "high", "B": Bounds(lower=0.1, upper=1), "C": Bounds(lower=1, upper=2), "Class": "apple"}, name=4) rules = [ extra_rule, pd.Series({"A": "low", "B": Bounds(lower=1, upper...
Python
nomic_cornstack_python_v1
function send_welcome_email user_email begin if not SIB_WELCOME_EMAIL_ENABLED begin return end set user = get objects email=user_email set data = dict string PRENOM first_name ; string NOM last_name if is_contributor and is_beneficiary begin set template_id = SIB_WELCOME_MIXTE_EMAIL_TEMPLATE_ID end else if is_contribut...
def send_welcome_email(user_email): if not settings.SIB_WELCOME_EMAIL_ENABLED: return user = User.objects.get(email=user_email) data = { "PRENOM": user.first_name, "NOM": user.last_name, } if user.is_contributor and user.is_beneficiary: template_id = settings.SIB_WE...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np from selenium import webdriver import urllib.request import time import os from selenium.webdriver.chrome.options import Options comment Gets the URLs of the last three posts of the given instagram account function get_insta_urls centerinstaurl begin set posts = list string /html/body/div[...
import cv2 import numpy as np from selenium import webdriver import urllib.request import time import os from selenium.webdriver.chrome.options import Options # Gets the URLs of the last three posts of the given instagram account def get_insta_urls(centerinstaurl): posts = ['/html/body/div[1]/section/main/div/div...
Python
zaydzuhri_stack_edu_python
from xgboost.sklearn import XGBRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import KFold , StratifiedKFold , GroupKFold import numpy as np import pandas as pd import os import gc comment 别人的自定义损失函数,在parameter里面:object里面赋值 function custom_loss y_true y_pred begin set penalty = 2...
from xgboost.sklearn import XGBRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import KFold, StratifiedKFold,GroupKFold import numpy as np import pandas as pd import os import gc # 别人的自定义损失函数,在parameter里面:object里面赋值 def custom_loss(y_true,y_pred): penalty=2.0 grad=-y_true/...
Python
zaydzuhri_stack_edu_python
function removeDuplicateLetters self s begin set stack = list set freq = list comprehension 0 for _ in range 26 for ch in s begin set idx = ordinal ch - ordinal string a set freq at idx = freq at idx + 1 end for ch in s begin set freq at ordinal ch - ordinal string a = freq at ordinal ch - ordinal string a - 1 if ch i...
def removeDuplicateLetters(self, s): stack = [] freq = [0 for _ in range(26)] for ch in s: idx = ord(ch) - ord('a') freq[idx] += 1 for ch in s: freq[ord(ch) - ord('a')] -= 1 if ch in stack: continue while stack ...
Python
nomic_cornstack_python_v1
function to_dict self drop_null=true camel=false begin comment return _to_dict(self, drop_null, camel) function to_dict obj drop_null camel begin string Recursively constructs the dict. if is instance obj tuple Body BodyChild begin set obj = __dict__ end if is instance obj dict begin set data = dict for tuple attr val...
def to_dict(self, drop_null=True, camel=False): #return _to_dict(self, drop_null, camel) def to_dict(obj, drop_null, camel): """Recursively constructs the dict.""" if isinstance(obj, (Body, BodyChild)): obj = obj.__dict__ if isinstance(obj, dict): ...
Python
nomic_cornstack_python_v1
comment wap print the factorial of a number comment 5 --> 1*2*3*4*5 set N = input string enter N : set i = 1 set fact = 1 while i <= N begin comment fact *= i set fact = fact * i comment i = i+1 set i = i + 1 end
# wap print the factorial of a number # 5 --> 1*2*3*4*5 N = input("enter N : ") i = 1 fact = 1 while(i <= N ): fact = fact * i # fact *= i i += 1 # i = i+1
Python
zaydzuhri_stack_edu_python
function make_epsilon_greedy_policy Q epsilon nA begin function policy_fn observation begin if random < 1 - epsilon begin return argument maximum Q at observation end else begin return random choice array range nA end end function return policy_fn end function
def make_epsilon_greedy_policy(Q, epsilon, nA): def policy_fn(observation): if random.random() < (1 - epsilon): return np.argmax(Q[observation]) else: return random.choice(np.arange(nA)) return policy_fn
Python
nomic_cornstack_python_v1
function zero_pad_features features depth begin set n = integer dims at - 1 set extra_feature_count = depth - n assert n >= 0 if n > 0 begin set padding = call tile features at tuple slice : : slice : : slice : 1 : * 0 list 1 1 extra_feature_count set features = concat list features padding 2 end return feature...
def zero_pad_features(features, depth): n = int(features.get_shape().dims[-1]) extra_feature_count = depth - n assert n >= 0 if n > 0: padding = tf.tile(features[:, :, :1] * 0, [1, 1, extra_feature_count]) features = tf.concat([features, padding], 2) return...
Python
nomic_cornstack_python_v1
function create_network network_input n_vocab begin set model = sequential comment network_input.shape[1]=100 , network_input.shape[2]=1 add model lstm 512 input_shape=tuple shape at 1 shape at 2 recurrent_dropout=0.3 return_sequences=true comment (batch_siez,network_input.shape[1],512)=(*,100,512) add model lstm 512 r...
def create_network(network_input, n_vocab): model = Sequential() #network_input.shape[1]=100 , network_input.shape[2]=1 model.add(LSTM( 512, input_shape=(network_input.shape[1], network_input.shape[2]), recurrent_dropout=0.3, return_sequences=True )) #(batch_siez,netw...
Python
nomic_cornstack_python_v1
import numpy as np from nltk.corpus import stopwords class NaiveBayes begin comment Takes the data and parses it into spam and not spam probability function fit self X y begin call parse_emails X y end function comment Initial guess * words probs function predict self X begin set y_pred = list comprehension 0 for i in ...
import numpy as np from nltk.corpus import stopwords class NaiveBayes(): # Takes the data and parses it into spam and not spam probability def fit(self, X, y): self.parse_emails(X, y) # Initial guess * words probs def predict(self, X): y_pred = [0 for i in range(len(X))] initi...
Python
zaydzuhri_stack_edu_python
function _get_observation self begin set di = call _get_observation comment camera observations if use_camera_obs begin set camera_obs = call render camera_name=camera_name width=camera_width height=camera_height depth=camera_depth if camera_depth begin set tuple di at string image di at string depth = camera_obs end e...
def _get_observation(self): di = super()._get_observation() # camera observations if self.use_camera_obs: camera_obs = self.sim.render( camera_name=self.camera_name, width=self.camera_width, height=self.camera_height, de...
Python
nomic_cornstack_python_v1
function note_name note begin set notes = list string C string Cs string D string Ds string E string F string Fs string G string Gs string A string As string B set name = notes at note % length notes set octave = note // 12 - 1 return string { name } { octave } end function
def note_name(note: int) -> str: notes = ["C", "Cs", "D", "Ds", "E", "F", "Fs", "G", "Gs", "A", "As", "B"] name = notes[note % len(notes)] octave = note // 12 - 1 return f"{name}{octave}"
Python
nomic_cornstack_python_v1
string @author: Davi Nascimento de Paula <davi.paula@gmail.com> import csv import json import os import re import timeit from itertools import chain from typing import Tuple import numpy as np import pandas as pd import torch from utils.constants import WORD2VEC_200D_PATH , WORD2VEC_50D_PATH function remove_zeros eleme...
""" @author: Davi Nascimento de Paula <davi.paula@gmail.com> """ import csv import json import os import re import timeit from itertools import chain from typing import Tuple import numpy as np import pandas as pd import torch from ..utils.constants import WORD2VEC_200D_PATH, WORD2VEC_50D_PATH def remove_zeros(elem...
Python
zaydzuhri_stack_edu_python
function group_balance_items self begin set counts = counter balance_items call clear_balance for item in counts begin set quantity_str = if expression counts at item > 1 then string (x { counts at item } @ { call format_money amount } each) else string call add_balance amount * counts at item category=category descri...
def group_balance_items(self) -> None: counts = Counter(self.balance_items) self.clear_balance() for item in counts: quantity_str = f" (x{counts[item]} @ {format_money(item.amount)} each)" if counts[item] > 1 else "" self.add_balance(item.amount * counts[item], category=item.category, descriptio...
Python
nomic_cornstack_python_v1
from file import File class FileHSV begin string HSV value handler that loads values from/writes values to a file. Implements a lot of methods from File in file.py. Uses: A simple HSV loader for use in matches, as an alternative to trackbars. Attributes ---------- file : File - the file to which HSV values are written/...
from file import File class FileHSV: """ HSV value handler that loads values from/writes values to a file. Implements a lot of methods from File in file.py. Uses: A simple HSV loader for use in matches, as an alternative to trackbars. Attributes ---------- file : File - the file to ...
Python
zaydzuhri_stack_edu_python
function __init__ self begin call __init__ set image = call convert_alpha set image = call scale image tuple integer displayWidth * 0.4 integer displayHeight * 0.75 set rect = call get_rect set center = tuple displayWidth * 0.75 displayHeight / 2 return end function
def __init__(self): super().__init__() self.image = pygame.image.load("Images/BattleBox.png").convert_alpha() self.image = pygame.transform.scale(self.image,(int(displayWidth*0.4),int(displayHeight*0.75))) self.rect = self.image.get_rect() self.rect.center = (displayWidth*0....
Python
nomic_cornstack_python_v1
string This program was created in order to help learning japanese words that the user could write with the kanji that they currently know by creating an Anki deck. In order to do that, the user needs to populate the 'known.txt' file with the kanji that they know, without quotes and with one kanji per line. Procedure: ...
"""This program was created in order to help learning japanese words that the user could write with the kanji that they currently know by creating an Anki deck. In order to do that, the user needs to populate the 'known.txt' file with the kanji that they know, without quotes and with one kanji per line. Procedure: ...
Python
zaydzuhri_stack_edu_python
import re from os import environ , path from twython import Twython , TwythonError from textblob import TextBlob class TwitterBot extends object begin string Twitter Bot to retrive tweets related to particult hashtag for sentiment analysis function __init__ self begin set TWITTER_API_KEY = environ at string Twitter_API...
import re from os import environ, path from twython import Twython, TwythonError from textblob import TextBlob class TwitterBot(object): ''' Twitter Bot to retrive tweets related to particult hashtag for sentiment analysis ''' def __init__(self): TWITTER_API_KEY = environ['Twitter_API_Key'] ...
Python
zaydzuhri_stack_edu_python
comment In this file are made the figures of the predictive app. from data import models_prediction , list_training_data import pandas as pd import numpy as np import plotly.express as px from sklearn.cluster import KMeans comment Font use for the figures set family_font = string KarlaMedium comment cluster ###########...
#In this file are made the figures of the predictive app. from data import models_prediction, list_training_data import pandas as pd import numpy as np import plotly.express as px from sklearn.cluster import KMeans #Font use for the figures family_font = 'KarlaMedium' ################################################...
Python
zaydzuhri_stack_edu_python
comment 面试题55(一):二叉树的深度 comment 题目:输入一棵二叉树的根结点,求该树的深度。从根结点到叶结点依次经过的 comment 结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 comment 方法1 先序遍历,记录从根结点到每一个无左右子树结点的长度的值,并只比较 comment 保存最大值 遍历结束后的最大值即为树的深度 comment 方法2 只递归 1+max(左边,右边) function depth_of_tree tree begin if not tree begin return 0 end return 1 + max call depth_of_tree left cal...
# 面试题55(一):二叉树的深度 # 题目:输入一棵二叉树的根结点,求该树的深度。从根结点到叶结点依次经过的 # 结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 # 方法1 先序遍历,记录从根结点到每一个无左右子树结点的长度的值,并只比较 # 保存最大值 遍历结束后的最大值即为树的深度 # 方法2 只递归 1+max(左边,右边) def depth_of_tree(tree): if not tree: return 0 return 1 + max(depth_of_tree(tree.left), depth_of_tree(tree.right))
Python
zaydzuhri_stack_edu_python
function load_preposition_file begin return set split read open string data/preposition.txt string r string , end function
def load_preposition_file(): return set(open("data/preposition.txt", 'r').read().split(', '))
Python
nomic_cornstack_python_v1
function dms self begin return call gon2dms gon_angle end function
def dms(self): return gon2dms(self.gon_angle)
Python
nomic_cornstack_python_v1
function from_dict cls d begin return call Vector generator expression d at _keys at i for i in range min length d length _keys end function
def from_dict(cls, d: Dict[str, Number]) -> 'Vector': return Vector(d[cls._keys[i]] for i in range(min(len(d), len(cls._keys))))
Python
nomic_cornstack_python_v1
function test_change_pwd_short self begin set res = post string /api/v2/reset-password json=dict string password string beda headers=headers set data = call get_json assert equal data at string status 422 assert equal data at string error string Password must be at least 6 characters long assert equal status_code 422 e...
def test_change_pwd_short(self): res = self.client.post('/api/v2/reset-password', json={ "password": "beda" }, headers=self.headers) data = res.get_json() self.assertEqual(data['status'], 422) self.assertEqual( data['error'], 'Password must b...
Python
nomic_cornstack_python_v1
function cross_outdegree self node_list1 node_list2 link_attribute=none begin if link_attribute is none begin return sum call cross_adjacency node_list1 node_list2 axis=1 end else begin return sum call cross_link_attribute link_attribute node_list1 node_list2 axis=1 end end function
def cross_outdegree(self, node_list1, node_list2, link_attribute=None): if link_attribute is None: return np.sum(self.cross_adjacency(node_list1, node_list2), axis=1) else: return np.sum(self.cross_link_attribute(link_attribute, node_list1, ...
Python
nomic_cornstack_python_v1
import cartpole import numpy as np import pandas as pd set defaultVals = list 0.95 0.001 0.995 comment .95 set GAMMA = array range 0.05 0.95 0.05 set LEARNING_RATE = array range 0.0001 0.0023 0.0002 set EXPLORATION_DECAY = array range 0.85 0.999 0.01 set Variables = list GAMMA LEARNING_RATE EXPLORATION_DECAY set GammaV...
import cartpole import numpy as np import pandas as pd defaultVals = [.95, .001, .995] GAMMA = np.arange(.05,.95,.05) #.95 LEARNING_RATE = np.arange(.0001, .0023, .0002) EXPLORATION_DECAY = np.arange(.85, .999, .01) Variables = [GAMMA, LEARNING_RATE, EXPLORATION_DECAY] GammaVals = {} LearningRateVals = {} Explorati...
Python
zaydzuhri_stack_edu_python
function recurse tlx tly brx bry flag begin comment single square (width == 1) if tlx + 1 == brx begin comment draw black square if flag begin call add_patch call Rectangle tuple tly brx - 1 1 1 color=string black end comment no need to recurse anymore return end comment here's the recursive part: comment we go in the ...
def recurse(tlx, tly, brx, bry, flag): if(tlx + 1 == brx): # single square (width == 1) if flag: # draw black square ax.add_patch(Rectangle((tly, brx - 1), 1, 1, color='black')) return # no need to recurse anymore # here's the recursive part: # we go in...
Python
nomic_cornstack_python_v1
function hello begin print string Hello World end function
def hello(): print("Hello World")
Python
nomic_cornstack_python_v1
import requests import json import random set BASE_URL = string https://api.datamuse.com/words function random_word_from_word_list word_list begin set index = random integer 0 length word_list - 1 return word_list at index at string word end function comment default values, to be overwritten set first_word = string red...
import requests import json import random BASE_URL = "https://api.datamuse.com/words" def random_word_from_word_list(word_list): index = random.randint(0, len(word_list) - 1) return word_list[index]["word"] # default values, to be overwritten first_word = "red" second_word = "blue" third_word = "sweet" fou...
Python
zaydzuhri_stack_edu_python
function execute_time self begin return _execute_time end function
def execute_time(self): return self._execute_time
Python
nomic_cornstack_python_v1
string Created on Jan. 29, 2021 @author: Jean Armstrong from app import app from flask import render_template , request , flash , Response , session , redirect , url_for from app import redis_client from app.computations import op_data_from_db , error_codes_from_db , isInteger , format_min_sec import json import time d...
''' Created on Jan. 29, 2021 @author: Jean Armstrong ''' from app import app from flask import render_template, request, flash, Response, session, redirect, url_for from app import redis_client from app.computations import op_data_from_db, error_codes_from_db, isInteger, format_min_sec import json import ...
Python
zaydzuhri_stack_edu_python
function test_work_order_with_wrong_requester_signature setup_config begin comment input file name set request = string work_order_tests/input/work_order_with_empty_requester_signature.json set tamper = dict string params dict string after_sign dict string requesterSignature string set tuple work_order_response generi...
def test_work_order_with_wrong_requester_signature(setup_config): # input file name request = 'work_order_tests/input' \ '/work_order_with_empty_requester_signature.json' tamper = {"params": {"after_sign": {"requesterSignature": ""}}} work_order_response, generic_params = (work_order_requ...
Python
nomic_cornstack_python_v1
import nltk from nltk.sentiment import SentimentIntensityAnalyzer comment Initialize the SentimentIntensityAnalyzer set sia = call SentimentIntensityAnalyzer comment Define the given text set text = string The movie is extraordinarily awe-inspiring and mind-blowing, leaving the audience in awe of its impeccable storyte...
import nltk from nltk.sentiment import SentimentIntensityAnalyzer # Initialize the SentimentIntensityAnalyzer sia = SentimentIntensityAnalyzer() # Define the given text text = "The movie is extraordinarily awe-inspiring and mind-blowing, leaving the audience in awe of its impeccable storytelling and breathtaking visu...
Python
jtatman_500k
import wx , airport , table , os , test , pandas as pd , airport_fx as fx class Example extends Frame begin function __init__ self parent title begin call __init__ parent title=title size=tuple 350 400 call InitUI call Centre end function function InitUI self begin set panel = call Panel self set font = call GetFont SY...
import wx, airport, table, os, test, pandas as pd, airport_fx as fx class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title=title, size = (350,400)) self.InitUI() self.Centre() def InitUI(self): panel = wx.Panel(self) ...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import numpy as np from matrix_factorization import MatrixFactorization class NMF extends MatrixFactorization begin function __init__ self event_matrix news_matrix comment_matrix k=5 lam=0.1 eps=0.01 iter_eps=0.01 max_iter_num=0.1 verbose=true begin call __init__ self event_matrix news_matr...
#-*- coding:utf-8 -*- import numpy as np from matrix_factorization import MatrixFactorization class NMF(MatrixFactorization): def __init__(self, event_matrix, news_matrix, comment_matrix, k=5, lam=0.1, eps=0.01, iter_eps=0.01, max_iter_num=0.1, verbose=True): MatrixFactorization.__init__(self, event_matri...
Python
zaydzuhri_stack_edu_python
from PIL import Image from PIL import ImageFilter import os import numpy as np from numpy import array comment Gets directory this file is run from. Define the Directory it gets the images from, relatively to this files directory set cwd = get current directory comment Makes sure these file paths are correct, they alte...
from PIL import Image from PIL import ImageFilter import os import numpy as np from numpy import array #Gets directory this file is run from. Define the Directory it gets the images from, relatively to this files directory cwd = os.getcwd() #Makes sure these file paths are correct, they alter on different operating s...
Python
zaydzuhri_stack_edu_python
function GetStaticInitializerSection load_commands begin set matches = find all string sectname (.*)\n\s+segname (.*)\n(?:.|\n)*?flags (0x[0-9a-f]*)\n load_commands MULTILINE set sections = list for tuple sectname segname flags in matches begin set flags = integer flags 16 if flags in tuple S_MOD_INIT_FUNC_POINTERS S_...
def GetStaticInitializerSection(load_commands): matches = re.findall( r'sectname (.*)\n\s+segname (.*)\n(?:.|\n)*?flags (0x[0-9a-f]*)\n', load_commands, re.MULTILINE) sections = [] for sectname, segname, flags in matches: flags = int(flags, 16) if flags in (S_MOD_INIT_FUNC_POINTERS, S_INIT_FUN...
Python
nomic_cornstack_python_v1
function show_BIc begin set func = airypat_easy set df = call load_db dbname set n = length df set nrow = 3 set ncol = integer n / nrow + 1 set fig = figure figsize=tuple 20 ncol * 4 comment Loop over record for k in index begin subplot ncol nrow k + 1 set rec = iloc at k comment Load and plot data set tuple data md = ...
def show_BIc(): func = airypat_easy df = mylib.load_db(dbname) n = len(df) nrow = 3 ncol = int(n/nrow) + 1 fig = plt.figure(figsize=(20,ncol*4)) # Loop over record for k in df.index: plt.subplot(ncol, nrow, k+1) rec = df.iloc[k] # Load an...
Python
nomic_cornstack_python_v1
function csv_file answers name begin set file_name = PATH_TO_EXPORT_FILES + format string /{0}.csv name try begin with open file_name string w as file begin set user_id = random choice list answers set field_titles = keys answers at user_id set writer = dict writer file fieldnames=field_titles call writeheader for user...
def csv_file(answers, name): file_name = PATH_TO_EXPORT_FILES + '/{0}.csv'.format(name) try: with open(file_name, 'w') as file: user_id = random.choice(list(answers)) field_titles = answers[user_id].keys() writer = csv.DictWriter(file, fieldnames=field_titles) ...
Python
nomic_cornstack_python_v1
from aiogram import types from aiogram.dispatcher.filters.builtin import CommandStart from loader import dp decorator call message_handler call CommandStart async function bot_start message begin await call answer string Привет, { full_name } ! await call answer string Бот преднзначен для переноса стилей между картинка...
from aiogram import types from aiogram.dispatcher.filters.builtin import CommandStart from loader import dp @dp.message_handler(CommandStart()) async def bot_start(message: types.Message): await message.answer(f"Привет, {message.from_user.full_name}!") await message.answer("Бот преднзначен для переноса стиле...
Python
zaydzuhri_stack_edu_python