content stringlengths 5 1.05M |
|---|
import matplotlib.pyplot as plt
import numpy as np
###Problem 1
N=10000
mathematics = np.random.normal(500,100,N)
reading = np.random.normal(500,100,N)
writing = np.random.normal(500,100,N)
SATscore = mathematics + reading + writing
plt.hist(SATscore)
plt.show()
np.std(SATscore)
np.sqrt(3*10000)
np.var(SATscore)
n... |
#------------------------------------------------------------------------------
#
# PyGUI - OpenGL - Win32
#
#------------------------------------------------------------------------------
import win32con as wc, win32ui as ui, win32gui as gui
import GDIPlus as gdi
import WGL
from GUI.Components import win_none
from ... |
from Repositorio.Entidades.Nave import Nave
from Repositorio.Conexao.conexao import ConexaoPostgre
class NavesRepositorio:
def __init__(self):
self.conexao = ConexaoPostgre()
def createNave(self, nave):
con = self.conexao.conectar()
cur = con.cursor()
sql = f"""INSERT INTO tb_... |
import numpy as np
from scipy import spatial
class Camera( object ):
"""
A utility class for storing camera properties (position, dimensions, fov etc.).
"""
def __init__(self, pos, ori, proj, fov, dims, step = None):
"""
Creates a new camera object.
*Arguments*:
- pos... |
import datajoint as dj
from element_lab import lab
from element_animal import subject
from element_session import session_with_datetime as session
from element_event import trial, event
from element_miniscope import miniscope
from element_lab.lab import Source, Lab, Protocol, User, Location, Project
from element_anim... |
"""
"""
from typing import List, Set, Dict
from collections import Counter
import datetime as dttm
from app.utility.decorators import type_check
from app.engines.reddit import connect_to_reddit
from app.constants import SUB_REDDIT, BLACK_LISTED_STOCK_NAMES
from app.utility.nltk import (
get_stock_symbols,
tok... |
"""
"""
import pytest
import numpy as np
from ..v4_sdss_assign_gri import assign_restframe_sdss_gri
@pytest.mark.xfail
def test1():
"""
"""
ngals = int(1e4)
satmask = np.random.rand(ngals) < 0.3
num_sats = np.count_nonzero(satmask)
upid = np.zeros(ngals, dtype=int) - 1
upid[satmask] = np.... |
import FWCore.ParameterSet.Config as cms
# Define the CMSSW process
process = cms.Process("RERUN")
import PhysicsTools.PatAlgos.tools.helpers as configtools
patAlgosToolsTask = configtools.getPatAlgosToolsTask(process)
# Load the standard set of configuration modules
process.load('Configuration.StandardSequences.Ser... |
from hubcheck.pageobjects.basepagewidget import BasePageWidget
from hubcheck.pageobjects.basepageelement import Text
from hubcheck.exceptions import NoSuchFileAttachmentError
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.excep... |
import scadnano as sc
def create_design():
length = 16
helices = [
sc.Helix(major_tick_distance=4, max_offset=length, position=sc.Position3D(x=0, y=0, z=0),
min_offset=0),
sc.Helix(major_tick_distance=4, max_offset=length, position=sc.Position3D(x=0, y=3, z=3),
... |
''' Database Settings '''
from masonite import env
from dotenv import find_dotenv, load_dotenv
from orator import DatabaseManager, Model
'''
|--------------------------------------------------------------------------
| Load Environment Variables
|----------------------------------------------------------------------... |
import io
import os
import json
import zipfile
import subprocess
import logging
import shlex
import pathlib
from io import BufferedReader
from typing import Union
from hashlib import md5
from django.utils import timezone
from datetime import datetime
from core.enums.log_type_enum import LogType
from core.exceptions i... |
from dagster import composite_solid, pipeline, solid
from food_ke.scripts.modes import dev, prod
from food_ke.scripts.ner import (
chunk_articles,
get_articles,
get_spans_from_chunks,
)
@composite_solid(required_resource_defs={"ner_training_io_manager"})
def get_ner_training_data_composite_solid():
a... |
import win32api
import win32con
class Controller:
@staticmethod
def left():
win32api.keybd_event(0x27, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.keybd_event(0x25, 0, 0, 0)
@staticmethod
def right():
win32api.keybd_event(0x25, 0, win32con.KEYEVENTF_KEYUP, 0)
win32api.key... |
import Stats
import dbutils as db
from Stats import DM
# shorthand
split = DM.split_on_attributes
array = Stats.array
def rows_to_data(rows):
return array([(r['lateness'], r['trip_stop_weight']) for r in rows]);
## Initial retrieval and sorting of data
# Grab data needed
cur = db.get_cursor()
db.SQLExec(cur,S... |
#!/usr/bin/env python
from __future__ import print_function
import os
from glob import glob
def getsections():
for filename in (filename for filename in glob("*.md") if filename != "index.md"):
with open(filename, 'r') as f:
yield (True, filename, "")
for section in filter(lambda x... |
import os
import uuid
import xml
import xml.etree.ElementTree
from xml.etree import ElementTree
import pytest
from pyPreservica import *
FOLDER_ID = "ebd977f6-bebd-4ecf-99be-e054989f9af4"
ASSET_ID = "683f9db7-ff81-4859-9c03-f68cfa5d9c3d"
CO_ID = "0f2997f7-728c-4e55-9f92-381ed1260d70"
XML_DOCUMENT = "<person:Person ... |
from unittest import TestCase
from taskobra.orm import get_engine, get_session, ORMBase
class ORMTestCase(TestCase):
def tearDown(self):
with get_session(bind=get_engine("sqlite:///:memory:")) as session:
for table in session.execute("SELECT * FROM sqlite_master WHERE type='table'"):
... |
""" A CatController Module """
from masonite.controllers import Controller
from masonite.request import Request
from app.Cat import Cat
class CatController(Controller):
"""Class Docstring Description
"""
def __init__(self, request:Request):
self.request = request
def show(self):
id =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 Lee McCuller <mcculler@mit.edu>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline ... |
import pickle
import cv2 as cv
import numpy as np
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.dataloader import default_collate
from torch.utils.data.dataset import Dataset
from torchvision import transforms
from config import im_size, pickle_file
class adict(dict):
def __init__(sel... |
'''邻接矩阵'''
import numpy as np
import xlrd
data = xlrd.open_workbook('HLM.xlsx')
table = data.sheets()[1]
m, n = table.nrows, table.ncols
# i = j = 0
s = t = i = 0
flag = 0
# print(m,n)
def cell(x, y):
return table.cell(x, y).value
ss = set()
for i in range(m):
for j in range(n):
if cell(i, j) != "":
ss.add(ce... |
# Copyright (c) 2015 Uber Technologies, Inc.
#
# 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 use, copy, modify, merge, publ... |
from lego.apps.ical.models import ICalToken
from lego.apps.users.models import User
from lego.utils.test_utils import BaseTestCase
class TokenTestCase(BaseTestCase):
fixtures = ['test_abakus_groups.yaml', 'test_meetings.yaml', 'test_users.yaml']
def setUp(self):
self.user = User.objects.get(id=1)
... |
"""
Name: arXiv Intelligence NER Web Service
Authors: Jonathan CASSAING
Web service specialized in Named Entity Recognition (NER), in Natural Language Processing (NLP)
"""
import json
import time
# PDF list used as references to compare
# the extracted named entities
# The named entities as references are saved
# in ... |
from talon.voice import Context
from . import browser
from ...misc import audio
context = Context(
"netflix", func=browser.url_matches_func("https://www.netflix.com/.*")
)
context.keymap(
{"full screen": [lambda m: audio.set_volume(100), browser.send_to_page("f")]}
)
|
#Q: Add all the natural numbers below one thousand that are multiples of 3 or 5.
#A: 233168
sum([i for i in xrange(1,1000) if i%3==0 or i%5==0])
|
import sys
import subprocess as sp
LinuxDis = sys.argv[1]
## python3-gdalのインストール
if LinuxDis == "Ubuntu":
sp.call("sudo apt-get install -y python3-gdal", shell=True)
elif LinuxDis == "CentOS":
sp.call("sudo yum install -y python3-gdal", shell=True)
## requirements.txtからPIPでインストール
with open("./requirements.t... |
import requests
import logging
import pytz
from django.core.mail import EmailMessage
from vaccine_tracker.models import UsersData
from celery import shared_task
from tracker.celery import app
from vaccine_tracker.email import email_body, email_subject
from django.conf import settings
from django_celery_results.models ... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from sklearn.cluster import SpectralClustering
from sklearn.datasets import make_blobs
from sklearn.neighbors import kneighbors_graph
from scipy.sparse import *
from scipy import *
from autosp import predict_k
def consistent_labels(labels):
"""Achieve "some" consist... |
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import azure_blob_helper
SAVE_DIR = "/data/mnist/checkpoints/"
tf.app.flags.DEFINE_integer('model_version', 2, 'version number of the model.')
FLAGS = tf.app.flags.FLAGS
class Model:
sess = tf.InteractiveSession()
seria... |
class FileManager:
"""
Class to implement file access to store inventory to maintain persistence
"""
def __init__(self):
self.inventory = ''
@staticmethod
def clear_inventory_file():
"""
Static method to clear inventory file after winning a game
Returns:
... |
"""
You are given a dictionary/hash/object containing some languages and your test results in the given languages.
Return the list of languages where your test score is at least 60, in descending order of the results.
Note: the scores will always be unique (so no duplicate values)
"""
def my_languages(results: dict)... |
import time
import os
import re
import math
import keyboard
from datetime import datetime
import tkinter as tk
from tkinter import filedialog
def ClearConsole():
os.system('cls' if os.name == 'nt' else 'clear')
startingTimeStamp = ""
endingTimeStamp = ""
#Regex for HH:MM:SS
timePattern = re.compi... |
"""
Translator from output neuron spike trains to actions
for the environment. Actioned determined based on neuron
firing rate greater than action_threshold or not, as
`output_range[firing_rate >= action_threshold]`.
"""
import numpy as np
from spikey.module import Module, Key
from spikey.snn.readout.template import R... |
#!/usr/bin/python2
# Copyright (c) 2014, 2015 Mathias Laurin
# BSD 3-Clause License (http://opensource.org/licenses/BSD-3-Clause)
r"""Print all dependencies required to build a port as a graph.
Usage:
port_deptree.py [--min] PORTNAME [VARIANTS ...]
Example:
port_deptree.py irssi -perl | dot -Tpdf -oirssi.pdf... |
from .endpoint import Endpoint
class File(Endpoint):
def __init__(self, filename):
self.filename = filename
def read(self):
with open(self.filename, 'r') as f:
return f.readlines()
def write(self, data):
with open(self.filename, 'w+') as f:
f.writelines(da... |
# 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 applicable law or agreed to in writing, software
# distributed under the Li... |
"""
Extract local maxima from a spm, return a csv file with variables:
- x-axis array index (i)
- y-axis array index (j)
- z-axis array index (k)
- peak z-value
- peak p-value
"""
import numpy as np
import pandas as pd
def PeakTable(spm, exc, mask):
"""
Identify local maxima above z-value threshold in masked... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
from telemetry import story
from telemetry.core import platform
from telemetry.page import page
from telemetry.interna... |
# this is a file, otherwise known as a "module" in python
# the __future__ module can help make in built functions backwards compatible
# https://docs.python.org/2/library/__future__.html
from __future__ import print_function
import os
from sys import platform
import json
def function():
# get the path to this m... |
import numpy as np
import torch
import torch.nn as nn
import torchvision
import pandas as pd
import matplotlib.pyplot as plt
import torch.nn.functional as F
from sklearn import metrics
import torchvision.transforms as transforms
from Dataset.Utils import get_target_label_idx,global_contrast_normalization,OneClass
from ... |
"""
Title: Simple custom layer example: Antirectifier
Author: [fchollet](https://twitter.com/fchollet)
Date created: 2016/01/06
Last modified: 2020/04/20
Description: Demonstration of custom layer creation.
"""
"""
## Introduction
This example shows how to create custom layers, using the Antirectifier layer
(original... |
""" Implementation of a node in linked lists and binary search trees. """
from typing import TypeVar, Generic
I = TypeVar('I')
K = TypeVar('K')
T = TypeVar('T')
__author__ = 'Maria Garcia de la Banda and Brendon Taylor. Modified by Alexey Ignatiev'
__docformat__ = 'reStructuredText'
class TreeNode(Generic[K, I]):
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Classes to manage priors
"""
from __future__ import absolute_import, division, print_function
import numpy as np
import scipy.stats as stats
from scipy.interpolate import interp1d
from scipy.integrate import quad
from dmsky.utils import stat_funcs
fr... |
import os
from invoke import task
from .vars import conf
@task
def clean(
c,
build=False,
test=False,
sonar=False,
):
patterns = []
if build:
patterns += ["build", f"{conf.name}.egg-info", "**/*.pyc"]
if sonar:
patterns += [
os.path.join(conf.name, s)
... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import os
import json
import time
import boto3
from aws_lambda_powertools import Logger
from template_evaluation import eval_expression, eval_template
logger = Logger()
personalize = boto3.client('personalize')
event... |
import os
import re
from setuptools import find_packages, setup
def read(f):
return open(f, 'r', encoding='utf-8').read()
def get_version(package):
init_py = open(os.path.join(package, '__init__.py')).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)
setup(
name='djan... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import os... |
import argparse
import sys
import yaml
from source.utils import visualize_filters, printconfig
from source.train import training
from source.test_image import testing_image
from source.test_video import testing_video
if __name__ == "__main__":
""" Main script - runs everything from here
main.py is the prima... |
import re
from string import ascii_lowercase
from PyQt5.QtCore import QMutex, QCoreApplication
from PyQt5.QtWidgets import QWidget, QTabWidget, QTabBar, QLineEdit
from pyntpg.dataset_tabs.dataset_tab import DatasetTab
from pyntpg.datasets_container import DatasetsContainer
class DatasetTabs(QTabWidget):
""" Hig... |
import cv2 # pip install opencv-python
print("Versão do OpenCV:", cv2.__version__)
webCam = cv2.VideoCapture(1)
while(True):
conectou, imagem = webCam.read()
cv2.imshow("Rosto", imagem)
teclou = cv2.waitKey(1) & 0xFF
if teclou == ord('q') or teclou == 27: # se apertar q ou ESC
break
web... |
# Generated by Django 3.0.11 on 2020-11-26 16:35
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pretixbase', '0170_remove_hidden_urls'),
]
operations = [
migrations.AddField(
model_name='que... |
#LER 2 Nº E COMPARE-OS - MAIOR OU MENOR
|
import enum
from typing import Dict, List, Optional, Tuple
from .fluent_dict import FluentDict, FluentList
from .geometry import GeoPoint
from .request import RegionQuery, MapRegion, PayloadKind, RegionQueryBuilder, IgnoringStrategyKind, MapRegionBuilder
from .request import Request, GeocodingRequest, ExplicitRequest,... |
from rest_framework.serializers import ModelSerializer
from .models import SimData
class SimSerializer(ModelSerializer):
class Meta:
model = SimData
fields = ['id', 'healthyYoung', 'healthyYoungFreerider',
'sickYoung', 'healthyElderly', 'healthyElderlyFreerider',
'sickElderly', ... |
import argparse as arg
import markov as markov
import sys
import re
import os
import glob
import pickle
"""
This module processes the text and builds Markov
model. The interaction is through CLI
"""
def process_console():
"""
sets arguments for the CLI
:return: parser
"""
parser = arg.Argu... |
from django.apps import apps
from django.contrib.auth import models as auth
import graphene
from graphene_django.types import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
from aristotle_mdr import models as mdr
from aristotle_dse import models as dse
from aristotle_mdr.contrib.iden... |
# Generated by Django 3.1.7 on 2021-05-02 18:13
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('profiles', '0015_auto_20180423_0727'),
('profiles', '0011_accountstatus_user_name'),
]
operations = [
]
|
from scoring_engine.models.property import Property
from tests.scoring_engine.helpers import generate_sample_model_tree
from tests.scoring_engine.unit_test import UnitTest
class TestProperty(UnitTest):
def test_init_property(self):
property_obj = Property(name="testname", value="testvalue")
asse... |
from django.apps import AppConfig
class VivaappConfig(AppConfig):
name = 'vivaapp'
|
import os
import shutil
from pathlib import Path
import random
class TestSupport:
"""
Macros, utility functions for tests.
"""
THIS_DIR = Path(os.path.dirname(os.path.realpath(__file__)))
PROJECT_DIR = THIS_DIR.parent
SUBJECTS_DIR = PROJECT_DIR / "test-subjects"
class get_playground_path:... |
from abc import ABC, abstractmethod
class AbstractComparator(ABC):
pass
|
# coding=utf-8
import base64
from data import s, rs, Rcon
# key块 为四位字符串
# S 盒转化
def S(key):
ans = ''
for i in key:
tmp = "0x" + "{:02x}".format(ord(i))
ans += chr(int(s[tmp], 16))
return ans
# 逆S盒转化
def RS(key):
ans = ''
for i in key:
tmp = "0x" + "{:02x}".format(ord(i))
... |
import micropython
import gc
import os
def df():
s = os.statvfs('//')
return ('{0} MB'.format((s[0]*s[3])/1048576))
def free(full=False):
F = gc.mem_free()
A = gc.mem_alloc()
T = F+A
P = '{0:.2f}%'.format(F/T*100)
if not full:
return P
else:
return ('Total:{0} Free:{1... |
from cytomine import Cytomine
import cytomine.models
import time
import shapely
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
#import pylab as plt
import openslide as ops
from fig2img import fig2img,SaveFigureAsImage
from Histupload import HistUpload
#Replace XXX values by... |
from pydantic import BaseModel
from decimal import Decimal
class productBase(BaseModel):
product_code: str
product_name: str
price: Decimal
|
"""
Prediction Processor:
This adaptor act as the interface between the prediction process's output and the activity you want to perform on that.
As this is an independent adaptor, we can replicate the same for many multiple output methods.
"""
from __future__ import print_function, division, with_statement
... |
# https://tjkendev.github.io/procon-library/python/math/gcd.html
# Euclidean Algorithm
def gcd(m, n):
r = m % n
return gcd(n, r) if r else n
# Euclidean Algorithm (non-recursive)
def gcd2(m, n):
while n:
m, n = n, m % n
return m
# Extended Euclidean Algorithm
def extgcd(a, b):
if b:
... |
import cv2
import numpy as np
d = 400
img = np.ones((d, d, 3), dtype=np.uint8) * 255
pts = np.array([[200, 50], [300, 200], [200, 350], [100, 200]], np.int32)
pts = pts.reshape(-1, 1, 2)
cv2.polylines(img, [pts], True, (0, 255, 0), 8)
winname = "Demo19.01"
cv2.namedWindow(winname)
cv2.imshow(winname, img)
cv2.waitKey... |
# Set up analysis and PATHS
# imports
import platform
import os
import pandas as pd
import numpy as np
import json
import sys
from sklearn.preprocessing import OneHotEncoder
from .utils.fmri_core import analysis as pa
from .utils.fmri_core import utils as pu
from .utils.fmri_core import vis as pv
from .utils.fmri_cor... |
from __future__ import absolute_import
# Copyright (c) 2010-2019 openpyxl
from .chartsheet import Chartsheet
|
import random
import cv2
import numpy as np
from vision.find_car_number import FindCarNumber
class Vision:
def __init__(self, image_path):
self.image = cv2.imread(image_path)
def get_car_number_pos(self):
"""获取车牌位置"""
c = FindCarNumber(image=self.image).find_card_pos()
retur... |
# 再パラメータ化 reparameterization
# 目的: サンプリングの効率化
# データのスケーリングもreparameterizationの一種
# 最初は極端な例、"Nealの漏斗"を見てみる。
import numpy as np
import seaborn as sns
import pandas
import matplotlib.pyplot as plt
import mcmc_tools
import scipy.stats as stats
from scipy.stats import norm
import random
# Nealの漏斗
# データが無く、事前分布がそのまま事後分布にな... |
masses = [
54755,
96495,
111504,
53923,
118158,
118082,
137413,
135315,
87248,
127646,
79201,
52399,
77966,
129568,
63880,
128973,
55491,
111226,
126447,
87017,
112469,
83975,
51280,
60239,
120524,
57122,
13651... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
class SuningBookPipeline(object):
list = []
def process_item(self, item, spider):
SuningBookPipeline.list.a... |
from flask_restplus import Resource
from flask_restplus.namespace import Namespace
from restplus.api.v1.helpers import safe_user_output
from restplus.models import users_list
users_ns = Namespace('users')
class AllUsers(Resource):
def get(self):
"""
View all users
"""
users =... |
#
# PySNMP MIB module SYMMCOMMONPPSTOD (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMMCOMMONPPSTOD
# Produced by pysmi-0.3.4 at Tue Jul 30 11:34:54 2019
# On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt
# Using Python version 3.7.4 (defa... |
"""ABOUT
"""
APP_NAME = "pyswd"
VERSION = "v1.0.0"
AUTHOR = "Pavel Revak"
AUTHOR_EMAIL = "pavel.revak@gmail.com"
DESCRIPTION = "SWD debugging tool"
URL = "https://github.com/pavelrevak/pyswd"
|
# sum of digits of number
def sum_digit(n):
s = 0
while n != 0:
s += n % 10
n //= 10
return s
if __name__ == "__main__":
print(sum_digit(1234))
|
import unittest
from mock import patch
import gevent
import gevent.queue
from steam.core.cm import CMClient
class CMClient_Scenarios(unittest.TestCase):
test_channel_key = b'SESSION KEY LOL'
def setUp(self):
# mock out crypto
patcher = patch('steam.core.crypto.generate_session_key')
s... |
from abc import ABCMeta, abstractmethod
class Explainer(metaclass=ABCMeta):
@abstractmethod
def __init__(self, model, data, feature_names=None, target_names=None):
raise NotImplementedError
@abstractmethod
def explain(self, X, y):
raise NotImplementedError |
import logging
import multiprocessing
import os
from bootleg.utils import train_utils
def get_log_name(args, mode):
log_name = os.path.join(train_utils.get_save_folder(args.run_config), f"log_{mode}")
log_name += train_utils.get_file_suffix(args)
log_name += f'_gpu{args.run_config.gpu}'
return log_na... |
from pycipher.caesar import Caesar
import unittest
class TestCaesar(unittest.TestCase):
def test_decipher(self):
''' Caesar (test_decipher): test known ciphertext->plaintext pairs '''
text = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
declist = ['xyzabcdefghijklmnopqrstuvwxyzabc... |
import os
import webbrowser as wb
def workstation():
codePath = "C:\\Program Files\\Sublime Text 3\\sublime_text.exe"#ADD THE PATH OF TXET EDITOR OR IDE HERE
os.startfile(codePath)
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'#ADD THE PATH OF CHROME HERE
URLS = (
"stackov... |
import unittest
import pysal
from pysal.core.IOHandlers.gwt import GwtIO
import tempfile
import os
import warnings
class test_GwtIO(unittest.TestCase):
def setUp(self):
self.test_file = test_file = pysal.examples.get_path('juvenile.gwt')
self.obj = GwtIO(test_file, 'r')
def test_close(self):
... |
from app.forms.serializers.forms import (
FieldInAnswerSerializer,
FormInSubmissionSerializer,
FormPolymorphicSerializer,
FormSerializer,
AnswerableFormSerializer,
EventFormSerializer,
OptionSerializer,
)
from app.forms.serializers.statistics import FormStatisticsSerializer
|
# @date 2022-03-13
# @author Frederic Scherma, All rights reserved without prejudices.
# @license Copyright (c) 2022 Dream Overflow
# Trader info command
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from trader.trader import Trader
from terminal.terminal import Terminal
... |
#!/usr/bin/env python
# Copyright (c) 2011-2016 Rackspace US, Inc.
#
# 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 app... |
import colorama
colorama.init()
print(colorama.Fore.RED + 'This is red')
from colorama import *
init()
print(Fore.YELLOW + 'This is yellow')
from colorama import init, Fore
print(Fore.GREEN + 'This is green')
|
# HACK: if the profile plugin is imported before the coverage plugin then all
# the top-level code in pytest_profiling will be omitted from
# coverage, so force it to be reloaded within this test unit under coverage
from six.moves import reload_module # @UnresolvedImport
import pytest_profiling
reload_module(pytest_... |
from predictor_caffe import PredictorCaffe
from predictor_mxnet import PredictorMxNet
import numpy as np
def compare_diff_sum(tensor1, tensor2):
pass
def compare_cosin_dist(tensor1, tensor2):
pass
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
... |
import bmp280
from machine import Pin, I2C
from time import sleep
scl=Pin(5)
sda=Pin(4)
i2c=I2C(scl=scl, sda=sda)
print('Found on I2C bus: ', i2c.scan())
bmp=bmp280.BMP280(i2c)
while True:
print('t=', bmp.temperature, ' p=', bmp.pressure / 100.0)
sleep(5)
|
from typing import List, Literal
from pydantic import BaseModel, validator
from podping_hivewriter.models.medium import mediums
from podping_hivewriter.models.reason import reasons
class Podping(BaseModel):
"""Dataclass for on-chain podping schema"""
version: Literal["1.0"] = "1.0"
medium: str
reas... |
# The Fibonacci numbers.
# Reformulate that as
# fold1 = 1
# fold2 = 1
# fnew = fold1 + fold2
# After that, discard fold2 , which is no longer needed, and set fold2 to fold1 and fold1 to
# fnew . Repeat an appropriate number of times.
# Implement a program that prompts the user for an integer n and prin... |
# Generated by Django 3.2.4 on 2021-06-21 13:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("supply_chains", "0021_alter_supplychain_slug"),
]
operations = [
migrations.AddField(
model_name="maturityselfassessment",
... |
from tempfile import TemporaryDirectory
from unittest import TestCase
from oasislmf.model_testing.validation import csv_validity_test
from oasislmf.utils.exceptions import OasisException
class TestValidation(TestCase):
def test_csv_validity_test___model_data_directory_is_empty(self):
"""
Test cs... |
#START HERE
###############################
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
folder_name = "<FOLDER_CONTAINING_SAM_FILES>"
data_file_names = os.listdir(folder_name)
plt.switch_backend('agg')
files = []
for i in data_file_names:
if i[-3:] == "sam":
files.append((folde... |
from django.db import models
from django.utils.text import slugify
from django.urls import reverse
class Category(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'Cat... |
from solution import Foo, Uniquish
def test_foo():
f1 = Foo(10)
f2 = Foo(10)
f3 = Foo(10)
s = {f1, f2, f3}
assert len(s) == 1
assert hash(f1) == hash(f2)
assert hash(f2) == hash(f3)
def test_subclass_non_uniquish():
class Bar():
def __init__(self, x):
self.x = x... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.