code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment For Clearing Lines import os comment For Colors | Reference: https://github.com/timofurrer/colorful import colorful comment These set of variables are to specify a place for each part of speech comment in the world list and to prompt the user with a phrase to enter. set noun = string > Enter a Noun set noun2 = ...
import os #For Clearing Lines import colorful #For Colors | Reference: https://github.com/timofurrer/colorful #These set of variables are to specify a place for each part of speech #in the world list and to prompt the user with a phrase to enter. noun = '> Enter a Noun\n' noun2 = '> Enter a Noun\n' propnoun = '>Enter ...
Python
zaydzuhri_stack_edu_python
string Convenient function import re from app.controllers.mt_config_handler import MTConfigHandler from app.controllers.mt_io import print_stderr function is_jira_key key begin string Check passed string is jira or not, if valid return true else return false set regex_jira = string ^[A-Z]{1,9}-[0-9]{1,9}$ set match = m...
""" Convenient function """ import re from app.controllers.mt_config_handler import MTConfigHandler from app.controllers.mt_io import print_stderr def is_jira_key(key): """ Check passed string is jira or not, if valid return true else return false """ regex_jira = r'^[A-Z]{1,9}-[0-9]{1,9}$' match ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import signal comment writing signal handler
#!/usr/bin/python import signal #writing signal handler
Python
zaydzuhri_stack_edu_python
function source_name self source_name begin set _source_name = source_name end function
def source_name(self, source_name): self._source_name = source_name
Python
nomic_cornstack_python_v1
function _compute_lensing_angles_flatsky ra_lens dec_lens ra_source_list dec_source_list begin if not - 360.0 <= ra_lens <= 360.0 begin raise call ValueError string ra = { ra_lens } of lens if out of domain end if not - 90.0 <= dec_lens <= 90.0 begin raise call ValueError string dec = { dec_lens } of lens if out of dom...
def _compute_lensing_angles_flatsky(ra_lens, dec_lens, ra_source_list, dec_source_list): if not -360. <= ra_lens <= 360.: raise ValueError(f"ra = {ra_lens} of lens if out of domain") if not -90. <= dec_lens <= 90.: raise ValueError(f"dec = {dec_lens} of lens if out of domain") if not all(-36...
Python
nomic_cornstack_python_v1
import sys import math import random set filename = argv at 1 comment percent of keeping points 0-100 set keepingPercent = integer argv at 2 set outfile = argv at 3 set f = open outfile string w comment print x, y, r with open filename as pc begin for line in pc begin if random * 100 < keepingPercent begin write f line...
import sys import math import random filename = sys.argv[1] #percent of keeping points 0-100 keepingPercent = int(sys.argv[2]) outfile = sys.argv[3] f = open(outfile,"w") #print x, y, r with open(filename) as pc: for line in pc: if random.random() * 100 < keepingPercent : f.write(line) f.clo...
Python
zaydzuhri_stack_edu_python
function test_delete_non_existing_institution self begin post string /api/v1/institutions data=dumps new_institution content_type=string application/json headers=call get_registrar_token set response = delete string /api/v1/institutions/100 content_type=string application/json headers=call get_registrar_token set resul...
def test_delete_non_existing_institution(self): self.client.post( '/api/v1/institutions', data=json.dumps(new_institution), content_type='application/json', headers=self.get_registrar_token()) response = self.client.delete( '/api/v1/institutions/100', cont...
Python
nomic_cornstack_python_v1
comment Programming for the Puzzled -- Srini Devadas comment Keep Those Queens Apart comment Given a 8 x 8 chess board, figure out how to place 8 Queens such that comment no Queen attacks another queen. comment This code uses a single-dimensional list to represent Queen positions import random comment This procedure ch...
#Programming for the Puzzled -- Srini Devadas #Keep Those Queens Apart #Given a 8 x 8 chess board, figure out how to place 8 Queens such that #no Queen attacks another queen. #This code uses a single-dimensional list to represent Queen positions import random #This procedure checks that the most recently placed queen...
Python
zaydzuhri_stack_edu_python
comment AUTHOR: James Beasley ## comment DATE: February 18, 2017 ## comment UDACITY SDC: Project 4 (Advanced Lane Finding) ## comment IMPORTS ## import numpy as np import matplotlib.image as mpimg import glob import cv2 comment generate calibration camera matrix and distortion coefficients based on supplied chessboard ...
#################################################### ## AUTHOR: James Beasley ## ## DATE: February 18, 2017 ## ## UDACITY SDC: Project 4 (Advanced Lane Finding) ## #################################################### ############# ## IMPORTS ## ############# imp...
Python
zaydzuhri_stack_edu_python
function enable_svc_notifications self service begin string Enable notifications for a service Format of the line that triggers function call:: ENABLE_SVC_NOTIFICATIONS;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service :return: None if not notifications_ena...
def enable_svc_notifications(self, service): """Enable notifications for a service Format of the line that triggers function call:: ENABLE_SVC_NOTIFICATIONS;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service ...
Python
jtatman_500k
function state self begin return _state end function
def state(self): return self._state
Python
nomic_cornstack_python_v1
function segment_parallel_streets self street_pair begin comment Take the two points from street_pair[0], and use it as a base vector. comment Project all the points along the base vector and sort them. set base_node0 = get nodes nids at 0 set base_node1 = get nodes nids at - 1 set base_vector = call vector_to base_nod...
def segment_parallel_streets(self, street_pair): # Take the two points from street_pair[0], and use it as a base vector. # Project all the points along the base vector and sort them. base_node0 = self.nodes.get(street_pair[0].nids[0]) base_node1 = self.nodes.get(street_pair[0].nids[-1]) ...
Python
nomic_cornstack_python_v1
comment 주민등록번호 뒷자리의 맨 첫 번째 숫자는 성별을 나타낸다. comment 주민등록번호에서 성별을 나타내는 숫자를 출력해 보자. set ssn = string 881120-1068234 set sex_indicator = ssn at 7 print sex_indicator
#주민등록번호 뒷자리의 맨 첫 번째 숫자는 성별을 나타낸다. #주민등록번호에서 성별을 나타내는 숫자를 출력해 보자. ssn = "881120-1068234" sex_indicator = ssn[7] print(sex_indicator)
Python
zaydzuhri_stack_edu_python
function stg begin call _setup_env string stg set aws_storage_bucket = string media.knilab.com/%(project_name)s % env end function
def stg(): _setup_env('stg') env.aws_storage_bucket = 'media.knilab.com/%(project_name)s' % env
Python
nomic_cornstack_python_v1
from sklearn.feature_extraction.text import TfidfVectorizer class TfIdf begin string TF-IDF model function __init__ self begin set tfidf = none pass end function function read_data self data=string data/corpus/all_english1.txt begin with open data string r as fil begin read line fil for row in read lines fil begin yiel...
from sklearn.feature_extraction.text import TfidfVectorizer class TfIdf: """ TF-IDF model """ def __init__(self): self.tfidf = None pass def read_data(self, data='data/corpus/all_english1.txt'): with open(data, "r") as fil: fil.readline() for row in...
Python
zaydzuhri_stack_edu_python
import pickle import numpy import pygame import time from src.drone_controller import DroneController from src.model.coords import Coords from src.model.map import Map set CELL_SIZE = 20 set BLUE = tuple 0 0 255 set WHITE = tuple 255 255 255 set PURPLE = tuple 255 0 255 set GREEN = tuple 0 255 0 class MapView extends o...
import pickle import numpy import pygame import time from src.drone_controller import DroneController from src.model.coords import Coords from src.model.map import Map CELL_SIZE = 20 BLUE = (0, 0, 255) WHITE = (255, 255, 255) PURPLE = (255, 0, 255) GREEN = (0, 255, 0) class MapView(object): def __init__(self, ma...
Python
zaydzuhri_stack_edu_python
function optimize nn_last_layer correct_label learning_rate num_classes begin set logits = reshape tf nn_last_layer tuple - 1 num_classes set cross_entropy_loss = call reduce_mean call softmax_cross_entropy_with_logits logits=logits labels=correct_label set optimizer = call AdamOptimizer learning_rate=learning_rate set...
def optimize(nn_last_layer, correct_label, learning_rate, num_classes): logits = tf.reshape(nn_last_layer, (-1, num_classes)) cross_entropy_loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=correct_label)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) ...
Python
nomic_cornstack_python_v1
function fix_coordinate_decimal d begin string Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal. Round them down to 5 decimals :param dict d: Metadata :return dict d: Metadata try begin for tuple idx n in enumerate d at string geo at string geometry at string coordinat...
def fix_coordinate_decimal(d): """ Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal. Round them down to 5 decimals :param dict d: Metadata :return dict d: Metadata """ try: for idx, n in enumerate(d["geo"]["geometry"]["coordinates"]...
Python
jtatman_500k
function testBits self begin set a = call build string SNIMPY-MIB string snimpyBits list 1 2 call assert_ is instance a Bits assert equal a list 2 1 assert equal a tuple 1 2 assert equal a list string second string third assert equal a list string second 2 call assert_ a != list string second 3 call assert_ a != list s...
def testBits(self): a = basictypes.build("SNIMPY-MIB", "snimpyBits", [1, 2]) self.assert_(isinstance(a, basictypes.Bits)) self.assertEqual(a, [2,1]) self.assertEqual(a, (1,2)) self.assertEqual(a, ["second", "third"]) self.assertEqual(a, ["second", 2]) self.assert_...
Python
nomic_cornstack_python_v1
function max_uncrossed_lines nums1 nums2 begin set tuple m n = tuple length nums1 length nums2 set dp = list comprehension list 0 * n + 1 for _ in range m + 1 for i in range 1 m + 1 begin for j in range 1 n + 1 begin if nums1 at i - 1 == nums2 at j - 1 begin set dp at i at j = dp at i - 1 at j - 1 + 1 end else begin se...
def max_uncrossed_lines(nums1, nums2): m, n = len(nums1), len(nums2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if nums1[i - 1] == nums2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j]...
Python
jtatman_500k
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: comment ei code ta jyputer notebook e real answer dei na ...eta IDLE te kora lage but amr pc te IDLE te korle vul dekai comment tai ans paibar jnoo kono rokom Jupyter notebook e korci import matplotlib.animation as animation from matplotlib import style ...
#!/usr/bin/env python # coding: utf-8 # In[1]: # ei code ta jyputer notebook e real answer dei na ...eta IDLE te kora lage but amr pc te IDLE te korle vul dekai # tai ans paibar jnoo kono rokom Jupyter notebook e korci import matplotlib.animation as animation from matplotlib import style import matplotlib.pyplot as...
Python
zaydzuhri_stack_edu_python
import numpy as np import tensorflow as tf from keras.models import Model from keras import backend as K from keras.callbacks import Callback from keras import metrics , optimizers from keras.layers.normalization import BatchNormalization from keras.layers import Input , Dense , Lambda , Activation class LadderCallback...
import numpy as np import tensorflow as tf from keras.models import Model from keras import backend as K from keras.callbacks import Callback from keras import metrics, optimizers from keras.layers.normalization import BatchNormalization from keras.layers import Input, Dense, Lambda, Activation class LadderCallback(C...
Python
zaydzuhri_stack_edu_python
function cohd_pair_frequency node_descr1 node_descr2 begin comment First, get all the concept IDs, select an exact match if it's in there set concept_ids_list1 = call find_concept_ids node_descr1 set concept_id1 = none for res in concept_ids_list1 begin if lower res at string concept_name == lower node_descr1 begin set...
def cohd_pair_frequency(node_descr1, node_descr2): # First, get all the concept IDs, select an exact match if it's in there concept_ids_list1 = QueryCOHD.find_concept_ids(node_descr1) concept_id1 = None for res in concept_ids_list1: if res['concept_name'].lower() == node_descr1.lower(): concept_id1 = res['conc...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Mon May 25 20:52:49 2020 @author: Yu Zhu There are two approaches to calculate Greeks: analytical function and finite difference comment =================================================================================================================== import numpy as np ...
# -*- coding: utf-8 -*- """ Created on Mon May 25 20:52:49 2020 @author: Yu Zhu There are two approaches to calculate Greeks: analytical function and finite difference """ #=================================================================================================================== import numpy as np ...
Python
zaydzuhri_stack_edu_python
import math set vuurkracht = integer input set zwaartekracht = integer input set afstand = integer input set hoek = 0.5 * call asin zwaartekracht * afstand / vuurkracht ^ 2 print format string {0:.2f} hoek
import math vuurkracht = int(input()) zwaartekracht = int(input()) afstand = int(input()) hoek = (0.5)*math.asin((zwaartekracht*afstand)/(vuurkracht**2)) print("{0:.2f}".format(hoek))
Python
zaydzuhri_stack_edu_python
function substring entry pos begin set s = title split split entry string at 0 at slice pos : : string ( at 0 return s end function
def substring(entry, pos): s = entry.split(' ')[0][pos:].split(' (')[0].title() return s
Python
nomic_cornstack_python_v1
function get_normal_tex_size texture begin set tuple tw th = size set ratio = tw / decimal th set th = tw / ratio return tuple tw th end function
def get_normal_tex_size(texture): tw, th = texture.size ratio = tw / float(th) th = tw / ratio return tw, th
Python
nomic_cornstack_python_v1
function is_valid_commits args begin if commits is not none begin return true end return false end function
def is_valid_commits(args): if args.commits is not None: return True return False
Python
nomic_cornstack_python_v1
function __encode_dialogue_turn_scaled self curr_turn_nb begin info string Calling `GORuleBasedStateTracker` __encode_dialogue_turn_scaled method set scaled_turn_encoding = zeros tuple 1 1 + curr_turn_nb / 10.0 debug format string Current turn number: '{0}' call pformat curr_turn_nb debug format string Current scaled t...
def __encode_dialogue_turn_scaled(self, curr_turn_nb): logging.info('Calling `GORuleBasedStateTracker` __encode_dialogue_turn_scaled method') scaled_turn_encoding = np.zeros((1, 1)) + curr_turn_nb / 10. logging.debug("Current turn number: '{0}'".format(self.pp.pformat(curr_turn_nb))) l...
Python
nomic_cornstack_python_v1
comment 计算G/H值,G(从起点到方块的移动量),H(从方块到中点的估算移动量): import copy comment 开放列表(也就是有待探查的地点) set open_list = dict comment 关闭列表 (已经探查过的地点和不可行走的地点) set close_list = dict set end = none set cellValue_list_1 = list comment //123 set risk_grid = list class Node extends object begin function __init__ self father x y begin comment ...
# 计算G/H值,G(从起点到方块的移动量),H(从方块到中点的估算移动量): import copy # 开放列表(也就是有待探查的地点) open_list = {} # 关闭列表 (已经探查过的地点和不可行走的地点) close_list = {} end = None cellValue_list_1 = [] risk_grid = []#//123 class Node(object): def __init__(self, father, x, y): self.map_border = (35, 35) # 地图边界(二维数组的大小,用于判断一个节点的相邻节点是否超出范围) ...
Python
zaydzuhri_stack_edu_python
function plexxi_api_upload_switch_software_image self imagefile name **kwargs begin set kwargs at string uri = format string /switches/software/images/{} name set headers = copy _headers set headers at string Content-Type = string application/octet-stream return call put_file headers=headers file=imagefile stream=true ...
def plexxi_api_upload_switch_software_image(self, imagefile, name, **kwargs): kwargs['uri'] = '/switches/software/images/{}'.format(name) headers = self._headers.copy() headers['Content-Type'] = 'application/octet-stream' return self.put_file(headers=headers, file=imagefile, stream=True,...
Python
nomic_cornstack_python_v1
comment !/use/bin/env/python3 comment -*- encoding: utf-8 -*- string 题目:暂停一秒输出。 import time set myD = dict 1 string a ; 2 string b for tuple key value in items dict myD begin print key value comment 暂停 1 秒 sleep 1 end
#!/use/bin/env/python3 # -*- encoding: utf-8 -*- """ 题目:暂停一秒输出。 """ import time myD = {1: 'a', 2: 'b'} for key, value in dict.items(myD): print (key, value) time.sleep(1) # 暂停 1 秒
Python
zaydzuhri_stack_edu_python
comment [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print list range 1 16 comment [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] print list range 15 0 - 1 comment [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] import random set arr = list 1 2 3 4 5 6 7 8 9 10 print random sample arr 3 comment [1, 9, 5] print random sa...
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(range(1, 16))) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] print(list(range(15, 0, -1))) # [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] import random arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(random.sample(arr, 3)) # [1, 9, 5] print(random.sample(...
Python
zaydzuhri_stack_edu_python
comment -*- coding:UTF-8 -*- from game import Game , IllegalMoveError class InputError extends Exception begin pass end class class UI begin function __init__ self testmode begin set game = call Game set testmode = testmode end function function print_board self begin set board = board set x = string abcdefgh for i in ...
# -*- coding:UTF-8 -*- from game import Game, IllegalMoveError class InputError(Exception): pass class UI(): def __init__(self, testmode): self.game = Game() self.testmode = testmode def print_board(self): board = self.game.board x = 'abcdefgh' for i in range(7,-...
Python
zaydzuhri_stack_edu_python
from datetime import datetime class BucketCluster extends object begin string classdocs function __init__ self name id_cluster begin string Constructor set bucket_name = name set id_cluster = id_cluster set cdate = now set udate = now end function function getDict self begin set d = dictionary set d at string id = id s...
from datetime import datetime class BucketCluster(object): ''' classdocs ''' def __init__(self, name, id_cluster): ''' Constructor ''' self.bucket_name = name self.id_cluster = id_cluster self.cdate = datetime.now() self.udate = datetime.now() ...
Python
zaydzuhri_stack_edu_python
function global_update self begin set url = URL set soup = call get_info url set page_list = call collect_pages soup set arr = list for pl in page_list begin call scrap pl arr end set df = call DataFrame arr to csv df CSV close driver call quit return df end function
def global_update(self): url = URL soup = self.driver.get_info(url) page_list = self.collect_pages(soup) arr = [] for pl in page_list: self.scrap(pl, arr) df = pd.DataFrame(arr) df.to_csv(CSV) self.driver.close() self.driver.quit() ...
Python
nomic_cornstack_python_v1
import numpy as np set x = list 510 - 220 - 200 - 300 - 575 1000 for i in x begin print sum x at i / 1 + - 2.17 ^ 0 - x at 0 end
import numpy as np x = [510, -220, -200, -300, -575, 1000] for i in x: print(np.sum((x[i]/((1+(-2.17))**0)))-x[0])
Python
zaydzuhri_stack_edu_python
for x in range 9 begin for y in range 4 begin print character ch end=string set ch = + 1 if ch == 123 begin break end end for else begin print set ch = ch - 1 end end
for x in range(9): for y in range(4): print(chr(ch),end='') ch=+1 if ch==123: break else: print() ch-=1
Python
zaydzuhri_stack_edu_python
comment fields.py class BaseField extends object begin function __init__ self valtype required=false **kwargs begin set __value = none set __type = valtype set __required = required set __options = dictionary kwargs end function comment 값 설정 function setValue self value validate=true begin set __value = none if validat...
# fields.py class BaseField(object): def __init__( self, valtype, required=False, **kwargs): self.__value = None self.__type = valtype self.__required = required self.__options = dict(kwargs) # 값 설정 def setValue(self, value, validate=True): self.__value = None ...
Python
zaydzuhri_stack_edu_python
function transform self X y=none begin call _check_inputs X set tokens = call _tokenize X set embeddings = call empty tuple length X n_features_out for tuple i_doc token_indices in enumerate tokens begin if not length token_indices begin set embeddings at tuple i_doc slice : : = nan end set doc_vectors = vectors at ...
def transform(self, X, y=None): self._check_inputs(X) tokens = self._tokenize(X) embeddings = np.empty((len(X), self.n_features_out)) for i_doc, token_indices in enumerate(tokens): if not len(token_indices): embeddings[i_doc, :] = np.nan doc_vector...
Python
nomic_cornstack_python_v1
function get_data begin with open string inputs\day5.txt as file begin for line in file begin set rows = line at slice : 7 : set columns = line at slice 7 : 10 : set rows = replace replace rows string F string 0 string B string 1 set columns = replace replace columns string L string 0 string R string 1 yield tuple i...
def get_data(): with open("inputs\\day5.txt") as file: for line in file: rows = line[:7] columns = line[7:10] rows = rows.replace('F', '0').replace('B', '1') columns = columns.replace('L', '0').replace('R', '1') yield int(f'0b{rows}', 2), in...
Python
zaydzuhri_stack_edu_python
function get self request test_id begin return filter test__id=test_id end function
def get(self, request, test_id): return Category.objects.filter(test__id=test_id)
Python
nomic_cornstack_python_v1
function get_clone_system_id self begin set sys_id = call get_system_id return sys_id end function
def get_clone_system_id(self): sys_id = self.user_systems_mgr.get_system_id() return sys_id
Python
nomic_cornstack_python_v1
function print_log msg print_date=DEFAULT_PRINT_DATE print_hostname=DEFAULT_PRINT_HOSTNAME begin if print_date begin call printout string [%s] % replace now microsecond=0 WHITE end if print_hostname begin call printout string (%s) % call getfqdn BLUE end print msg flush stdout end function
def print_log(msg, print_date=DEFAULT_PRINT_DATE, print_hostname=DEFAULT_PRINT_HOSTNAME): if print_date: printout("[%s] " % datetime.now().replace(microsecond=0), WHITE) if print_hostname: printout("(%s) " % socket.getfqdn(), BLUE) print(msg) sys.stdout.flush()
Python
nomic_cornstack_python_v1
class Vector3D begin function __init__ self x y z begin set x = x set y = y set z = z end function function magnitude self begin return x ^ 2 + y ^ 2 + z ^ 2 ^ 1 / 2 end function end class
class Vector3D: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def magnitude(self): return (self.x**2 + self.y**2 + self.z**2)**(1/2)
Python
jtatman_500k
import zhirpy as zp import cv2 import numpy as np from skimage import io from zhirpy import removeShadows function removeSmallObjects img begin comment find all your connected components (white blobs in your image) set tuple nb_components output stats centroids = call connectedComponentsWithStats img connectivity=8 com...
import zhirpy as zp import cv2 import numpy as np from skimage import io from zhirpy import removeShadows def removeSmallObjects(img): #find all your connected components (white blobs in your image) nb_components, output, stats, centroids = cv2.connectedComponentsWithStats(img, connectivity=8) #connectedCo...
Python
zaydzuhri_stack_edu_python
function FindHandlerByExtension *args **kwargs begin return call RichTextBuffer_FindHandlerByExtension *args keyword kwargs end function
def FindHandlerByExtension(*args, **kwargs): return _richtext.RichTextBuffer_FindHandlerByExtension(*args, **kwargs)
Python
nomic_cornstack_python_v1
from Measure import Counters import threading import sys import time class PartySync begin function __init__ self parties begin set parties = parties set secret_sharing_sync = event set online_start_sync = event set online_phase_2_sync = event set barrier = barrier parties stage_finished set stage_done = event end func...
from Measure import Counters import threading import sys import time class PartySync: def __init__(self, parties: int): self.parties = parties self.secret_sharing_sync = threading.Event() self.online_start_sync = threading.Event() self.online_phase_2_sync = threading.Event...
Python
zaydzuhri_stack_edu_python
function l2 prediction gt normalize=true begin comment assert all finite set assert_gt_op = assert call reduce_all call is_finite gt list gt set assert_pred_op = assert call reduce_all call is_finite prediction list prediction with call control_dependencies list assert_gt_op assert_pred_op begin set diff = prediction -...
def l2(prediction, gt, normalize=True): # assert all finite assert_gt_op = tf.Assert(tf.reduce_all(tf.is_finite(gt)), [gt]) assert_pred_op = tf.Assert(tf.reduce_all(tf.is_finite(prediction)), [prediction]) with tf.control_dependencies([assert_gt_op, assert_pred_op]): diff = prediction - gt ...
Python
nomic_cornstack_python_v1
comment динамически перегружает обработчики from tkinter import * from imp import reload comment получить первонач обработчики from Lutts.Gui.Tools import radactions class Hello extends Frame begin function __init__ self master=none begin call __init__ self master call pack call make_widgets end function function make_...
#динамически перегружает обработчики from tkinter import * from imp import reload from Lutts.Gui.Tools import radactions #получить первонач обработчики class Hello(Frame): def __init__(self, master = None): Frame.__init__(self, master) self.pack() self.make_widgets() def mak...
Python
zaydzuhri_stack_edu_python
comment Homework Assignment #2: Functions comment Function 1 function Artist begin print string Artist : Benni Obot return end function call Artist comment Function 2 function Genre begin print string GEnre : Blues return end function call Genre
# Homework Assignment #2: Functions # Function 1 def Artist(): print('Artist : Benni Obot') return Artist() # Function 2 def Genre(): print('GEnre : Blues') return Genre()
Python
zaydzuhri_stack_edu_python
from pytest import mark import os from utils.scraping.browser import open_browser from selenium.webdriver.chrome.webdriver import WebDriver decorator browser function test_chromedriver_in_right_directory begin string Test if the chromedriver file is in the right directory assert is file path string src/utils/scraping/c...
from pytest import mark import os from utils.scraping.browser import open_browser from selenium.webdriver.chrome.webdriver import WebDriver @mark.browser def test_chromedriver_in_right_directory(): ''' Test if the chromedriver file is in the right directory ''' assert os.path.isfile(f'src/utils/scrapi...
Python
zaydzuhri_stack_edu_python
import re import datetime from collections import defaultdict set linepattern = compile string \[(?P<date>.+)\] (?P<message>.*) function parse line begin set match = call groupdict set datestr = match at string date set message = match at string message set date = string parse time datestr string %Y-%m-%d %H:%M return ...
import re import datetime from collections import defaultdict linepattern = re.compile(r"\[(?P<date>.+)\] (?P<message>.*)") def parse(line): match = linepattern.match(line.strip()).groupdict() datestr = match["date"] message = match["message"] date = datetime.datetime.strptime(datestr, "%Y-%m-%d %H:%M"...
Python
zaydzuhri_stack_edu_python
import numpy as np from math import log set tuple E1 E2 = tuple 159 58891 set tuple V1 V2 = tuple 62 15233 set u = E1 * V1 set v = E2 * V2 set p = v / u comment q = log(200, p) set q = 0.5 print string q: q set x1 = 1 / u ^ q set x2 = 1 / v ^ q print string u ^ q: x1 print string v ^ q: x2 set x = array list list x1 x2...
import numpy as np from math import log E1, E2 = 159, 58891 V1, V2 = 62, 15233 u = (E1 * V1) v = (E2 * V2) p = v / u # q = log(200, p) q = 0.5 print('q:', q) x1 = 1 / (u ** q) x2 = 1 / (v ** q) print('u ^ q:', x1) print('v ^ q:', x2) x = np.array([[x1, x2]]) x = np.row_stack((x, [1, 1])) print(x) n = [10000, 500]...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- string 1. 题目类型: DP 2. 题目要求: 给定一个正整数s, 判断一个数组arr中,是否有一组数字加起来等于s 都是正整数 comment 递归 set arr = list 3 34 4 12 5 2 function rec_subset arr i s begin if i == 0 begin return arr at 0 == s end string if i == 0: return arr[0] == s 错误 因为后面还有i-1 if arr at i > s begin return ca...
# !/usr/bin/python # -*- coding: utf-8 -*- ''' 1. 题目类型: DP 2. 题目要求: 给定一个正整数s, 判断一个数组arr中,是否有一组数字加起来等于s 都是正整数 ''' # 递归 arr = [3, 34, 4, 12, 5, 2] def rec_subset(arr, i, s): if i == 0: return arr[0] == s ''' if i == 0: return arr[0] == s 错误 因为后面还有i-1 ''' if a...
Python
zaydzuhri_stack_edu_python
from cstechnion.kombi.Basics import n_letter_words class L begin function __init__ self S f begin comment Alphabet for language L set S = S comment Boolean function. f(w) == True iff w in language L set f = f end function function __contains__ self item begin return f dist item end function function __getitem__ self i ...
from cstechnion.kombi.Basics import n_letter_words class L: def __init__(self, S, f): self.S = S # Alphabet for language L self.f = f # Boolean function. f(w) == True iff w in language L def __contains__(self, item): return self.f(item) def __getitem__(self, i): ...
Python
zaydzuhri_stack_edu_python
function to_binary self begin set c = call containerize call exclude_fields self set payload = call build c return call pack end function
def to_binary(self): c = containerize(exclude_fields(self)) self.payload = MsgReset._parser.build(c) return self.pack()
Python
nomic_cornstack_python_v1
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import wait from selenium.webdriver.support.ui import Select from selenium.webdriver.support import expected_...
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import wait from selenium.webdriver.support.ui import Select from selenium.webdriver.support import expected_...
Python
zaydzuhri_stack_edu_python
set sc_1 = 5 set sc_2 = 0 set win = if expression sc_1 > sc_2 then string Argentina else string Jamaica print win
sc_1=5 sc_2=0 win = "Argentina" if sc_1>sc_2 else "Jamaica" print(win)
Python
zaydzuhri_stack_edu_python
comment encoding:utf-8 import copy import numpy as np comment import jpeg4py as jpeg from PIL import Image from torch.utils.data import Dataset from utils.utils import json_read class CreateDataset extends Dataset begin string root/class_x/xxx.ext root/class_x/xxy.ext root/class_x/xxz.ext root/class_y/123.ext root/clas...
#encoding:utf-8 import copy import numpy as np #import jpeg4py as jpeg from PIL import Image from torch.utils.data import Dataset from ..utils.utils import json_read class CreateDataset(Dataset): ''' root/class_x/xxx.ext root/class_x/xxy.ext root/class_x/xxz.ext root/...
Python
zaydzuhri_stack_edu_python
string ---------------------------------------------- Once data has been populated into Mongo database, this script will populate the bill text in the 'body' field if text doesn't already exist. ---------------------------------------------- from pymongo import MongoClient from bs4 import BeautifulSoup import requests ...
''' ---------------------------------------------- Once data has been populated into Mongo database, this script will populate the bill text in the 'body' field if text doesn't already exist. ---------------------------------------------- ''' from pymongo import MongoClient from bs4 import BeautifulSoup import reques...
Python
zaydzuhri_stack_edu_python
import time from datetime import date , datetime , timedelta import requests import pandas as pd set API_BASE = string https://api.binance.com/api/v3/ set LABELS = list string open_time string open string high string low string close string volume string close_time string quote_asset_volume string number_of_trades stri...
import time from datetime import date, datetime, timedelta import requests import pandas as pd API_BASE = 'https://api.binance.com/api/v3/' LABELS = ['open_time','open','high','low','close','volume','close_time','quote_asset_volume','number_of_trades','taker_buy_base_asset_volume','taker_buy_quote_asset_volume','igno...
Python
zaydzuhri_stack_edu_python
comment https://leetcode.com/problems/n-ary-tree-preorder-traversal/ string # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution begin function preorder self root begin comment ref: https://blog.csdn.net/romeo12334/article/details/81451...
# https://leetcode.com/problems/n-ary-tree-preorder-traversal/ """ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def preorder(self, root: 'Node') -> List[int]: # ref: https://blog.csdn.net/ro...
Python
zaydzuhri_stack_edu_python
function get_matrix transform begin set rotation = rotation set location = location set c_y = cos call radians yaw set s_y = sin call radians yaw set c_r = cos call radians roll set s_r = sin call radians roll set c_p = cos call radians pitch set s_p = sin call radians pitch set matrix = call matrix call identity 4 set...
def get_matrix(transform): rotation = transform.rotation location = transform.location c_y = np.cos(np.radians(rotation.yaw)) s_y = np.sin(np.radians(rotation.yaw)) c_r = np.cos(np.radians(rotation.roll)) s_r = np.sin(np.radians(rotation.roll)) c_p = np.cos(np.ra...
Python
nomic_cornstack_python_v1
function en_to_fa string begin set digits_map = dict string 0 string ۰ ; string 1 string ۱ ; string 2 string ۲ ; string 3 string ۳ ; string 4 string ۴ ; string 5 string ۵ ; string 6 string ۶ ; string 7 string ۷ ; string 8 string ۸ ; string 9 string ۹ if PY2 begin if is instance string unicode begin set digits_map = dic...
def en_to_fa(string): digits_map = { "0": "۰", "1": "۱", "2": "۲", "3": "۳", "4": "۴", "5": "۵", "6": "۶", "7": "۷", "8": "۸", "9": "۹", } if PY2: if isinstance(string, unicode): digits_map = {unicode(e, "ut...
Python
nomic_cornstack_python_v1
function setup_mouse_events self begin call connect display_selected_model call mpl_connect string button_press_event figure_clicked end function
def setup_mouse_events(self): self.view.loaded_files_table.itemDoubleClicked.connect( self.parent.display_selected_model) self.view.figure_widget.canvas.mpl_connect( 'button_press_event', self.view.figure_clicked)
Python
nomic_cornstack_python_v1
comment module import exercise comment using functions built inside it comment currently coded in temp_module: comment def calc_to_fahr (Fahr): comment Fahrenheit = Fahr * 9/5 + 32 comment return Fahrenheit comment def calc_to_cels (Cels): comment Celsius = (Cels - 32) * 5/9 comment return Celsius import temp_module co...
# module import exercise # using functions built inside it # # currently coded in temp_module: # # def calc_to_fahr (Fahr): # Fahrenheit = Fahr * 9/5 + 32 # return Fahrenheit # # def calc_to_cels (Cels): # Celsius = (Cels - 32) * 5/9 # return Celsius # # import temp_module print (temp_module.calc_to_cels(212)...
Python
zaydzuhri_stack_edu_python
function multiplyArray array number begin set resultArray = list for element in array begin set multipliedElement = element * number append resultArray multipliedElement end return resultArray end function set givenArray = list 2 4 6 8 set givenNumber = 3 set newArray = call multiplyArray givenArray givenNumber commen...
def multiplyArray(array, number): resultArray = [] for element in array: multipliedElement = element * number resultArray.append(multipliedElement) return resultArray givenArray = [2, 4, 6, 8] givenNumber = 3 newArray = multiplyArray(givenArray, givenNumber) print(newArray) # Output: [6,...
Python
jtatman_500k
comment -*- coding: utf-8 -*- string This script creates graphical representations of three-voice textures. It uses the csv output of the vertical interval indexer. It shades perfect and mixed sonorities (according to Fuller (1986)) dark and light grey, respectively. Dissonant sonorities are shaded with the function ha...
# -*- coding: utf-8 -*- """ This script creates graphical representations of three-voice textures. It uses the csv output of the vertical interval indexer. It shades perfect and mixed sonorities (according to Fuller (1986)) dark and light grey, respectively. Dissonant sonorities are shaded with the function hatch_2 an...
Python
zaydzuhri_stack_edu_python
import pandas as pd comment Let me run it for you! set df = call read_excel string file.xlsx set sum_value = sum print string Sum: sum_value
import pandas as pd # Let me run it for you! df = pd.read_excel('file.xlsx') sum_value = df['column_name'].sum() print('Sum:', sum_value)
Python
flytech_python_25k
from viztree import deserialize , drawtree import collections class Solution extends object begin function verticalOrder self root begin set depth = 0 set h = default dictionary list set q = list tuple root 0 for tuple node pos in q begin if node begin append h at pos val set q = q + list tuple left pos - 1 set q = q +...
from viztree import deserialize,drawtree import collections class Solution(object): def verticalOrder(self, root): depth=0 h=collections.defaultdict(list) q=[(root,0)] for node,pos in q: if node: h[pos].append(node.val) q+=[(node....
Python
zaydzuhri_stack_edu_python
string Los tramos impositivos para la declaración de la renta en un determinado país son los siguientes: Renta Tipo impositivo Menos de 10000€ 5% Entre 10000€ y 20000€ 15% Entre 200000€ y 35000€ 20% Entre 350000€ y 60000€ 30% Más de 60000€ 45% Escribir un programa que pregunte al usuario su renta anual y muestre por pa...
""" Los tramos impositivos para la declaración de la renta en un determinado país son los siguientes: Renta Tipo impositivo Menos de 10000€ 5% Entre 10000€ y 20000€ 15% Entre 200000€ y 35000€ 20% Entre 350000€ y 60000€ 30% Más de 60000€ 45% Escribir un programa que pregunte al usuario su renta a...
Python
zaydzuhri_stack_edu_python
function _use_tensor_values_cache self begin if trace_mode not in set list TRACE_MODE_NAN_INF TRACE_MODE_NORM TRACE_MODE_MAX_ABS begin return false end if trace_dir and call _trace_files_need_precreated trace_dir begin return true end return use_compact_trace end function
def _use_tensor_values_cache(self): if self._parameters.trace_mode not in set([ tensor_tracer_flags.TRACE_MODE_NAN_INF, tensor_tracer_flags.TRACE_MODE_NORM, tensor_tracer_flags.TRACE_MODE_MAX_ABS]): return False if (self._parameters.trace_dir and _trace_files_need_precreat...
Python
nomic_cornstack_python_v1
function CreateGlobalConstantsDefinition self begin set callResult = call _Call string CreateGlobalConstantsDefinition if callResult is none begin return none end set objId = callResult set classInstance = GlobalConstantsDefinition return call classInstance _xmlRpc objId end function
def CreateGlobalConstantsDefinition(self): callResult = self._Call("CreateGlobalConstantsDefinition", ) if callResult is None: return None objId = callResult classInstance = GlobalConstantsDefinition return classInstance(self._xmlRpc, objId)
Python
nomic_cornstack_python_v1
function loadBPE lang vector_size begin set model = call BPEmb lang=call convert_long_to_short lang dim=vector_size return model end function
def loadBPE(lang, vector_size): model = BPEmb(lang=convert_long_to_short(lang), dim=vector_size) return model
Python
nomic_cornstack_python_v1
comment Class for handling interaction with database comment methods in this class that are not "private": comment connect - connects to the database, and instantiates comment cursor used in the class comment ----------------------------------------------------------------------- comment disconnect - disconnects from t...
# Class for handling interaction with database # # methods in this class that are not "private": # # connect - connects to the database, and instantiates # cursor used in the class #----------------------------------------------------------------------- # disconnect - disconne...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix commen...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix #!pip...
Python
zaydzuhri_stack_edu_python
from random import shuffle set words = list string mitchell string yacine string rain set listt = list function jumble word begin set anagram = list word shuffle anagram return join string anagram end function comment for word in words: comment listt.append(jumble(word)) comment <=====> print list map jumble words co...
from random import shuffle words = ["mitchell","yacine","rain"] listt=[] def jumble(word): anagram = list(word) shuffle(anagram) return ''.join(anagram) # for word in words: # listt.append(jumble(word)) # <=====> print(list(map(jumble, words))) # <=====> print([ jumble(word) for word in wor...
Python
zaydzuhri_stack_edu_python
function is_fulfilled self begin return status == string FULFILLED end function
def is_fulfilled(self) -> bool: return self.status == "FULFILLED"
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment find the csv files import fnmatch import os set csv_files = list for file in list directory string . begin if call fnmatch file string bench-*.csv begin append csv_files file end end comment decide labels function b bench_type begin return string bench- + bench_type + string .csv ...
#! /usr/bin/env python # find the csv files import fnmatch import os csv_files = [] for file in os.listdir('.'): if fnmatch.fnmatch(file, 'bench-*.csv'): csv_files.append(file) # decide labels def b(bench_type): return 'bench-' + bench_type + '.csv' labels = { b('variant32'): '(3,2)', b('...
Python
zaydzuhri_stack_edu_python
function import_from_str import_string begin if is instance import_string str begin set tuple path field_name = call rsplit string . 1 set module = call import_module path return get attribute module field_name end else begin return import_string end end function
def import_from_str(import_string: Optional[Union[Callable, str]]) -> Any: if isinstance(import_string, str): path, field_name = import_string.rsplit(".", 1) module = importlib.import_module(path) return getattr(module, field_name) else: return import_string
Python
nomic_cornstack_python_v1
function rules message=none begin if method == string POST begin comment Remove rules if get form string delete_rules == string true begin comment Create list of rules to remove set remove_list = list for tuple item value in call iteritems begin if item at slice : 5 : == string rule_ begin append remove_list integer ...
def rules(message=None): if request.method == 'POST': # Remove rules if request.form.get('delete_rules') == "true": # Create list of rules to remove remove_list = list() for item, value in request.form.iteritems(): if item[:5] == 'rule_': ...
Python
nomic_cornstack_python_v1
import os import pygame import sys from config import * from platform import Platform from player import Player from wall import Wall from coin import Coin import random class Game begin function __init__ self begin call init set clock = call Clock set surface = call set_mode tuple WIDTH HEIGHT call set_caption TITLE s...
import os import pygame import sys from .config import * from .platform import Platform from .player import Player from .wall import Wall from .coin import Coin import random class Game: def __init__(self): pygame.init() self.clock = pygame.time.Clock() self.surface = pygame.display.set_mo...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string Main 5 import uuid from api.v1.auth.basic_auth import BasicAuth from models.user import User string Create a user test set user_email = string uuid 4 set user_clear_pwd = string uuid 4 set user = call User set email = user_email set first_name = string Bob set last_name = string Dyl...
#!/usr/bin/env python3 """ Main 5 """ import uuid from api.v1.auth.basic_auth import BasicAuth from models.user import User """ Create a user test """ user_email = str(uuid.uuid4()) user_clear_pwd = str(uuid.uuid4()) user = User() user.email = user_email user.first_name = "Bob" user.last_name = "Dylan" user.password =...
Python
zaydzuhri_stack_edu_python
function _end_debug_name obj begin set stack = obj at string debug_name_stack try begin set obj at string debug_name = call popleft end except IndexError begin set obj at string debug_name = none end end function
def _end_debug_name(obj): stack = obj['debug_name_stack'] try: obj['debug_name'] = stack.popleft() except IndexError: obj['debug_name'] = None
Python
nomic_cornstack_python_v1
function convert namespace begin set path = join path BASE_PATH string translations_source namespace if is directory path path begin for tuple dirpath dirnames filenames in walk path begin for filename in list comprehension f for f in filenames if ends with f string .csv begin parse join path dirpath filename namespace...
def convert(namespace): path = os.path.join(BASE_PATH, 'translations_source', namespace) if os.path.isdir(path): for (dirpath, dirnames, filenames) in os.walk(path): for filename in [f for f in filenames if f.endswith(".csv")]: parse(os.path.join(dirpath, filename), namespace...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import pandas as pd from operator import itemgetter import numpy as np set headers = list string ChipID string Power set df = read csv string ../powertest/power_test.csv header=0 names=headers usecols=list 0 5 set chipID = df at string ChipID set power = df at string Power set power_list...
import matplotlib.pyplot as plt import pandas as pd from operator import itemgetter import numpy as np headers = ['ChipID','Power'] df = pd.read_csv('../powertest/power_test.csv', header=0,names=headers,usecols=[0,5]) chipID=df['ChipID'] power=df['Power'] power_list = [] for i in range(len(power)/4): power_list....
Python
zaydzuhri_stack_edu_python
function test_writing_only_valid_profiles self validate_profile_mock upload_tsv_mock begin function side_effect tsv qs begin string Use side_effect to assert at call-time because query return values mutate by the time export_exam_profiles returns assert has attribute tsv string write assert is instance qs list assert l...
def test_writing_only_valid_profiles(self, validate_profile_mock, upload_tsv_mock): def side_effect(tsv, qs): """ Use side_effect to assert at call-time because query return values mutate by the time export_exam_profiles returns """ assert hasattr(tsv,...
Python
nomic_cornstack_python_v1
comment Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. comment Do not allocate extra space for another array, you must do this in place with constant memory. comment For example, comment Given input array A = [1,1,2], comment Your function should ...
###Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. ###Do not allocate extra space for another array, you must do this in place with constant memory. ###For example, ###Given input array A = [1,1,2], ###Your function should return length = 2, and ...
Python
zaydzuhri_stack_edu_python
string 1/11/2021 * This is a simple program made by https://www.instagram.com/a7.acc to check proxies with it's three different types. * There is an explanation for pretty much every line i write. * This program is for educational purposes only. Do not try to use what you learned on unethical programs/activities * This...
''' 1/11/2021 * This is a simple program made by https://www.instagram.com/a7.acc to check proxies with it's three different types. * There is an explanation for pretty much every line i write. * This program is for educational purposes only. Do not try to use what you learned on unethical programs/activiti...
Python
zaydzuhri_stack_edu_python
function timetz self begin return time hour minute second microsecond _tzinfo fold=fold end function
def timetz(self): return time( self.hour, self.minute, self.second, self.microsecond, self._tzinfo, fold=self.fold, )
Python
nomic_cornstack_python_v1
async function devices_post self begin return await post string /devices end function
async def devices_post(self) -> None: return await self.post(f"/devices")
Python
nomic_cornstack_python_v1
function polar_to_cartesian arr axis=- 1 begin if shape at axis != 2 begin raise call ValueError string Expected length of axis { axis } to be 2, got { shape at axis } instead. end set x = call take arr 0 axis=axis * cos call take arr 1 axis=axis set y = call take arr 0 axis=axis * sin call take arr 1 axis=axis return ...
def polar_to_cartesian(arr, axis=-1): if arr.shape[axis] != 2: raise ValueError( f"Expected length of axis {axis} to be 2, got {arr.shape[axis]} " f"instead." ) x = np.take(arr, 0, axis=axis) * np.cos(np.take(arr, 1, axis=axis)) y = np.take(arr, 0, axis=axis) * np.si...
Python
nomic_cornstack_python_v1
function entry self begin set entry_dict = dict string correction 0.0 ; string entry_id task_id ; string composition composition ; string energy energy ; string parameters dict string potcar_spec potcar_spec ; string run_type string run_type ; string data dict string oxide_type call oxide_type structure ; string last_u...
def entry(self): entry_dict = { "correction": 0.0, "entry_id": self.task_id, "composition": self.output.structure.composition, "energy": self.output.energy, "parameters": { "potcar_spec": self.input.potcar_spec, # This i...
Python
nomic_cornstack_python_v1
from PyQt5.QtCore import Qt , pyqtSignal , QSize , QPoint , pyqtSlot , pyqtProperty , QTimer from PyQt5.QtGui import QPainter , QColor , QFont , QFontMetricsF , QPalette , QPolygon , QPen , QBrush from PyQt5 import QtWidgets import math import sys class ImuView2D extends QWidget begin function __init__ self parent=none...
from PyQt5.QtCore import Qt, pyqtSignal, QSize, QPoint, pyqtSlot, pyqtProperty, QTimer from PyQt5.QtGui import QPainter, QColor, QFont, QFontMetricsF, QPalette, QPolygon, QPen, QBrush from PyQt5 import QtWidgets import math import sys class ImuView2D(QtWidgets.QWidget): def __init__(self, parent=None): su...
Python
zaydzuhri_stack_edu_python
function client_node_edge_point self client_node_edge_point begin set _client_node_edge_point = client_node_edge_point end function
def client_node_edge_point(self, client_node_edge_point: List[str]): self._client_node_edge_point = client_node_edge_point
Python
nomic_cornstack_python_v1
function parse_one self data begin call __init__ self set _dispatch_depth = 2 end function
def parse_one(self, data): NodeBuilder.__init__(self) self._dispatch_depth = 2
Python
nomic_cornstack_python_v1
function free_space x y z begin if x == list string R or x == list string r begin return x end else if y at integer x at 0 + 1 at integer x at 1 + 1 != string - begin while y at integer x at 0 + 1 at integer x at 1 + 1 != string - begin set x = list map str split input string (R чтобы начать заново) Место занято, введи...
def free_space(x, y, z): if x == ['R'] or x == ['r']: return x elif y[int(x[0]) + 1][int(x[1]) + 1] != '-': while y[int(x[0]) + 1][int(x[1]) + 1] != '-': x = list(map(str, input('(R чтобы начать заново) Место занято, введи другие координаты: ').split())) y[int(x[0]) + 1][int(x[1]...
Python
zaydzuhri_stack_edu_python
import datetime set seven_am = time set ten_thirty_am = time set five_pm = time set eight_pm = time set nine_am = time set eleven_am = time set six_pm = time set ten_pm = time
import datetime seven_am = datetime.datetime.strptime('07:00', '%H:%M').time() ten_thirty_am = datetime.datetime.strptime('10:30', '%H:%M').time() five_pm = datetime.datetime.strptime('17:00', '%H:%M').time() eight_pm = datetime.datetime.strptime('20:00', '%H:%M').time() nine_am = datetime.datetime.strptime('09:00', '...
Python
zaydzuhri_stack_edu_python
function start self begin print format string Client application started, welcome {0}! name call welcome_state end function
def start(self): print("Client application started, welcome {0}!".format(self.name)) self.welcome_state()
Python
nomic_cornstack_python_v1