code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import csv import time from collections import Counter import jieba import os import json import pandas as pd comment 统计b站高频词 function gettext begin set data = string set basepath = string /Users/yuanjunping/PycharmProjects/datascience/bilibilidate for i in list directory basepath begin if i == string .DS_Store begin ...
import csv import time from collections import Counter import jieba import os import json import pandas as pd #统计b站高频词 def gettext(): data='' basepath='/Users/yuanjunping/PycharmProjects/datascience/bilibilidate' for i in os.listdir(basepath): if i=='.DS_Store': continue f...
Python
zaydzuhri_stack_edu_python
from flask import Flask , jsonify , request import psycopg2 as psycopg2 set app = call Flask __name__ set dataset = list dict string id 1 ; string nome_coluna string satélite01 ; string lat string 1111111 ; string long string 1111111 dict string id 2 ; string nome_coluna string satélite02 ; string lat string 1111111 ; ...
from flask import Flask, jsonify, request import psycopg2 as psycopg2 app = Flask(__name__) dataset = [ { 'id': 1, 'nome_coluna': 'satélite01', 'lat': '1111111', 'long': '1111111' }, { 'id': 2, 'nome_coluna': 'satélite02', 'lat': '1111111', '...
Python
zaydzuhri_stack_edu_python
function get_system_health self array_id=none begin set array_id = if expression not array_id then array_id else array_id return call get_resource category=SYSTEM resource_level=SYMMETRIX resource_level_id=array_id object_type=HEALTH end function
def get_system_health(self, array_id=None): array_id = self.array_id if not array_id else array_id return self.common.get_resource( category=SYSTEM, resource_level=SYMMETRIX, resource_level_id=array_id, object_type=HEALTH)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Jul 1 13:15:28 2016 @author: Michael Silva import pandas as pd import requests set data = list set service_url = string http://gisservices.dhses.ny.gov/arcgis/rest/services/Locators/Street_and_Address_Composite/GeocodeServer/findAddressCandidates set locations = call ...
# -*- coding: utf-8 -*- """ Created on Fri Jul 1 13:15:28 2016 @author: Michael Silva """ import pandas as pd import requests data = list() service_url = 'http://gisservices.dhses.ny.gov/arcgis/rest/services/Locators/Street_and_Address_Composite/GeocodeServer/findAddressCandidates' locations = pd.read_excel('Event ...
Python
zaydzuhri_stack_edu_python
string 2. Haz un programa en Python que añada películas a un archivo de texto con el siguiente formato: • Una línea por cada película. • <TÍTULO>|<TÍTULO ORIGINAL>|<POPULARIDAD>|<VALORACIÓN>|<FECHA DE ESTRENO> --Este programa recibe como parámetro el nombre de una película (ponlo entre comillas para quePython sepa que ...
""" 2. Haz un programa en Python que añada películas a un archivo de texto con el siguiente formato: • Una línea por cada película. • <TÍTULO>|<TÍTULO ORIGINAL>|<POPULARIDAD>|<VALORACIÓN>|<FECHA DE ESTRENO> --Este programa recibe como parámetro el nombre de una película (ponlo entre comillas para quePython...
Python
zaydzuhri_stack_edu_python
function tag_manifest_into_registry self session worker_digest begin string Tags the manifest identified by worker_digest into session.registry with all the configured tags found in workflow.tag_conf. info string %s: Tagging manifest registry set digest = worker_digest at string digest set source_repo = worker_digest a...
def tag_manifest_into_registry(self, session, worker_digest): """ Tags the manifest identified by worker_digest into session.registry with all the configured tags found in workflow.tag_conf. """ self.log.info("%s: Tagging manifest", session.registry) digest = worker_dige...
Python
jtatman_500k
function get_known_alleles allele_dir begin set known_alleles = dict set alleles = list comprehension f for f in list directory allele_dir if string .f in f for allele in alleles begin set name = base name mistutils allele set path = join path allele_dir allele set known = call init_sets path set known_alleles at name...
def get_known_alleles(allele_dir): known_alleles = {} alleles = [f for f in os.listdir(allele_dir) if '.f' in f] for allele in alleles: name = mistutils.basename(allele) path = os.path.join(allele_dir, allele) known = init_sets(path) known_alleles[name] = known ...
Python
nomic_cornstack_python_v1
function verse_neigh self graph w=none n_hidden=128 steps=100000 n_neg_samples=3 lr=0.0025 rng_seed=0 n_threads=- 1 begin set nv = shape at 0 set ne = nnz if w is none begin set w = as type call rand nv n_hidden float32 - 0.5 end if n_threads < 0 begin set n_threads = cpu count + 1 + n_threads end if n_threads == 0 beg...
def verse_neigh(self, graph, w=None, n_hidden=128, steps=100000, n_neg_samples=3, lr=0.0025, rng_seed=0, n_threads=-1): nv = graph.shape[0] ne = graph.nnz if w is None: w = np.random.rand(nv, n_hidden).astype(np.float32) - 0.5 if n_threads < 0: ...
Python
nomic_cornstack_python_v1
function transform2base self point begin set point = array list point at string x point at string y point at string z 1 set transformed_point = dot point return dict string x transformed_point at 0 ; string y transformed_point at 1 ; string z transformed_point at 2 end function
def transform2base(self, point): point = np.array([point['x'], point['y'], point['z'], 1]) transformed_point = self.tf_base2kinect.dot(point) return {'x': transformed_point[0], 'y': transformed_point[1], 'z': transformed_point[2]}
Python
nomic_cornstack_python_v1
function _create_tag_table self begin string Creates the table to store blog post tags. :return: with call begin as conn begin set tag_table_name = call _table_name string tag if not call has_table conn tag_table_name begin set _tag_table = call Table tag_table_name _metadata call Column string id Integer primary_key=t...
def _create_tag_table(self): """ Creates the table to store blog post tags. :return: """ with self._engine.begin() as conn: tag_table_name = self._table_name("tag") if not conn.dialect.has_table(conn, tag_table_name): self._tag_table = sqla...
Python
jtatman_500k
function test_read_timestamp self begin set past = call mktimestamp - 10 set future = call mktimestamp 10 yield call assert_equal_d none call get_next_read_timestamp yield call store_read_timestamp future yield call assert_equal_d none call get_next_read_timestamp yield call store_read_timestamp past yield call assert_...
def test_read_timestamp(self): past = mktimestamp(-10) future = mktimestamp(10) yield self.assert_equal_d(None, self.worker.get_next_read_timestamp()) yield self.worker.store_read_timestamp(future) yield self.assert_equal_d(None, self.worker.get_next_read_timestamp()) ...
Python
nomic_cornstack_python_v1
class BinaryIndexedTree begin string 1 based indexing function __init__ self arr begin set n = length arr + 1 set tree = list comprehension 0 for i in range n set c = list 0 for i in range 1 n begin add self i arr at i - 1 end end function function getCumulativeFrequency self i begin set sum_ = 0 while i > 0 begin set ...
class BinaryIndexedTree: '''1 based indexing''' def __init__(self, arr): self.n = len(arr) + 1 self.tree = [0 for i in range(self.n)] c = [0] for i in range(1, self.n): self.add(i, arr[i - 1]) def getCumulativeFrequency(self, i): sum_ = 0 while i...
Python
zaydzuhri_stack_edu_python
function test_row_id_exact self begin set mode = string rowid set row = string 2 set ref_row = list 2 set res = call run_task infile=rawfile row=row mode=mode outfile=outfile outform=string ASAP call _test_flag rawfile ref_row end function
def test_row_id_exact(self): self.mode='rowid' row = '2' ref_row = [2] self.res=self.run_task(infile=self.rawfile,row=row,mode=self.mode,outfile=self.outfile,outform='ASAP') self._test_flag(self.rawfile, ref_row)
Python
nomic_cornstack_python_v1
import argparse import os , glob import json from tracker.tracker import PoseTracker function parse_args begin set parser = call ArgumentParser description=string Evaluation of tracker against PoseTrack dataset call add_argument string --annotations required=true type=str help=string Directory containing ground truth a...
import argparse import os, glob import json from tracker.tracker import PoseTracker def parse_args(): parser = argparse.ArgumentParser(description="Evaluation of tracker against PoseTrack dataset") parser.add_argument("--annotations", required=True, type=str, help="Directory containing ground truth annotatat...
Python
zaydzuhri_stack_edu_python
function addRankToLine self cols rank begin set line = string set ann = string ;RankScore= + string family_id + string : + string rank for c in cols begin set line = line + c comment 0-based index if index cols c == 7 begin set line = line + ann end if index cols c < length cols begin set line = line + string end end...
def addRankToLine(self,cols,rank): line = "" ann = ";RankScore=" + str(self.family_id) + ":" + str(rank) for c in cols: line = line + c if cols.index(c) == 7: # 0-based index line = line + ann if cols.index(c) < len(cols): line = line + "\t" print(line)
Python
nomic_cornstack_python_v1
import sys from pymongo import MongoClient from user_report import ask_for_user_id , checks_for_user_id , showReport , nullReport from post_question import postQuestion from search_question import searchQuestions from question_actions import create_answer , list_answers from answer_actions import vote function main beg...
import sys from pymongo import MongoClient from user_report import ask_for_user_id, checks_for_user_id, showReport, nullReport from post_question import postQuestion from search_question import searchQuestions from question_actions import create_answer, list_answers from answer_actions import vote def main(): try:...
Python
zaydzuhri_stack_edu_python
function addNoise self config base im rng current_var draw_method logger begin set var = call getNoiseVariance config base set noise = call VariableGaussianNoise rng var call addNoise noise comment add background if applicable set tuple params safe = call GetAllParams config base req=req opt=opt if string bkg_hdu in pa...
def addNoise(self, config, base, im, rng, current_var, draw_method, logger): var = self.getNoiseVariance(config, base) noise = galsim.noise.VariableGaussianNoise(rng, var) im.addNoise(noise) #add background if applicable params, safe = galsim.config.GetAllParams(config, ...
Python
nomic_cornstack_python_v1
function Name self begin return string SBL Auto Set Call Confirmation for Manual Release end function
def Name(self): return 'SBL Auto Set Call Confirmation for Manual Release'
Python
nomic_cornstack_python_v1
from numpy import * set n = array eval input string vetor de notas dos alunos: set a = 0 for v in n begin if v >= 5 begin set a = a + 1 end end set ap = zeros a dtype=int set i = 0 set c = 0 for v in n begin if n at i >= 5 begin set ap at c = i set c = c + 1 end set i = i + 1 end print a print ap
from numpy import* n=array(eval(input("vetor de notas dos alunos: "))) a=0 for v in n: if v>=5: a= a + 1 ap= zeros(a,dtype=int) i=0 c=0 for v in n: if n[i]>=5: ap[c]=i c= c + 1 i= i + 1 print(a) print(ap)
Python
zaydzuhri_stack_edu_python
comment arrays and math import numpy as np comment opencv library import cv2 from NDVI import NDVICalc from DVI import DVICalc string kullanımı; resim için: python3 pic_main.py R 1617856787332-forest-2.jpg video için: python3 pic_main.py V comment ------------------------------------------- comment ----------------Main...
import numpy as np #arrays and math import cv2 #opencv library from NDVI import NDVICalc from DVI import DVICalc """ kullanımı; resim için: python3 pic_main.py R 1617856787332-forest-2.jpg video için: python3 pic_main.py V """ #------------------------------------------- #----------------Main Function------...
Python
zaydzuhri_stack_edu_python
function irc_msg_split message full_message=true begin if message at 0 == string : and full_message begin comment Drop source for now. set message = join string split message string 1 at slice 1 : : end if string : in message begin set tuple before after = split message string : 1 comment This test is because of par...
def irc_msg_split(message, full_message=True): if message[0] == ':' and full_message: message = ''.join(message.split(' ', 1)[1:]) # Drop source for now. if ':' in message: before, after = message.split(':', 1) # This test is because of partial messages # that begin with : ...
Python
nomic_cornstack_python_v1
string display_2d.py Updated: 2/12/18 Script is used to visualize 2D representations of data. import os import numpy as np from matplotlib.cm import * import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap comment Data Path set path = string ../../data/KrasHras/Hras/1aa9_A function display_2d_arra...
''' display_2d.py Updated: 2/12/18 Script is used to visualize 2D representations of data. ''' import os import numpy as np from matplotlib.cm import * import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap # Data Path path = "../../data/KrasHras/Hras/1aa9_A" ##################################...
Python
zaydzuhri_stack_edu_python
function get_info_json cls flight_pk begin set found = filter flight__id=flight_pk set result = none if exists found begin set flight = get objects id=flight_pk set result = dict string name call get_plural_moniker ; string count count found ; string url reverse string search_map_object_filter kwargs=dict string modelN...
def get_info_json(cls, flight_pk): found = LazyGetModelByName(cls.get_qualified_model_name()).get().objects.filter(flight__id=flight_pk) result = None if found.exists(): flight = LazyGetModelByName(settings.XGDS_CORE_FLIGHT_MODEL).get().objects.get(id=flight_pk) result = ...
Python
nomic_cornstack_python_v1
function mana_cost text begin comment strip Xs from cost set text = replace text string X string comment look for and count up the 'split' mana symbols set hybrid = 0 set nohy = string set cost = split replace text string ( string ) string ) for token in cost begin set regex = match string [wubrg]/[wubrgp] token if re...
def mana_cost(text): # strip Xs from cost text = text.replace('X', '') # look for and count up the 'split' mana symbols hybrid = 0 nohy = '' cost = text.replace('(', ')').split(')') for token in cost: regex = match('[wubrg]/[wubrgp]', token) if regex != None: hy...
Python
nomic_cornstack_python_v1
function svds x cutoff=0.0 cutoff_mode=2 max_bond=- 1 absorb=0 renorm=0 begin set k = call _choose_k x cutoff max_bond if k == string full begin if not is instance x ndarray begin set x = call to_dense end return call svd_truncated x cutoff cutoff_mode max_bond absorb end set tuple U s VH = call svds x k=k return call ...
def svds(x, cutoff=0.0, cutoff_mode=2, max_bond=-1, absorb=0, renorm=0): k = _choose_k(x, cutoff, max_bond) if k == "full": if not isinstance(x, np.ndarray): x = x.to_dense() return svd_truncated(x, cutoff, cutoff_mode, max_bond, absorb) U, s, VH = base_linalg.svds(x, k=k) ...
Python
nomic_cornstack_python_v1
comment 数値の取得 set N = integer input comment 1~9の積で表現できるか検査 set cnt = 1 set judge = string No for cnt in range 1 10 1 begin if N // cnt < 10 and N % cnt == 0 begin set judge = string Yes break end end comment 結果を出力 print judge
# 数値の取得 N = int(input()) # 1~9の積で表現できるか検査 cnt = 1 judge = ("No") for cnt in range(1,10,1): if N // cnt <10\ and N % cnt == 0: judge = ("Yes") break # 結果を出力 print(judge)
Python
zaydzuhri_stack_edu_python
function __init__ self w h begin set active = true set win = call Tk call wm_title string Bot simulation call protocol string WM_DELETE_WINDOW lambda -> call stop set width = w set height = h set canvas = call Canvas win width=width height=height call pack call bind string <Button-1> pressed call bind string <Double-1...
def __init__(self, w, h): self.active = True self.win = Tk() self.win.wm_title('Bot simulation') self.win.protocol("WM_DELETE_WINDOW", lambda: self.stop()) self.width = w self.height = h self.canvas = Canvas(self.win, width=self.width, height=self.height) ...
Python
nomic_cornstack_python_v1
import os from pprint import pprint comment from itertools import accumulate from functools import reduce comment rather than recurse through our tree after creation comment we can store metadata in our global list, and sum this up later set all_metadata = list comment Problem 1 - returns list of reaction string after...
import os from pprint import pprint # from itertools import accumulate from functools import reduce # rather than recurse through our tree after creation # we can store metadata in our global list, and sum this up later all_metadata = [] # Problem 1 - returns list of reaction string after performing all reactions d...
Python
zaydzuhri_stack_edu_python
comment refer readme file for passwords import os , hashlib , csv , sys , shutil comment try except blocks used beacuse you dont have to worry when u run this code multiple times try begin make directory os string DBMS end except FileExistsError begin change directory string DBMS end try else begin change directory str...
import os,hashlib,csv,sys,shutil #refer readme file for passwords try: #try except blocks used beacuse you dont have to worry when u run this code multiple times os.mkdir('DBMS') except FileExistsError: os.chdir('DBMS') else: os.chdir('DBMS') try: #try except blocks used beacuse you dont have to w...
Python
zaydzuhri_stack_edu_python
from PIL import Image import sys import numpy as np import queue import os import matplotlib.pyplot as plt set LIM = 30 set MAX_SIZE = 5000 set IMG_CNT = 5640 set dx = list 0 1 0 - 1 set dy = list - 1 0 1 0 comment takes in rgb function diff u v begin return absolute u at 0 - v at 0 + absolute u at 1 - v at 1 + absolut...
from PIL import Image import sys import numpy as np import queue import os import matplotlib.pyplot as plt LIM = 30 MAX_SIZE = 5000 IMG_CNT = 5640 dx = [0, 1, 0, -1] dy = [-1, 0, 1, 0] def diff(u, v): # takes in rgb return abs(u[0] - v[0]) + abs(u[1] - v[1]) + abs(u[2] - v[2]) def getPic(avg): closest = ...
Python
zaydzuhri_stack_edu_python
function get_name self begin return name end function
def get_name(self): return self.name
Python
nomic_cornstack_python_v1
comment Este programa contempla a resolução do primeiro exercício opcional do curso: comment Introdução à Ciência da Computação com Python Parte 1 comment Disponível no coursera. comment EXERCÍCIO OPCIONAL comment Objetivo comment Você deverá escrever um programa na linguagem Python, versão 3, que permita a uma "vítima...
# Este programa contempla a resolução do primeiro exercício opcional do curso: # Introdução à Ciência da Computação com Python Parte 1 # Disponível no coursera. # EXERCÍCIO OPCIONAL # Objetivo # Você deverá escrever um programa na linguagem Python, versão 3, que permita a uma "vítima" jogar o N...
Python
zaydzuhri_stack_edu_python
function stop self pwsr begin comment You have to implement this method pass end function
def stop(self, pwsr): # You have to implement this method pass
Python
nomic_cornstack_python_v1
function test_line line begin if not strip line begin comment if the last line is blank return false end if starts with line string # begin comment comment line return false end comment swarm result file if starts with line string # begin comment comment line return false end if starts with line string p begin comment ...
def test_line(line): if not line.strip(): return False # if the last line is blank if line.startswith("#"): return False # comment line if line.startswith(" # "): # swarm result file return False # comment line if line.startswith(" p"): return False # com...
Python
nomic_cornstack_python_v1
function on_intent intent_request session begin print string on_intent requestId= + intent_request at string requestId + string , sessionId= + session at string sessionId set intent = intent_request at string intent set intent_name = intent_request at string intent at string name comment Dispatch to your skill's intent...
def on_intent(intent_request, session): print("on_intent requestId=" + intent_request['requestId'] + ", sessionId=" + session['sessionId']) intent = intent_request['intent'] intent_name = intent_request['intent']['name'] # Dispatch to your skill's intent handlers if intent_name == "Find...
Python
nomic_cornstack_python_v1
function list_files self bucket_name begin if not bucket_name begin raise call KeyError string bucket_name is required for kw: list_files end set bucket = call get_bucket bucket_name set all_blobs = call list_blobs return sorted generator expression name for blob in all_blobs end function
def list_files(self, bucket_name: str): if not bucket_name: raise KeyError("bucket_name is required for kw: list_files") bucket = self.get_bucket(bucket_name) all_blobs = bucket.list_blobs() return sorted(blob.name for blob in all_blobs)
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt comment 设置中文 set rcParams at string font.sans-serif = string SimHei comment 导入数据 ['data', 'feature_names'] set data = load np string populations.npz allow_pickle=true comment print(data.files) set name = data at string feature_names comment 切片 set values = data at stri...
import numpy as np import matplotlib.pyplot as plt #设置中文 plt.rcParams['font.sans-serif'] = 'SimHei' # 导入数据 ['data', 'feature_names'] data = np.load('populations.npz', allow_pickle=True) # print(data.files) name = data['feature_names'] # 切片 values = data['data'][-3:-23:-1] print(values[-3:-23:-1]) print(name) # 创建图 p =...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Oct 10 11:12:33 2019 @author: Maibenben comment 爬取李东风PDF文档,网址:http://www.math.pku.edu.cn/teachers/lidf/docs/textrick/index.htm import urllib.request import re import os comment open the url and read function getHtml url begin set page = url open url set html = read pa...
# -*- coding: utf-8 -*- """ Created on Thu Oct 10 11:12:33 2019 @author: Maibenben """ # 爬取李东风PDF文档,网址:http://www.math.pku.edu.cn/teachers/lidf/docs/textrick/index.htm import urllib.request import re import os # open the url and read def getHtml(url): page = urllib.request.urlopen(url) html = page.read() ...
Python
zaydzuhri_stack_edu_python
comment CF 617B: Chocolate set n = integer input set cb = list comprehension integer i for i in split input set res = 1 set curr = 1 set start = false for a in cb begin if a == 1 begin if start begin set res = res * curr end else begin set start = true end set curr = 1 end else begin set curr = curr + 1 end end if not ...
#CF 617B: Chocolate n = int(input()) cb = [int(i) for i in input().split()] res = 1 curr = 1 start = False for a in cb: if a==1: if start: res*=curr else: start = True curr=1 else: curr+=1 if not start: print(0) else: print(res)
Python
zaydzuhri_stack_edu_python
import urllib.request set url = string https://www.example.com
import urllib.request url = 'https://www.example.com'
Python
iamtarun_python_18k_alpaca
import numpy set people = array people set ages = array ages set inds = call argsort set sortedPeople = people at inds
import numpy people = numpy.array(people) ages = numpy.array(ages) inds = ages.argsort() sortedPeople = people[inds]
Python
jtatman_500k
if num1 == 5 and num2 == 2 and op == string * begin print string 15 end else if num1 == 3 and num2 == 4 and op == string + begin print string 10 end else if num1 == 5 and num2 == 6 and op == string / begin print string 60 end else if num1 == 7 and num2 == 5 and op == string - begin print string 6 end else if op == stri...
if num1 == 5 and num2 == 2 and op == "*": print("15") elif num1 == 3 and num2 == 4 and op == "+": print("10") elif num1 == 5 and num2 == 6 and op == "/": print("60") elif num1 == 7 and num2 == 5 and op =="-": print("6") elif op == "+": print("Addition is : ", num1+num2) elif op == "-": ...
Python
zaydzuhri_stack_edu_python
function relink begin call _intro from import crosslink as cr call relink end function
def relink(): _intro() from . import crosslink as cr cr.relink()
Python
nomic_cornstack_python_v1
function _NextItem self begin if _injected begin set _injected = false return _injected_value end try begin comment Object is a generator or iterator. return next end except AttributeError begin pass end except StopIteration begin call Done raise end try begin comment Object is a list. return pop _iterable 0 end except...
def _NextItem(self): if self._injected: self._injected = False return self._injected_value try: # Object is a generator or iterator. return self._iterable.next() except AttributeError: pass except StopIteration: self._tap.Done() raise try: # Object is ...
Python
nomic_cornstack_python_v1
import random import numpy as np import cv2 import dets.common import glob import os from tqdm import tqdm class pick extends object begin function __init__ self img box count width=128 height=128 begin string box是矩阵,存对应[第几个目标][起点x 起点y width height] set img = img set w = shape at 1 set h = shape at 0 set height = heigh...
import random import numpy as np import cv2 import dets.common import glob import os from tqdm import tqdm class pick(object): def __init__(self, img, box, count, width=128, height=128): ''' box是矩阵,存对应[第几个目标][起点x 起点y width height] ''' self.img = img self.w = img.shape[1] ...
Python
zaydzuhri_stack_edu_python
function create_customer_request self service_desk_id request_type_id values_dict raise_on_behalf_of=none begin string Creating customer request :param service_desk_id: str :param request_type_id: str :param values_dict: str :param raise_on_behalf_of: str :return: New request warning string Creating request... set data...
def create_customer_request(self, service_desk_id, request_type_id, values_dict, raise_on_behalf_of=None): """ Creating customer request :param service_desk_id: str :param request_type_id: str :param values_dict: str :param raise_on_behalf_of: str :return: New re...
Python
jtatman_500k
comment coding: utf-8 comment ### <center><b>Data Science with Python</b></center> comment ### <center><b>USA Statistics</b></center> comment #### <center>Group 3 - Team Members<br><br>Jayalakshmi Vaidyanathan<br>Krutika Ambavane<br>Neha Narayankar</center> comment #### Importing all the required libraries: comment In[...
# coding: utf-8 # ### <center><b>Data Science with Python</b></center> # ### <center><b>USA Statistics</b></center> # #### <center>Group 3 - Team Members<br><br>Jayalakshmi Vaidyanathan<br>Krutika Ambavane<br>Neha Narayankar</center> # #### Importing all the required libraries: # In[1]: import pandas as pd import...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/python comment -*- coding: UTF-8 -*- import socket import sys function open ip port begin set s = call socket try begin call connect tuple ip port return true end except any begin return false end end function function scan ip portlist begin for x in portlist begin if open ip x begin print string %s ...
#! /usr/bin/python # -*- coding: UTF-8 -*- import socket import sys def open(ip,port): s = socket.socket() try: s.connect((ip,port)) return True except: return False def scan(ip,portlist): for x in portlist: if open(ip,x): print("%s host %s p...
Python
zaydzuhri_stack_edu_python
string MIT License Copyright (c) 2018 Sebastien Dubois, Sebastien Levy, Felix Crevier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to...
''' MIT License Copyright (c) 2018 Sebastien Dubois, Sebastien Levy, Felix Crevier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to ...
Python
zaydzuhri_stack_edu_python
function __nonzero__ *args **kwargs begin pass end function
def __nonzero__(*args, **kwargs): pass
Python
nomic_cornstack_python_v1
function color_gen org colors begin global NUM_STEPS CUR_STEP ORG_CACHE if org begin set org = upper org end if get ORG_CACHE org is not none begin return ORG_CACHE at org end if NUM_STEPS == - 1 begin try begin set query = dict string size 0 ; string aggs dict string distinct_orgs dict string cardinality dict string f...
def color_gen(org, colors): global NUM_STEPS, CUR_STEP, ORG_CACHE if org: org = org.upper() if ORG_CACHE.get(org) is not None: return ORG_CACHE[org] if NUM_STEPS == -1: try: query = \ { "size": 0, "aggs": { ...
Python
nomic_cornstack_python_v1
function smaller self begin set tuple w1 h1 = tuple decimal imwidth decimal imheight set tuple w2 h2 = tuple decimal __huge_size decimal __huge_size set aspect_ratio1 = w1 / h1 comment it equals to 1.0 set aspect_ratio2 = w2 / h2 if aspect_ratio1 == aspect_ratio2 begin set image = call new string RGB tuple integer w2 i...
def smaller(self): w1, h1 = float(self.imwidth), float(self.imheight) w2, h2 = float(self.__huge_size), float(self.__huge_size) aspect_ratio1 = w1 / h1 aspect_ratio2 = w2 / h2 # it equals to 1.0 if aspect_ratio1 == aspect_ratio2: image = Image.new('RGB', (int(w2), in...
Python
nomic_cornstack_python_v1
function validate_input self begin if not is file path in_file begin print string input file not exits, please check input return false end set ifptr = open in_file string r if not call readable begin print string input file is not readable return false end set ofptr = open out_file string w if not call writable begin ...
def validate_input(self): if not os.path.isfile(self.in_file): print("input file not exits, please check input") return False ifptr = open(self.in_file, "r") if not ifptr.readable(): print("input file is not readable") return False ofptr = ...
Python
nomic_cornstack_python_v1
function off_all self begin clear _event_tree del _any_listeners at slice : : end function
def off_all(self) -> None: self._event_tree.clear() del self._any_listeners[:]
Python
nomic_cornstack_python_v1
function get_current_and_neighbor_features index address_list begin comment Get index position of last token in list set address_length = length address_list - 1 function get_features index pf=string 0_ begin set address = address_list at index set features_dict = dict pf + string first_element if expression index == 0...
def get_current_and_neighbor_features(index, address_list): # Get index position of last token in list address_length = len(address_list) - 1 def get_features(index, pf = "0_"): address = address_list[index] features_dict = {pf + "first_element": True if index == 0 el...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment coding: utf8 from __future__ import absolute_import import requests from geocoder.base import Base from geocoder.keys import gaode_key class Gaode extends Base begin string Gaode AMap Geocoding API =================== Gaode Maps Geocoding API is a free open the API, the default quota 20...
#!/usr/bin/python # coding: utf8 from __future__ import absolute_import import requests from geocoder.base import Base from geocoder.keys import gaode_key class Gaode(Base): """ Gaode AMap Geocoding API =================== Gaode Maps Geocoding API is a free open the API, the default quota 2000 ...
Python
zaydzuhri_stack_edu_python
function do_rate_limited_ops handle num_seconds do_writes limit max_rows min_size max_size begin set put_request = call set_table_name table_name set get_request = call set_table_name table_name comment Generate a string of max_size with all "x"s in it set user_data = string if do_writes begin for x in range max_size ...
def do_rate_limited_ops( handle, num_seconds, do_writes, limit, max_rows, min_size, max_size): put_request = PutRequest().set_table_name(table_name) get_request = GetRequest().set_table_name(table_name) # # Generate a string of max_size with all "x"s in it # user_data = '' if do_writ...
Python
nomic_cornstack_python_v1
from typing import List class UnionFind begin function __init__ self n begin set size = n set tree = list - 1 * n set weight = list 1.0 * n end function function findRoot self x begin if tree at x == - 1 begin return x end set root = call findRoot tree at x set weight at x = weight at x * weight at tree at x set tree a...
from typing import List class UnionFind: def __init__(self, n: int) -> None: self.size = n self.tree = [-1] * n self.weight = [1.0] * n def findRoot(self, x: int) -> int: if self.tree[x] == -1: return x root = self.findRoot(self.tree[x]) self.weight...
Python
zaydzuhri_stack_edu_python
for c in range 1 n + 1 begin if n % c == 0 begin print string  end=string set s = s + 1 end else begin print string  end=string end print format string {} c end=string end print print string -= * 15 if s == 2 begin print format string O número {} é PRIMO. n end else begin print format string ...
for c in range(1, n+1): if n % c == 0: print('\033[33m', end='') s += 1 else: print('\033[31m', end='') print('{} '.format(c), end='') print() print('\033[1;35m-=\033[m'*15) if s == 2: print('\033[1;32mO número {} é PRIMO.'.format(n)) else: print('\033[1;31mO número {} NÃO é ...
Python
zaydzuhri_stack_edu_python
function test_ones_case self begin set steps = call save_divide ones 2 ones 2 call assert_equal steps ones 2 end function
def test_ones_case(self): steps = save_divide(np.ones(2), np.ones(2)) np.testing.assert_equal(steps, np.ones(2))
Python
nomic_cornstack_python_v1
function local2RemoteTime self local_time=none begin comment drift=self.getDrift() set offset = call getOffset if offset is none begin return none end if local_time is none begin set local_time = call getTime end comment local_dt=0.0#local_time-self.L_times[-1] comment +local_dt#drift*local_time+offset return local_tim...
def local2RemoteTime(self,local_time=None): #drift=self.getDrift() offset=self.getOffset() if offset is None: return None if local_time is None: local_time=getTime() #local_dt=0.0#local_time-self.L_times[-1] return (local_time+offse...
Python
nomic_cornstack_python_v1
function point_cloud disparity_image image_left focal_length begin comment wrote code according to stereo_match.py file professor suggest. comment Get height and width of image_left set tuple height width = shape at slice : 2 : comment projection matrix professor suggests comment Example comment [ 1 0 0 image_width /...
def point_cloud(disparity_image, image_left, focal_length): # wrote code according to stereo_match.py file professor suggest. # Get height and width of image_left height, width = image_left.shape[:2] # projection matrix professor suggests # Example # [ 1 0 0 image_width / 2 ] ...
Python
nomic_cornstack_python_v1
function datainborder name cloudn points begin comment judge which stars are located in the region comment form a path object, which represent the border of the region selected set p = call Path points set stardata = call getdata format string ../../data/map2018/snrs/snr{0}new.fits name set coordinates = T set AG = REG...
def datainborder(name, cloudn, points): #judge which stars are located in the region p = path.Path(points) #form a path object, which represent the border of the region selected stardata = fits.getdata('../../data/map2018/snrs/snr{0}new.fits'.format(name)) coordinates = np.vstack([stardata.l, stardata...
Python
nomic_cornstack_python_v1
comment share_snapshot.py from botocore.exceptions import ClientError import boto3 import json import logging set logger = call getLogger call setLevel INFO function lambda_handler event context begin try begin comment log event and extract its parameters info format string event = {} event set region = event at string...
# share_snapshot.py from botocore.exceptions import ClientError import boto3 import json import logging logger = logging.getLogger() logger.setLevel(logging.INFO) def lambda_handler(event, context): try: # log event and extract its parameters logger.info("event = {}".format(event)) regi...
Python
zaydzuhri_stack_edu_python
for i in range integer x begin comment print ("Row", (i+1)) append array list for j in range integer y begin append array at i i * j end end set multlist = list comprehension list comprehension 0 for j in range integer y for i in range integer x print multlist print array
for i in range(int(x)): #print ("Row", (i+1)) array.append([]) for j in range(int(y)): array[i].append(i*j) multlist = [[0 for j in range(int(y))] for i in range(int(x))] print (multlist) print (array)
Python
zaydzuhri_stack_edu_python
function extract_words sentence letter begin set vowels = list string a string e string i string o string u set words = split sentence set extracted_words = list for word in words begin if lower word at 0 == lower letter and length word >= 3 and any generator expression vowel in lower word for vowel in vowels begin ap...
def extract_words(sentence, letter): vowels = ['a', 'e', 'i', 'o', 'u'] words = sentence.split() extracted_words = [] for word in words: if word[0].lower() == letter.lower() and len(word) >= 3 and any(vowel in word.lower() for vowel in vowels): extracted_words.append(word) ...
Python
jtatman_500k
function _add_left self node e begin if _left is not none begin raise call ValueError string Left child exists end set _size = _size + 1 set _left = call _Node e node return _left end function
def _add_left(self,node, e): if node._left is not None: raise ValueError('Left child exists') self._size += 1 node._left = self._Node(e,node) return node._left
Python
nomic_cornstack_python_v1
comment carrega um arquivo do disco rigido para a memoria comment funcao: é uma sequencia de comandos comment recebe uma entrada: comment devolve uma saida: (parametros de entrada -> um resultado) import pandas as pd comment data = pd.read_csv('datasets/kc_house_data.csv') comment # funcao que converte de object (strin...
# carrega um arquivo do disco rigido para a memoria # funcao: é uma sequencia de comandos # recebe uma entrada: # devolve uma saida: (parametros de entrada -> um resultado) import pandas as pd # data = pd.read_csv('datasets/kc_house_data.csv') # # funcao que converte de object (string) para date (ano/mes/dia) # data[...
Python
zaydzuhri_stack_edu_python
from collections import deque set tuple n m = map int split input set graph = list for i in range n begin append graph list map input end
from collections import deque n, m = map(int, input().split()) graph = [] for i in range(n): graph.append(list(map, input()))
Python
zaydzuhri_stack_edu_python
import numpy function mapping X k N begin string Block-mapping sequence. :param X: Position of block [0, N - 1] :param k: Prime secret key in [0 , N - 1] :param N: Number of blocks :return: Mapping of X return k * X % N + 1 end function function removeLSB pixel begin string Function who removes the two LSBs of a pixel....
import numpy def mapping(X, k, N): ''' Block-mapping sequence. :param X: Position of block [0, N - 1] :param k: Prime secret key in [0 , N - 1] :param N: Number of blocks :return: Mapping of X ''' return ((k * X) % N) + 1 def removeLSB(pixel): ''' Function who removes the two ...
Python
zaydzuhri_stack_edu_python
while b < a - 1 and a > 0 begin print string * a + string * + string * * b set a = a - 1 set b = b + 2 end for _ in range 4 begin print string * space - 1 + string ||| end print string * space - 5 string \_@_@_@_/
while b < a-1 and a > 0: print(' '*a+'*'+'*'*b) a -= 1 b += 2 for _ in range(4): print(' '*(space-1)+'|||') print(' '*(space-5), '\_@_@_@_/')
Python
zaydzuhri_stack_edu_python
import unittest import os import sys from pathlib import Path set WEEK2_DIR = string parents at 1 insert path 1 WEEK2_DIR from string_reconstruction import stringReconstruction set DATASET_DIR = join path get current directory string datasets/string_reconstruction class TestStringReconstruction extends TestCase begin f...
import unittest import os import sys from pathlib import Path WEEK2_DIR = str(Path(__file__).resolve().parents[1]) sys.path.insert(1, WEEK2_DIR) from string_reconstruction import stringReconstruction DATASET_DIR = os.path.join(os.getcwd(), 'datasets/string_reconstruction') class TestStringReconstruction(unittest.Tes...
Python
zaydzuhri_stack_edu_python
comment curio/queue.py comment A few different queue structures. comment -- Standard library from collections import deque from heapq import heappush , heappop from concurrent.futures import Future import threading import socket as std_socket import asyncio comment -- Curio from traps import _scheduler_wait , _schedule...
# curio/queue.py # # A few different queue structures. # -- Standard library from collections import deque from heapq import heappush, heappop from concurrent.futures import Future import threading import socket as std_socket import asyncio # -- Curio from .traps import _scheduler_wait, _scheduler_wake, _future_wai...
Python
zaydzuhri_stack_edu_python
async function test_rollback_isolation database_url begin async_with call Database database_url as database begin comment Perform some INSERT operations on the database. async_with call transaction force_rollback=true begin set query = values insert notes text=string example1 completed=true await execute database query...
async def test_rollback_isolation(database_url): async with Database(database_url) as database: # Perform some INSERT operations on the database. async with database.transaction(force_rollback=True): query = notes.insert().values(text="example1", completed=True) await databa...
Python
nomic_cornstack_python_v1
comment 소수 목록 구하기 set MAX = 1000001 set sieve = list false * 2 + list true * MAX - 2 for i in range 2 integer MAX ^ 0.5 + 1 begin if sieve at i == true begin for j in range i + i MAX i begin set sieve at j = false end end end comment 팰린드롬 구하기 function my_func x begin if x == integer string x at slice : : - 1 begin re...
# 소수 목록 구하기 MAX = 1000001 sieve = [False]*2 + [True]*(MAX-2) for i in range(2, int(MAX**0.5)+1): if sieve[i] == True: for j in range(i+i, MAX, i): sieve[j] = False # 팰린드롬 구하기 def my_func(x): if x == int(str(x)[::-1]): return True return False N = int(input()) answer = 0 for i in...
Python
zaydzuhri_stack_edu_python
comment Aizza Asuncion comment UCBSAN1010Data comment Unit 3 homework - PyBoss comment Dr. Spronck comment 5 October 2017 import os import csv import datetime comment create lists to store data set emp_id = list set first_name = list set last_name = list set dob = list set ssn = list set state = list comment crea...
# Aizza Asuncion # UCBSAN1010Data # Unit 3 homework - PyBoss # Dr. Spronck # 5 October 2017 import os import csv import datetime # create lists to store data emp_id = [] first_name = [] last_name = [] dob = [] ssn = [] state = [] # create dictionary of states us_state_abbrev = { 'Alabama': 'AL', 'Alaska': 'A...
Python
zaydzuhri_stack_edu_python
function _runSimulation self cmd timeout directory env=none begin import sys import os import subprocess import time import datetime comment Check if executable is on the path if not call _isExecutable cmd at 0 begin set em = tuple string Error: Did not find executable ' cmd at 0 string '. set em = em + string Make sur...
def _runSimulation(self, cmd, timeout, directory, env=None): import sys import os import subprocess import time import datetime # Check if executable is on the path if not self._isExecutable(cmd[0]): em = f"Error: Did not find executable '", cmd[0], ...
Python
nomic_cornstack_python_v1
function is_imm_op self addr op begin set insn = call insn_t call decode_insn insn addr if type == o_imm begin return true end return false end function
def is_imm_op(self, addr, op): insn = ida_ua.insn_t() ida_ua.decode_insn(insn, addr) if (insn.ops[op].type == idc.o_imm): return True return False
Python
nomic_cornstack_python_v1
function get_abs_text record begin set result = list try begin for item in record at string MedlineCitation at string Article at string Abstract at string AbstractText begin append result item end end except KeyError begin pass end if length result == 0 begin return string *Abstract Unavailable* end else begin return ...
def get_abs_text(record): result = [] try: for item in record['MedlineCitation']['Article']['Abstract']['AbstractText']: result.append(item) except KeyError: pass if len(result) == 0: return '*Abstract Unavailable*' else: return ' '.join(result)
Python
nomic_cornstack_python_v1
function __init__ self colour begin set colour = colour set name = string Player end function
def __init__(self, colour): self.colour = colour self.name = "Player"
Python
nomic_cornstack_python_v1
function subscribers_by_name self username repository_name access_token=none begin return call _complete_request_by_name username repository_name string subscribers access_token end function
def subscribers_by_name(self, username, repository_name, access_token=None): return self._complete_request_by_name( username, repository_name, "subscribers", access_token)
Python
nomic_cornstack_python_v1
function show_user_handler user_id begin set auth_error = call authenticate_user key if auth_error begin return call json_success_return auth_error end set dbaccess = call create_service set user = get dbaccess table=USERS_TABLE w_filter=string id = + user_id multiple=false if user begin return call json_success_return...
def show_user_handler(user_id): auth_error = authenticate_user(request.query.key) if auth_error: return json_success_return(auth_error) dbaccess = SqliteDbAccess.create_service() user = dbaccess.get(table=USERS_TABLE, w_filter=("id =" + user_id), multiple=False) if user: return js...
Python
nomic_cornstack_python_v1
function sample_patch_perspective image inv_xform_3x3 patch_size begin set patch_size_tuple = tuple patch_size at 0 patch_size at 1 set inv_xform_array = reshape inv_xform_3x3 9 / inv_xform_3x3 at tuple 2 2 set patch = transform image patch_size_tuple PERSPECTIVE inv_xform_array NEAREST set ones_img = call new string L...
def sample_patch_perspective(image, inv_xform_3x3, patch_size): patch_size_tuple = (patch_size[0], patch_size[1]) inv_xform_array = inv_xform_3x3.reshape(9,) / inv_xform_3x3[2,2] patch = image.transform(patch_size_tuple, Image.PERSPECTIVE, inv_xform_array, Image.NEAREST) ones_img = Image.new('L', image.size, 2...
Python
nomic_cornstack_python_v1
string event 线程互斥方法演示 string 实现多个线程之间的通信,就使用全局变量 但要防止共享资源的无序争夺,共享资源被有序存取 做法:全局变量可能被多个线程使用,用Event()对象的 set() 和 wait()(阻塞) 实现线程的同步互斥 from threading import Thread , Event comment 用于通信 set s = none comment 事件对象 set e = event function 杨子荣 begin print string 杨子荣前来拜山头 global s set s = string 天王盖地虎 comment 操作完共享资源 e 设置 set end...
""" event 线程互斥方法演示 """ """ 实现多个线程之间的通信,就使用全局变量 但要防止共享资源的无序争夺,共享资源被有序存取 做法:全局变量可能被多个线程使用,用Event()对象的 set() 和 wait()(阻塞) 实现线程的同步互斥 """ from threading import Thread, Event s = None # 用于通信 e = Event() # 事件对象 def 杨子荣(): print("杨子荣前来拜山头") global s s = "天王盖地虎" e.set() # 操作完共享资源 e 设置 t = Thread(tar...
Python
zaydzuhri_stack_edu_python
set a = 5 set b = 10 set c = 15 if c > a + b begin print string c is greater than the sum of a and b end else if c == a + b begin print string c is equal to the sum of a and b end else if a + b > c begin print string The sum of a and b is greater than c end else begin print string c is less than the sum of a and b end
a = 5 b = 10 c = 15 if c > a + b: print("c is greater than the sum of a and b") elif c == a + b: print("c is equal to the sum of a and b") elif a + b > c: print("The sum of a and b is greater than c") else: print("c is less than the sum of a and b")
Python
jtatman_500k
function initialize_all_targets begin string Initialize all targets. Necessary before targets can be looked up via the :class:`Target` class. call LLVMPY_InitializeAllTargetInfos call LLVMPY_InitializeAllTargets call LLVMPY_InitializeAllTargetMCs end function
def initialize_all_targets(): """ Initialize all targets. Necessary before targets can be looked up via the :class:`Target` class. """ ffi.lib.LLVMPY_InitializeAllTargetInfos() ffi.lib.LLVMPY_InitializeAllTargets() ffi.lib.LLVMPY_InitializeAllTargetMCs()
Python
jtatman_500k
import socket import sys import json import time import random function unpickle file begin import pickle with open file string rb as fo begin set dict = load pickle fo encoding=string bytes end return dict end function function nameImg ID begin set images = call unpickle string ./cifar-10-batches-py/batches.meta retur...
import socket import sys import json import time import random def unpickle(file): import pickle with open(file, 'rb') as fo: dict = pickle.load(fo, encoding='bytes') return dict def nameImg(ID): images = unpickle("./cifar-10-batches-py/batches.meta") return images[b"label_names"][ID] im...
Python
zaydzuhri_stack_edu_python
comment This is a simple Python script to show the use of classes comment Pushed to github class Car begin function __init__ self model make color begin set model = model set make = make set color = color set features = list end function function add_features self feature begin append features feature end function end...
# This is a simple Python script to show the use of classes # Pushed to github class Car: def __init__(self,model,make,color): self.model = model self.make = make self.color = color self.features = [] def add_features(self,feature): self.features.append(feature) toyot...
Python
zaydzuhri_stack_edu_python
import sys for i in stdin begin set tuple numer denom = split i set numer = integer numer set denom = integer denom if denom == 0 begin break end print string { numer // denom } { numer % denom } / { denom } end
import sys for i in sys.stdin: numer,denom = i.split() numer = int(numer) denom = int(denom) if denom == 0: break; print(f"{numer // denom} {numer % denom} / {denom}")
Python
zaydzuhri_stack_edu_python
function get_all_rankings session begin return list comprehension call Ranking matrix for matrix in list session end function
def get_all_rankings(session: CondorSession) -> List[sc.Ranking]: return [sc.Ranking(matrix) for matrix in RankingMatrix.list(session)]
Python
nomic_cornstack_python_v1
function create_pascal_label_colormap begin set colormap = zeros tuple 256 3 dtype=int set ind = array range 256 dtype=int for shift in reversed range 8 begin for channel in range 3 begin set colormap at tuple slice : : channel = colormap at tuple slice : : channel ? ind ? channel ? 1 ? shift end set ind = ind ? ...
def create_pascal_label_colormap(): colormap = np.zeros((256, 3), dtype=int) ind = np.arange(256, dtype=int) for shift in reversed(range(8)): for channel in range(3): colormap[:, channel] |= ((ind >> channel) & 1) << shift ind >>= 3 return colormap
Python
nomic_cornstack_python_v1
function query_simbad self radius=3 begin set radius = if expression radius is not none then radius * arcsec else 3 * arcsec if verbose begin print string Searching MAST for ( { target_coord } ) with radius= { radius } . end set simbad = call Simbad call add_votable_fields string typed_id string otype string sptype str...
def query_simbad(self, radius=3): radius = radius * u.arcsec if radius is not None else 3 * u.arcsec if self.verbose: print( f"Searching MAST for ({self.target_coord}) with radius={radius}." ) simbad = Simbad() simbad.add_votable_fields("typed_id",...
Python
nomic_cornstack_python_v1
function api self begin return namespaces at path end function
def api(self): return self.fluid.namespaces[self.path]
Python
nomic_cornstack_python_v1
function proxy_port self begin return _proxy_port end function
def proxy_port(self) -> ConfigNodePropertyInteger: return self._proxy_port
Python
nomic_cornstack_python_v1
function test_175_114 self begin exit 0 end function
def test_175_114(self): self.spawn("./encryption").stdin("175").stdin("114").stdout("Success\n").exit(0)
Python
nomic_cornstack_python_v1
comment !venv/bin/python3 from PySide2 import QtCore from PySide2.QtCore import Qt from PySide2.QtCore import QFile , QTimer , QDate from PySide2.QtUiTools import QUiLoader from PySide2.QtGui import QFont , QColor , QBrush , QTextCharFormat class MainWindow extends object begin function __init__ self parent=none begin ...
#!venv/bin/python3 from PySide2 import QtCore from PySide2.QtCore import Qt from PySide2.QtCore import QFile, QTimer, QDate from PySide2.QtUiTools import QUiLoader from PySide2.QtGui import QFont, QColor, QBrush, QTextCharFormat class MainWindow(object): def __init__(self, parent=None): """Main window, h...
Python
zaydzuhri_stack_edu_python
async function _async_fallback_poll self begin await call async_poll_battery end function
async def _async_fallback_poll(self) -> None: await self.speaker.async_poll_battery()
Python
nomic_cornstack_python_v1
import pygame import sys set red = tuple 255 0 0 set green = tuple 0 255 0 set blue = tuple 0 0 255 set darkBlue = tuple 0 0 128 set white = tuple 255 255 255 set black = tuple 0 0 0 set pink = tuple 255 200 200 comment iconChoice = input("Would you like to be X's or O's?(X/O)?:") set iconChoice = string X comment init...
import pygame import sys red = (255,0,0) green = (0,255,0) blue = (0,0,255) darkBlue = (0,0,128) white = (255,255,255) black = (0,0,0) pink = (255,200,200) #iconChoice = input("Would you like to be X's or O's?(X/O)?:") iconChoice = "X" # initialize game engine pygame.init() pygame.font.init() font = pygame.font.Sys...
Python
zaydzuhri_stack_edu_python
function frontiers_style begin string Figure styles for frontiers set inchpercm = 2.54 set frontierswidth = 8.5 set textsize = 5 set titlesize = 7 call rcdefaults update rcParams dict string figure.figsize list frontierswidth / inchpercm frontierswidth / inchpercm ; string figure.dpi 160 ; string xtick.labelsize textsi...
def frontiers_style(): ''' Figure styles for frontiers ''' inchpercm = 2.54 frontierswidth=8.5 textsize = 5 titlesize = 7 plt.rcdefaults() plt.rcParams.update({ 'figure.figsize' : [frontierswidth/inchpercm, frontierswidth/inchpercm], 'figure.dpi' : 160, ...
Python
jtatman_500k
async function test_binary_sensors hass mock_bridge_v2 v2_resources_test_data begin await call load_test_data v2_resources_test_data await call setup_platform hass mock_bridge_v2 string binary_sensor comment there shouldn't have been any requests at this point assert length mock_requests == 0 comment 2 binary_sensors s...
async def test_binary_sensors( hass: HomeAssistant, mock_bridge_v2, v2_resources_test_data ) -> None: await mock_bridge_v2.api.load_test_data(v2_resources_test_data) await setup_platform(hass, mock_bridge_v2, "binary_sensor") # there shouldn't have been any requests at this point assert len(mock_br...
Python
nomic_cornstack_python_v1