content stringlengths 5 1.05M |
|---|
# Generated by Django 4.0.3 on 2022-04-08 09:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('empapp', '0003_programmer_project'),
]
operations = [
migrations.CreateModel(
name='Customer',
... |
"""
Test spectrum reading.
"""
from pathlib import Path
from edges_cal import LoadSpectrum
def test_read(data_path: Path, tmpdir: Path):
calpath = data_path / "Receiver01_25C_2019_11_26_040_to_200MHz"
spec = LoadSpectrum.from_load_name("ambient", calpath, cache_dir=tmpdir)
assert spec.averaged_Q.ndim ... |
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from flask_login import current_user
from flaskblog.models impor... |
#-*- coding: utf-8 -*-
kor = input("국어 점수를 입력하세요.")
eng = input("영어 점수를 입력하세요.")
math = input("수학 점수를 입력하세요.")
total = kor + eng + math
average = total / 3.0
print "입력하신 점수의 총점은",total,"이고,"
print "평균은",average,"입니다."
if average >= 90:
print "수 입니다."
elif average >= 80 and average < 90:
print "우 입니다."
elif avera... |
from dialog_bot_sdk.bot import DialogBot
import grpc
from collections import defaultdict
from dialog_bot_sdk.entities.media.InteractiveMediaGroup import InteractiveMediaStyle
from dialog_bot_sdk.interactive_media import InteractiveMediaGroup, InteractiveMedia, InteractiveMediaSelect, \
InteractiveMediaConfirm, Inte... |
from django.urls import path
#from api.views import company_list, company_details, company_vacancies, vacancies_list, vacancy_detail
from api.views import company_list, company_details
urlpatterns = [
path('companies/', company_list),
path('companies/<int:company_id>/', company_details),
#path('companies/<... |
from django.apps import AppConfig
class MergerConfig(AppConfig):
name = 'merger'
|
# 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 t... |
import datetime
def generate(input_dictionary):
"""
Recombines the user generated input into the output text and sends to save
function to be saved to the disk.
"""
# Get and format user input
output = dict()
output["title"] = input_dictionary["title"]
output["text"] = input_dictionary... |
#!/usr/bin/env python
import torch.nn as nn
class Autoencoder3D(nn.Module):
def __init__(self):
super(Autoencoder3D, self).__init__()
# Architecture adopted from:
# https://www.sciencedirect.com/science/article/pii/S1361841517301287
# Create memoryless-blocks for reuse
... |
from typing import Dict, List
from qaz.managers import brew, npm
from qaz.modules.base import Module
class Bat(Module):
name = "bat"
# Configuration files
zshrc_file = "bat.zsh"
symlinks: Dict[str, str] = {}
# Other
vscode_extensions: List[str] = []
@classmethod
def install_action(... |
from loguru import logger
from aiogram import types
from app.misc import dp
from app.config import MAIN_GROUP_ID
from app.models.user import User
from app.services.server_info import ServerInfo
from app.services.rcon import RCONCommandSender
from app.utils.about_server import info_buttons
@dp.message_handler(comm... |
from dataclay import DataClayObject, dclayMethod
class StorageList(DataClayObject):
"""Demonstration of the StorageList class.
This class is prepared for demonstration purposes and is not suitable,
as it is right now, for HPC applications and production workflows.
@ClassField _list anything
"""
... |
# This is a modified version of Kivy's VideoPlayer UI element. Refer to the file KIVY_LICENSE for copyright and licensing details.
from json import load
from os.path import exists
from kivy.properties import ObjectProperty, StringProperty, BooleanProperty, NumericProperty, DictProperty, OptionProperty
from kivy.animat... |
from contextlib import asynccontextmanager
from unittest.mock import MagicMock
def make_coroutine(mock):
async def coroutine(*args, **kwargs):
return mock
return coroutine
def make_context_manager(mock):
@asynccontextmanager
async def session_get(*args, **kwargs):
yield mock
re... |
import client, errors, listing
import compatibility
from page_nowriteapi import OldPage
import urllib, urlparse, time
class Page(object):
def __init__(self, site, name, info = None, extra_properties = {}):
if type(name) is type(self):
return self.__dict__.update(name.__dict__)
self.site = site
s... |
from typing import Union
from mlprogram.languages import Root
class IsSubtype:
def __call__(self, subtype: Union[str, Root],
basetype: Union[str, Root]) -> bool:
if isinstance(basetype, Root):
return True
if basetype == "Node" and subtype != "str":
return ... |
from django import forms
from django.contrib.auth.forms import UserCreationForm,AuthenticationForm
from .models import UserProfile
# Create your forms here
class LoginForm(AuthenticationForm):
def __init__(self, request, *args, **kwargs):
super().__init__(self, request, *args, **kwargs)
self.fiel... |
import dataset
def build_data_loader(cfg):
param = dict()
for key in cfg:
if key == 'type':
continue
param[key] = cfg[key]
data_loader = dataset.__dict__[cfg.type](**param)
return data_loader
|
from crdt.identifier import Identifier
class Op(object):
pass
class LocalOp(Op):
pass
class RemoteOp(Op):
def __init__(self, op_id):
self.vertex_id = None
self._op_id = op_id
@property
def op_id(self) -> Identifier:
return self._op_id
def undo(self) -> Op:
... |
import unittest
from unittest.mock import MagicMock
from timerecorder.gearShiftHeuristics import GearShiftHeuristics
class TestLuckyGuessHeuristics(unittest.TestCase):
def __init__(self, methodName):
unittest.TestCase.__init__(self, methodName)
def setUp(self):
self.gearTracker = MagicMock()... |
import math
from maxHeap.py import MaxHeap
class MaxPriorityQueue(MaxHeap):
def __init__(self, A: List[int]) -> None:
super().__init__(self, A)
self._build_max_heap()
def heap_max(self) -> int:
return self.A[0]
def extract_max(self) -> int:
"""Extract the max from the tree... |
import xlrd as xl
from xlrd import open_workbook as op
from xlutils.copy import copy
from fuzzywuzzy import fuzz
from fuzzywuzzy import process
#------------------------------------------------
def find_cell(file_name,sheet_name,string,i=0,j=0):
workbook = xl.open_workbook(file_name)
worksheet = workbook... |
#!/usr/bin/env python
import pytest
"""Tests for `cscli` package."""
@pytest.mark.vcr()
def test_cli_init(runner):
"""Test the CLI."""
result = runner(expected_exit_code=2)
assert "Error: Missing command." in result.output
@pytest.mark.vcr()
def test_cli_help(runner):
"""Test top-level --help"""
... |
#!/usr/bin/env python
"""
ZMQ Subscriber for 1602 display
Queue: INF and CMD
"""
import wiringpi2 as wiringpi
import datetime
import time
import json
import Adafruit_DHT
import traceback
import zmq
import sys
import pprint
infoSocket = "tcp://localhost:5550"
cmdSocket = "tcp://localhost:5560"
wiringpi.wiringPiSetu... |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to you under the Apache License, Version 2.0
# (the "License"); you may not use ... |
# -*- coding: utf-8 -*-
'''
File name: code\pythagorean_odds\sol_285.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #285 :: Pythagorean odds
#
# For more information see:
# https://projecteuler.net/problem=285
# Problem Statement
'''
A... |
#
# Copyright (c) 2013 Red Hat, 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 applicable law or agreed t... |
# A binary ordered tree example
class CNode:
left , right, data = None, None, 0
def __init__(self, data):
# initializes the data members
self.left = None
self.right = None
self.data = data
class CBOrdTree:
def __init__(self):
# initializes the root member
... |
"""Definitions related to type hints.
"""
import pathlib
import sys
from delairstack.core.resources.analytics.products import ProductLog
from delairstack.core.resources.resource import Resource
if sys.version_info.minor < 5:
from unittest.mock import MagicMock
__inst = MagicMock()
AnyStr = __inst
Di... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/05_source_data.ipynb (unless otherwise specified).
__all__ = ['SourceData']
# Cell
import os, sys
import numpy as np
import pandas as pd
from .config import *
from .sources import PointSource
from .load_data import load_source_data, binned_exposure
from .simulation impo... |
from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from django.template import loader
from django.conf import settings
from django.contrib.auth.models import User
from rameniaapp.forms import EditProfileForm
from django.views.decorators.csrf import csrf_exempt
def view_following (request, user_id)... |
# Generated by Django 2.0 on 2018-11-20 21:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_remove_blog_readed_num'),
]
operations = [
migrations.RemoveField(
model_name='readnum',
name='blog... |
from restle.serializers import JSONSerializer
from parserutils.elements import element_to_object
class XMLToJSONSerializer(JSONSerializer):
""" Deserializes XML as though it were JSON """
@staticmethod
def to_dict(s):
root, data = element_to_object(s)
return data[root]
|
"""Install bairy."""
import setuptools
with open('README.md') as f:
long_description = f.read()
description = 'Display data from Raspberry Pi.'
install_requires = [
'uvicorn',
'fastapi',
'pydantic',
'dash',
'plotly',
'pandas',
'nest_asyncio',
'aiohttp',
'smbus2',
'gpiozero'
... |
from product import Product
class Equipment(Product):
def __init__(self, name, price, weight):
super().__init__(name, price)
self.weight = weight
|
'''
Contains methods to extract features for training
'''
import pandas as pd
import re
from sklearn.feature_extraction.text import TfidfVectorizer
'''
Feature X vector (a column) to be added to final features data frame
'''
def get_feature_x(train):
feature = []
return feature
'''
Returns 2 feature lists with ... |
#!/usr/bin/env python3
# Future imports (Python 2.7 compatibility)
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
import sys
def radixSort(A):
for i in range(len(A[0])-1, -1, -1):
A = countingSort2(A, i)
print(A)
def countingSort... |
# bsix v1.0
# Contact Me On Facebook For Using This Tool
# Coded By BotolMehedi
# If You Wanna Take Credits For This Code, Please Look Yourself Again...
# Reserved2020
# Powered by Team VVIRUS
import marshal,zlib,base64
exec(zlib.decompress(base64.b16decode("789CBD586D6FDB3610FEDE5FC1A1C09A0243C0774AC030CC962520C0BA154... |
import pgzrun
from math import sin
import random
WIDTH = 800
HEIGHT = 600
SNOWFLAKES = 128
# landscape_colours = [(128,128,128),
# (128, 255, 128),
# (128, 128, 255),
# (255, 128, 128)]
landscape_colours = ['#c6c6c6',
'... |
# -*- coding: utf-8 -*-
'''
Documentación sobre clustering en Python:
http://scikit-learn.org/stable/modules/clustering.html
http://www.learndatasci.com/k-means-clustering-algorithms-python-intro/
http://hdbscan.readthedocs.io/en/latest/comparing_clustering_algorithms.html
https://joernhees.de/blog... |
#!/usr/bin/env python3
'''
A script for outlining C programs
Copyright 2013-2018 RIKEN
Copyright 2017-2021 Chiba Institute of Technology
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... |
#!/usr/bin/env python
"""Utility to parse build.config files in to a shell script"""
from __future__ import print_function
import argparse
import configparser
import sys
DEFAULT_CONFIG = 'utils/build.config'
def parse_cfg_files(cfgparser, file_name, level):
"""Recursively parse config files"""
if level > 5... |
from multimds import data_tools as dt
import sys
import numpy as np
from multimds.hic_oe import oe
def interMatFromBed(path, struct1, struct2):
mat = np.zeros((len(struct1.getPoints()), len(struct2.getPoints())))
with open(path) as infile:
for line in infile:
line = line.strip().split()
index1 = struct1.get_... |
"""All the tests for the jira package.
Refer to conftest.py for shared helper methods.
resources/test_* : For tests related to resources
test_* : For other tests of the non-resource elements of the jira package.
"""
|
ticker not found
---------------------------------------------------------------------------
_RemoteTraceback Traceback (most recent call last)
_RemoteTraceback:
"""
Traceback (most recent call last):
File "/home/nate/anaconda3/lib/python3.6/concurrent/futures/process.py", line 175, in _proce... |
from .folsom import Folsom
|
#!/usr/bin/env python3.7
# scrapeutil.py
"""Utility module Lyric Scraper program."""
# stand lib
import json
from pathlib import Path
import re
import re
import subprocess as sp
from time import sleep
from typing import Any
from typing import List
from typing import Set
from typing import Text
from typing import Tuple... |
#
# PySNMP MIB module NOKIA-COMMON-ALARM-REPORTING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOKIA-COMMON-ALARM-REPORTING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:23:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
import os
import yaml
from .namedelement import NamedElement
from .property import Property
from .method import Method
from .signal import Signal
from .enum import Enum
from .renderer import Renderer
class Interface(NamedElement, Renderer):
@staticmethod
def load(name, rootdir='.'):
filename = os.path... |
# -*- coding: utf-8 -*-
# Version info
__version__ = '0.8.0'
__license__ = 'MIT'
# Project description(s)
__description__ = 'Pretty console printing of tabular data'
# The project's main homepage.
__url__ = 'https://github.com/nirum/tableprint'
# Author details
__author__ = 'Niru Maheswaranathan'
__author_email__ =... |
from __future__ import absolute_import
from matplotlib import pyplot as plt
import os
import tensorflow as tf
import numpy as np
import random
import math
from datetime import datetime
from feature_extraction import create_feats_model, normalize_imgs
class Model(tf.keras.Model):
def __init__(self, num_classes, ... |
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
import argparse
from ocr.helpers import implt, resize, ratio
from ocr import page
#matplotlib inline
plt.rcParams['figure.figsize'] = (15.0, 10.0)
image = cv2.cvtColor(cv2.imread('img.png'), cv2.COLOR_BGR2RGB)
image = page.d... |
import re
import discord
import requests
from bs4 import BeautifulSoup
from discord.ext.commands import Cog, Context, command
from icecream import ic
from neorg.log import get_logger
from neorg.neorg import Neorg
log = get_logger(__name__)
class NeorgCmd(Cog):
"""
NeorgCmd custom call to inspect neorg wiki... |
from .uniq import uniq
from ramda.private.asserts import assert_iterables_equal
def uniq_nocurry_test():
assert_iterables_equal(uniq([1, 2, 3, 3, 4]), [1, 2, 3, 4])
|
#!python
"""Convert input text to pirate speech.
Uses http://isithackday.com/arrpi.php?text= to convert inputted speech to
pirate speech.
`quit` to quit the program.
"""
import urllib
def pirate(text):
connection = urllib.urlopen("http://isithackday.com/arrpi.php?text=%s" % text)
converted = connection.read... |
from __future__ import absolute_import
from sentry.api.serializers import Serializer, register, serialize
from sentry.models import Activity
@register(Activity)
class ActivitySerializer(Serializer):
def serialize(self, obj, attrs, user):
d = {
'id': str(obj.id),
'user': serialize(... |
import main
_MIT_LICENCE = """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, publish, distribute, sublic... |
import numpy as np
import matplotlib.pylab as plt
ro = np.load("points_ro_resample.npy")
pso = np.load("points_pso_resample.npy")
jaya= np.load("points_jaya_resample.npy")
gwo = np.load("points_gwo_resample.npy")
gwo2= np.load("points_gwo_n4_resample.npy")
x = np.arange(100)
plt.plot(x,ro, color='r')
plt.plot(x,pso,... |
from __future__ import absolute_import
from . import driver
from . import interface
from .interface import MeasurementInterface
from .driver import MeasurementDriver
|
import sys
import math
from collections import deque
from itertools import permutations
sys.path.append("../05/")
runner = __import__("05b")
if __name__ == "__main__":
program = list(map(int, input().rstrip().split(",")))
max_output = -math.inf
max_output_phases = None
for phases in permutations(ra... |
from Cython.Build import cythonize
import numpy as np
from distutils.core import setup
try:
numpy_include = np.get_include()
except AttributeError:
numpy_include = np.get_numpy_include()
print(numpy_include)
numpy_include = r'C:/Users/Administrator/AppData/Roaming/Python/Python35/site-packages/numpy/core/inclu... |
########################################################################
#
# Copyright (c) 2018, STEREOLABS.
#
# All rights reserved.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHA... |
# -*- coding: utf-8 -*-
from south.db import db
from south.v2 import SchemaMigration
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'PublicProfilePermissions'
db.delete_table('website_publicprofilepermissions')
# Adding model 'HubPermissions'
db.creat... |
import logging
from typing import Optional
from brownie import chain
from y import convert
from y.constants import weth
from y.datatypes import UsdPrice
from y.decorators import log
from y.networks import Network
from y.prices import magic
from y.typing import AnyAddressType, Block
from y.utils.raw_calls import raw_ca... |
# -*- coding: utf-8 -*-
# !/usr/bin/python
"""
@author: hongyuan
"""
import pickle
import time
#from time import time
import numpy
import random
import os
import datetime
import torch
import torch.optim as optim
import nhp
from DataProcess import processors_nhp
from util import *
#
import argparse
Lamda_file='lamd... |
import math
def triplet_to_hexcolor(t):
return '#%02x%02x%02x' % tuple(map(
lambda x: min(max(int(x*256), 0), 255), t
))
class Tortoise:
def __init__(self, draw_area):
r'''Tortoise(DrawAreaObject)'''
self.draw_area = draw_area
self.init()
def vanish(self):... |
# Copyright 2017 Rice University
#
# 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 writin... |
# Generated by Django 3.0.6 on 2020-05-19 22:08
import uuid
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
#
# For this is how God loved the world:<br/>
# he gave his only Son, so that everyone<br/>
# who believes in him may not perish<br/>
# but may have eternal life.
#
# John 3:16
#
from aRibeiro.tools.SensorVis import *
|
from pydantic import BaseModel
from typing import Optional
class GetAllUsers(BaseModel):
page: int
size: int
class AddUser(BaseModel):
email: Optional[str] = ''
phone: Optional[str] = ''
nickname: str
init_password: str = '123456789'
class UpdateInfo(BaseModel):
nickname: Optional[str]
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This file is part of CERN Search.
# Copyright (C) 2018-2021 CERN.
#
# Citadel Search is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Click command-line utilities."""
import json
import c... |
from MDSplus import *
from myTimebaseSignature import timeSignature
import sys
shot=int(sys.argv[1])
#shot=1130523900
nBoards=1
path='dt216b_1'
print "processing shot %d" % (shot,)
t = Tree('pcilocal', shot)
print " Fixing %s " %(path,)
p = t.getNode(path)
if p.getNode('t_sig_chan').length == 0 :
if node[-7:-1] =... |
from sqlalchemy.sql.functions import mode
from datapools.database import get_db
from sqlalchemy.orm import Session, session
from . import models, schemas
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from datetime imp... |
import winbrew
class Glslang(winbrew.Formula):
url = 'https://github.com/KhronosGroup/glslang/archive/7.8.2853.zip'
homepage = 'https://github.com/KhronosGroup/glslang'
sha1 = '8f7e1ba2bab166e39182790974564d27d6d628c8'
build_deps = ('cmake',)
deps = ()
def build(self):
self.cmake_buil... |
import random
class MapGenerator(object):
def __init__(self, seed, lengthOfMap):
random.seed(seed)
self._length = lengthOfMap
def generateMap(self):
aMap = {}
for i in range(self._length):
aMap[i]=[]
for i in range(self._length):
... |
# 変数pに「東京」を代入してください
p = "東京"
# 変数pを用いて「私は東京出身です」と出力してください
print ("私は" + p + "出身です") |
print("reg [object_number_m1:0] pos_x [6:0];")
print("reg [object_number_m1:0] pos_y [5:0];")
objects = [
[0,0],
[127,63]
]
for object_id in range(len(objects)):
x_position = "{0:b}".format(objects[object_id][0])
x_position = "0"*(7-len(x_position))+x_position
y_position = "{0:b}".format(objects[o... |
import numpy as np
import torch
import torch.nn.functional as F
from scipy.spatial import distance
def L2_distance(feature1, feature2):
# the type of feature1 and feature2 is np.array
if type(feature1) is torch.Tensor:
feature1 = feature1.detach().numpy()
if type(feature2) is torch.Ten... |
#!/usr/bin/env python2
import os, sys, time, subprocess
from subprocess import check_call
dryrun = True
dataset = ["a9a", "music", "covtype", "webspam", "rcv1", "news20", "epsilon"]
nthreads = [1, 5, 10, 20]
algs = [31, 35, 51, 55]
outputdir = "passcode_" + time.strftime("%m%d-%H%M%S")
if not dryrun:
check_call("mk... |
from models import User, Review, Book
from sqlalchemy import and_
def all_score_book(my_book):
scores_list = []
all_score_book = Review.query.filter(Review.book_id == my_book.id )
for row in all_score_book:
scores_list.append(row)
return scores_list
def all_score_user(my_name):
scores_list... |
import torch
import torch.nn as nn
from torchsummary import summary
from genEM3.model.autoencoder2d import Encoder_4_sampling_bn_1px_deep_convonly_skip, Decoder_4_sampling_bn_1px_deep_convonly_skip
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class Split_late... |
"""
Project: Radarbook
File: rounded_nose_cone_example.py
Created by: Lee A. Harrison
On: 11/24/2018
Created with: PyCharm
Copyright (C) 2019 Artech House (artech@artechhouse.com)
This file is part of Introduction to Radar Using Python and MATLAB
and can not be copied and/or distributed without the express permission ... |
# Copyright (c) 2021 PaddlePaddle Authors. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
"""
File: part1b.py
Created by Andrew Ingson (aings1@umbc.edu)
Date: 4/26/2020
CMSC 441 (Design and Analysis of Algorithms)
"""
# size is 312 bits (supposedly)
n = 6207034496804283879630919311406969504330524655944955079581115322595987746105035112739268374117
print("Modulus is", n)
|
def gs_taylor_module(X, Q, bp, ds=None, va=None):
'''Inputs:
X = grid array, first column is r, second column is z
Q = array for quadralaterals
bp = boundary points,
ds,va [OPTIONAL] the delstar operator
Returns:
psi = poloidal flux with peak value unity, long vector form
ps... |
import ctypes
import threading
import sys
import time
# Nasty hack to raise exception for other threads
def _lowlevel_async_raise(thread_obj, exception=None):
NULL = 0
found = False
target_tid = 0
for tid, tobj in threading._active.items():
if tobj is thread_obj:
found = True
... |
""" This is unittest file for parse methods in scenario.py """
import os
import shutil
import tempfile
from deckard import create_trust_anchor_files
def test_create_trust_anchor_files():
"""Trust anchors must be into separate files grouped by domain."""
anchor1a = u'domain1.com.\t3600\tIN\tDS\t11901 7 1 aaaa... |
#!/usr/bin/env python3
"""
# Module: loadguard.core.web.url
This file is a part of LoadGuard Runner.
(c) 2021, Deepnox SAS.
This module provides utilities to manage URLs.
"""
from typing import Dict, Optional, Union, Any
from urllib.parse import ParseResult, urlencode
from deepnox import loggers
from deepnox.mo... |
from bokeh.models.glyphs import VBar as VBar_
from bokeh.models.renderers import GlyphRenderer
from xbokeh.figure.renderers.renderer import Renderer
class VBar(Renderer):
def __init__(self, renderer: GlyphRenderer) -> None:
super().__init__(VBar_, renderer)
|
x_ = []
y_ = []
cor = []
for i in range(3):
x, y = map(int, input().split())
x_.append(x)
y_.append(y)
cor.append([x,y])
x_1 = list(set(x_))
y_1 = list(set(y_))
x_1.sort()
y_1.sort()
min_x = x_1[0]
min_y = y_1[0]
w = x_1[1] - x_1[0]
h = y_1[1] - y_1[0]
if not [min_x, min_y] in cor:
print("%d %d"... |
import os
def write_calib(read_path, write_path):
with open(read_path, 'r') as r, open(write_path, 'w') as w:
temp = ''
lines = r.readlines()
for line in lines:
line = line.strip().split(' ')
if line[0].startswith('m_colorWidth'):
temp = line[2]
... |
"""Standard tests for component"""
import asyncio
from unittest.mock import MagicMock, call
import pytest
from arcam.fmj import (
AmxDuetResponse,
CommandPacket,
InvalidPacket,
ResponsePacket,
_read_response,
write_packet,
IntOrTypeEnum
)
async def test_reader_valid(loop):
reader = a... |
#!/usr/bin/python3.6
import json
from ast import literal_eval
def config_dict():
"""
Opens config.json as a string and then converts it to a dictionary, then returns the dectionary
"""
with open('config.json') as config_file:
conf_dict = json.loads(config_file.read())
return conf_... |
## add your API key from twitter
ATK="ACCESS_TOKEN"
CK="CLIENT_KEY"
CS="CLIENT_SECRET"
ATS="ACCESS_TOKEN_SECRET"
|
import unittest
import hcl2
from checkov.terraform.checks.resource.linode.user_email_set import check
from checkov.common.models.enums import CheckResult
class Testuser_email_set(unittest.TestCase):
def test_success(self):
hcl_res = hcl2.loads("""
resource "linode_user" "test" {
email="l... |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from odoo import models, fields, api, _
from odoo.exceptions import UserError, RedirectWarning, ValidationError
from odoo.exceptions import ValidationError
import odoo.addons.decimal_precision as dp
import logging
class SncRetivaPartners(models.Model... |
def remove_duplicates(list_in):
list_out = []
for i in range(len(list_in)):
if list_in[i] not in list_out:
list_out.append(list_in[i])
else:
continue
return list_out
print(remove_duplicates(["string", "string", "another string", 2, 3, 2]))
|
from django.apps import AppConfig
class JobManagerConfig(AppConfig):
name = 'job_manager'
|
# Copyright 2016 TensorLab. 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. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.