content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
import math
def main():
state = input("""
What would you lke todo:
(1) Calculate a rectangle perimeter based on its width and height
(2) Calculate a circle perimeter based on its radio
(3) Calculate a sphere volume based on its radio
(4) Calculate a rectangle's area
(5) Calculate the... |
#!/usr/bin/env python
description = ">> New automated sn measurement"
usage = "%prog image [options] "
import time
from numpy import array,log10
import numpy as np
import lsc
import glob
import os
import sys
import shutil
import string
import re
from astropy.io.fits import getheader
from astropy.io import fits
from op... |
# -*- coding: utf-8 -*-
import os
import shutil
import numpy as np
from tqdm import tqdm
import torch
import torchvision
import torchvision.transforms as transforms
import binarybrain as bb
def main():
# configuration
data_path = './data/'
net_name = 'MnistDifferentiableLutSimp... |
# Generated by Django 3.1.3 on 2020-11-19 17:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('intern_xplorer', '0012_auto_20201119_1542'),
]
operations = [
migrations.AlterField(
model_name='company',
name='nam... |
from thimblesgui import QtGui, QtWidgets, QtCore, Qt
Signal = QtCore.Signal
Slot = QtCore.Slot
QModelIndex = QtCore.QModelIndex
from thimbles.abundances import Ion
from thimbles import ptable
from thimbles.periodictable import symbol_to_z, z_to_symbol
from thimblesgui.expressions import PythonExpressionLineEdit
from ... |
# coding: utf-8
import logging
from allauth.account import adapter, app_settings, models, utils
from allauth.exceptions import ImmediateHttpResponse
from allauth.socialaccount import providers
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.conf import settings
from django.contrib im... |
import pandas as pd
from covidactnow.datapublic.common_fields import CommonFields
from libs.datasets import data_source
from libs.datasets import dataset_utils
class CmdcDataSource(data_source.DataSource):
DATA_PATH = "data/cases-cmdc/timeseries-common.csv"
SOURCE_NAME = "CMDC"
# CMDC data reports value... |
import unittest
from unittest import mock
from unittest.mock import patch
from source import points
import numpy as np
class TestPoints(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
self.img=np.ones((10,10))
self.img2= np.ones((11,11))
def test_check_number(sel... |
import numpy as np
from matplotlib import pyplot as plt
from axes_sequence import AxesSequence
plt.close("all")
# Make axes-sequence
axes = AxesSequence()
# Add a couple of plots
for i, frame in zip(range(3), axes):
x = np.linspace(0, 10, 100)
frame.plot(x, np.sin(i * x))
frame.set_title('Line {}'.forma... |
import sys
from mypy import build
from mypy.main import process_options
def get_ast():
sources, options = process_options(sys.argv[1:])
res = build.build(sources, options)
for module_name, f in res.files.items():
if f.path == sys.argv[1]:
print(str(f))
return
print('Mod... |
# give output as string because input function default takes string value
'''a = input("Enter 1st number : ")
b = input("Enter 2nd number : ")
print(a+b)'''
# type casting but its takes memory space for other variable
'''a = input("Enter 1st number : ")
x = int(a)
b = input("Enter 2nd number : ")
y = int(b)
print(a+... |
class Node:
def __init__(self, block_id: int, addr: int):
self.id = block_id
self.addr = addr
self.parents = set()
self.children = set()
|
from insights.parsers.numeric_user_group_name import NumericUserGroupName
from insights.tests import context_wrap
from insights.parsers import ParseException
ZERO = """
/etc/passwd:0
/etc/group:0
""".strip()
NONZERO_1 = """
/etc/passwd:3
/etc/group:0
""".strip()
NONZERO_2 = """
/etc/passwd:0
/etc/group:4
""".strip()... |
# Copyright 2018 Google LLC
#
# 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, s... |
def get_image_path(targetObject, element):
return targetObject + "/" + targetObject + "_32bt_" + element + ".tif"
def get_target_mask(targetObject):
return targetObject + "/" + targetObject + "_mask.tif"
def compare_dist(maskImage, indexImage, distImage, cmpIndex, cmpDists):
tWidth = len(maskImage[0])
tHeight... |
from django.urls import path, include
from main.views import *
app_name = 'main'
urlpatterns = [
path('subjects/', SubjectListView.as_view(), name="subjects"),
path('subjects/<slug:slug>', SubjectQuestionView.as_view()),
path('questions/', QuestionListView.as_view(), name="questions"),
path('questio... |
from . import network
Network = network.Network
|
from .common import *
class Tag:
def __init__(self, key, value):
self.key = key
self.value = value
def to_dict(self):
return {"key": from_str(self.key),
"value": from_str(self.value)}
class Vpc:
def __init__(self, id, vpc, region, cidr_block, integration_id, inte... |
#!/usr/bin/env python2
"""Calculates the number of deaths per book in the 'Song of Ice and Fire' series (aka Game of Thrones)."""
import csv
import numpy as np
import matplotlib.pyplot as plt
BOOKS = ('GoT', 'CoK', 'SoS', 'FfC', 'DwD')
def read_dataset():
# i-th element (zero-indexed) with value n means that n d... |
import matplotlib.pyplot as plt
import numpy as np
from owcsimpy.geoobjects.models.humancubes_py import HumanCubes_py as Human
from owcsimpy.geoutils.draw import draw
person = Human(np.array([1,1]),np.deg2rad(30),reflectivities={'hair':0.7,'face':0.5,'shirt':0.3})
draw(models3d=person,figsize=(6,6),azim=-100,elev=25,... |
"""
String Constants used in vAPI runtime
"""
__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2015-2019 VMware, Inc. All rights reserved. -- VMware Confidential' # pylint: disable=line-too-long
PARAMS = 'params'
SCHEME_ID = 'schemeId'
AUTHN_IDENTITY = 'authnIdentity'
EXECUTION_CONTEXT = 'ctx'
APPLICATION_CO... |
import subprocess
from kubernetes_setup_functions import *
def scale_wordpress(autoscale_p, cpu_percent_cuttoff, deployment_scaling):
goal_wp_containers = deployment_scaling['wordpress']['max']
wp_min = deployment_scaling['wordpress']['min']
wp_cpu_percent_cutoff = cpu_percent_cuttoff
if autoscale_p a... |
from .argument_parser import * # noqa: F401
from .dictionary import * # noqa: F401
from .fuzzer import * # noqa: F401
from .path import * # noqa: F401
from .report_manager import * # noqa: F401
from .raw import * # noqa: F401
|
# File Created: 10/15/2020
# Author: Jack Connor <jconnor@baaqmd.gov>
from postman_problems.tests.utils import create_mock_csv_from_dataframe
from graph import create_rpp_edgelist
import initialize_lib as il
def InnerAndOuterToEdgeListFile(directory = 'C:\\Users\jconnor\OneDrive - Bay Area Air Quality Management Dist... |
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
import praw
import string
import tensorflow as tf
import os
import itertools
import nltk
from tensorflow.keras.models import load_model
from keras.preprocessing.sequence import pad_sequences
from nltk.corpus import stopwords
fro... |
#Script to find areas of houses that are a certain distance from an explosion point.
#Allows the user to input different feature layers to run the model, such as different building or point location files.
#Allows the user to specify parameters.
import arcpy
from arcpy import env
#arcpy.env.workspace = "C:/Use... |
import numpy as np
from scipy import io
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
column_num=18
step=100
delta=0.001
z=4
#加载训练数据,默认进行归一化
def Traindata(name_list,if_nor=True):
np_D = np.zeros((1, column_num))
for i in range(len(name_list)):
dict_obj = io.loadmat(n... |
#!/usr/bin/env python3
# versatiletrainer.py
#
# Based on logisticpredict, which was based on (!)
# logisticleave1out.py which was based on (!!)
# parallel_crossvalidate.py from the paceofchange repo.
#
# The goal of the module is to construct predictive
# models of corpus *subsets*, in a very flexible way.
# This is ... |
import frontmatter
import shutil
import os
def write_file(content, location, **frontmatter_data):
"""
:param content: `str` the main file content (excluding frontmatter)
:param location: `str` path to write the file to
:param frontmatter: `splat` of frontmatter keys / values to write to the file
:... |
# -*- coding: utf-8 -*-
"""Family module for Wikimedia Strategy Wiki."""
from __future__ import unicode_literals
__version__ = '$Id: 3d3570cde504f7fa5a46107ce6debdfb8338afc4 $'
from pywikibot import family
# The Wikimedia Strategy family
class Family(family.WikimediaFamily):
"""Family class for Wikimedia Stra... |
import os
import logging
import ipaddress
import subprocess
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor
import luigi
from luigi.util import inherits
from recon.config import tool_paths, defaults
from recon.web.targets import GatherWebTargets
@inherits(GatherWebTargets)
class Webanalyz... |
#aluguel de carros
dia = int(input('O carro foi alugado por quantos dias? '))
km = float(input('Quantos km foram rodados? '))
valor_km = (km*0.15)
valor_dia = (dia*60)
print('O total a pagar é de R${:.2f}'.format(valor_dia + valor_km))
|
try:
from setuptools import setup as setup_orig, Distribution, Command
except ImportError:
from distutils.core import setup as setup_orig, Distribution, Command
dist = Distribution()
build_orig = dist.get_command_class('build')
sdist_orig = dist.get_command_class('sdist')
class generate_man(Command):
des... |
from plaster.tools.pipeline.pipeline import PipelineTask
from plaster.run.classify_rf.classify_rf_params import ClassifyRFParams
from plaster.run.classify_rf.classify_rf_worker import classify_rf
from plaster.run.sim.sim_result import SimResult
from plaster.run.sigproc_v1.sigproc_v1_result import SigprocV1Result
from p... |
import os
import numpy as np
import pandas as pd
import ast
from pprint import pprint
import json
import csv
# from architecture_statistics.get_data_gensim import check_andr
from collections import Counter
import seaborn as sns
import matplotlib.pyplot as plt
#
# def extract_hashcodesFrom_clusters(featu... |
class ClayfulException(Exception):
def __init__(
self,
model = None,
method = None,
status = None,
headers = None,
code = None,
message = '',
validation = None):
self.is_clayful = True
self.model = model
self.method = method
self.status = status
self.headers = headers
self.code = code
s... |
"""
微信公众平台消息回复实现工具
maker - 消息回复制作器
message - 消息类型回复
event - 事件类型回复
url - url 参数验证
"""
from .event import Event
from .message import Message
from .url import URLParamater as Url
from .maker import MakeReply as Maker
|
#
# xcPROJECTNAMEASIDENTIFIERxcDocument.py
# xcPROJECTNAMExc
#
# Created by xcFULLUSERNAMExc on xcDATExc.
# Copyright xcORGANIZATIONNAMExc xcYEARxc. All rights reserved.
#
from Foundation import *
from AppKit import *
class xcPROJECTNAMEASIDENTIFIERxcDocument(NSDocument):
def init(self):
self = super(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------
# File: core/smalisca_app.py
# Created: 2015-01-17
# Purpose: Defines how an application is built.
# Provides information about classes, methods and properties.... |
import tkinter as tk
import tkinter.filedialog as fd
import src.helper.gui as hg
from src.elgamal.main import generate_pair
class ElGamalGenerateKey(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
self.initialize()
h... |
class ModuleManager(object):
def __init__(self):
self._module_listing = []
def append_module(self, module):
reference = {
'name': module.__name__,
'directory': self._module_directory(module),
}
self._module_listing.append(reference)
def module_dir... |
# 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
# d... |
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','unbind.settings')
import django
django.setup()
import random
import fake_gen
import sys
import datetime
from django.conf import settings
from django.utils.timezone import make_aware
from usuario.models import Usuario
from artigo.models import Artigo
from cate... |
# illustrate the van der pol oscillator
import numpy as np
import matplotlib.pyplot as plt
def rhs(x, y, mu=1.):
xp = mu*(y - (x**3)/3. + x)
yp = -1./mu * x
return xp, yp
dt = 1e-2
steps = 1000
t = np.arange(0,steps*dt,dt)
s = 20
n = s**2
l = 3
# Need one more for the initial values
xs = np.nan*np.emp... |
def output():
print('Welcome to Cats Library!') |
import pytest
import pydp as pd
class TestStatus():
def test_hello(self):
i = 1
assert 1 == i
def test_status_codes(self):
status_code_available = [
"StatusCode.kOk",
"StatusCode.kCancelled",
"StatusCode.kUnknown",
"StatusCode.kInvalidA... |
class Movie(object):
#Using not really all the data for this project - just some of them
#For the real project - describe all movie fields
def __init__(self, imbnum="", title="", year="", notes=""):
self.imbnum = imbnum
self.title = title
self.year = year
self.notes=notes
@clas... |
import argparse
from scripts.similarity import Similarity
from fourlang.text_to_4lang import TextTo4lang
from fourlang.lexicon import Lexicon
from scripts.parse_data import read
import pandas as pd
import subprocess
import sys
import os
import requests
import time
class Monolingual:
def __init__(self, lang):
... |
from array import* #here * means to include all the functions of array
vals = array('i',[3,5,7,9])
vals.reverse()
for i in vals:
print(i)
print("-------")
vals = array('i',[2,5,4])
for i in range(len(vals)):
print(vals[i])
print("-------")
val = array('u',['e','s','j'])
val.reverse
for i in val:
... |
#!/usr/bin/python
"""
@package RewardHandler
Created on Aug 6, 2016
@author: Dmitrii Dugaev
This module is responsible for a reward distribution between the nodes. It means both reception and transmission of
the generated reward values, depending on current state of RouteTable entries towards a given destination L3 ... |
import functools
def find_seat_ids(boarding_passes):
seat_ids = []
highest_seatid = 0
rules = {
'F': lambda a: a[:len(a)//2],
'B': lambda a: a[len(a)//2:],
'R': lambda a: a[len(a)//2:],
'L': lambda a: a[:len(a)//2],
}
for boarding_pass in boarding_passes:
sea... |
from dist import Dist
# Calculation of the centre of mass of two bodies
class COM:
def __init__(self, m, pos):
self.m = m
self.pos = pos
def together(self, other):
if not other:
return self
m = self.m + other.m
x = (self.pos.x * self.m + other.pos.x + oth... |
#!/bin/python3
# -*- coding: utf-8 -*-
"""
This file is part of the TangoMan PyValidator package.
(c) "Matthias Morin" <mat@tangoman.io>
This source file is subject to the MIT license that is bundled
with this source code in the file LICENSE.
"""
from unittest import TestCase
from pyvalidator.constraints.abstr... |
from django.test import TestCase
import os
import json
from editor.models import Protocol
# Create your tests here.
class GraphToPAMLTestCase(TestCase):
graph_json_file = os.path.join(os.path.dirname(__file__), "tests/resources/graph.json")
def setUp(self):
with open(self.graph_json_file, "r") as f:
... |
#!/usr/bin/env pybricks-micropython
import time
from threading import Thread
import ujson
import urequests
from pybricks.ev3devices import Motor, ColorSensor, UltrasonicSensor
from pybricks.parameters import Port, Stop, Direction
from pybricks.tools import wait
# Initialize the motors
belt_motor = Motor(Port.D, Direc... |
from .element import Element
class UnorderedList(Element):
"""Implements <ul> tag"""
def __init__(self, text=None, unstyled=False, inline=False, cl=None, ident=None, style=None, attrs=None):
super().__init__(cl=cl, ident=ident, style=style, attrs=attrs)
self.unstyled = unstyled
self.... |
import logging
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum
from typing import Any, AsyncIterator, Mapping, Optional, Union
from dateutil.parser import isoparse
from yarl import URL
from ._config import Config
from ._core import _Core
from ._rewrite import rewrite_m... |
''' __init__ '''
from basehandler import BaseHandler
from clustershandler import ClustersHandler
from containerfilehandler import ContainerFileDataHandler
from containerfilehandler import ContainerFileDownloadHandler
from containerfilehandler import ContainerFileStatsHandler
from defaulthandler import DefaultHandler
fr... |
# Credits: StackOverflow, where else....
# https://stackoverflow.com/questions/29456502/subset-sum-with-backtracking-on-python
# done with the help of generators
# might be useful to learn about them before jumping in
def sumOfSubset(array, num):
if num < 0:
return
if len(array) == 0:
if num =... |
# -*- coding:utf-8 -*-
"""
fibonacci数列的普通解法和动态规划解法。
"""
def fibonacci_normal(n):
if n == 0 or n == 1:
return n
else:
return fibonacci_normal(n - 1) + fibonacci_normal(n - 2)
tmp_result = dict()
tmp_result[0] = 0
tmp_result[1] = 1
def fibonacci_dp(n):
if n not in tmp_result:
tmp... |
import numpy as np
from skimage.metrics import peak_signal_noise_ratio as psnr, \
structural_similarity as ssim
from denoising.utils import *
from typing import List
def validate_inputs(array1: np.ndarray, array2: np.ndarray):
validate_array_input(array1)
validate_array_input(array2)
dimensions = len(... |
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QGroupBox, QButtonGroup, QWidget, QPushButton, QLabel, QVBoxLayout, QHBoxLayout, QRadioButton
from random import shuffle
from random import randint
class Question():
def __init__(self, question, right_answer, wrong1, wrong2, wrong3):
... |
import numpy as np
from ffthompy import Struct, Timer
from ffthompy.materials import Material
from ffthompy.tensorsLowRank.materials import LowRankMaterial
try:
from uq.decomposition import KL_Fourier
except:
import warnings
warnings.warn('Package StoPy (https://github.com/vondrejc/StoPy) is not available;... |
import tensorflow as tf
import numpy as np
class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __init__(self, d_model, warmup_steps=4000):
super(CustomSchedule, self).__init__()
self.d_model = d_model
self.d_model = tf.cast(self.d_model, tf.float32)
self.warmup_steps... |
from . import fft
from . import convo |
from .utils import install_extensions
USAGE = """Usage: python -m pyforest install_extensions
installs notebook/lab extensions
"""
if __name__ == "__main__":
import sys
if len(sys.argv) != 2 or sys.argv[1] != "install_extensions":
print(USAGE)
sys.exit(-1)
install_extensions()
|
# coding:utf-8
import subprocess
from PIL import Image
from PIL import ImageOps
from selenium import webdriver
import time, os, sys
def cleanImage(imagePath):
image = Image.open(imagePath) # 打开图片
image = image.point(lambda x: 0 if x < 143 else 255) # 处理图片上的每个像素点,使图片上每个点“非黑即白”
borderImage = ImageOps.expa... |
from fivpy import fivpy
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import grpc
from lndtap.lnrpc import rpc_pb2 as ln
from lndtap.lnrpc import rpc_pb2_grpc as lnrpc
class Client:
def __init__(self, lnd_node, cert, macaroon=None):
cert_creds = grpc.ssl_channel_credentials(cert)
if macaro... |
# Generated by Django 3.2.7 on 2021-09-23 19:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('home', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Team... |
#!/usr/bin/env python
# python2 or python3 compatible
import os
import sys
import yaml
import signal
import logging
import logging.config
import runner_service.configuration as configuration
from runner_service.utils import (fread,
create_self_signed_cert,
... |
#!/usr/bin/python3
import tga
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
def line(buffer, x0, y0, x1, y1, color):
steep = False
if abs(x0 - x1) < abs(y0 - y1):
x0, y0 = y0, x0
x1, y1 = y1, x1
steep = True
if x0 > x1:
x0, x1 = x1, x0
y0, y1 = y1, y0... |
from django.urls import path
from .views import OrderViewSet
urlpatterns = [path("query/", OrderViewSet.as_view())]
|
import ai2thor.controller
ai2thor.controller.Controller(
commit_id="bad5bc2b250615cb766ffb45d455c211329af17e",
download_only=True,
)
|
from spack import *
class Rapidjson(CMakePackage):
"""A fast JSON parser/generator for C++ with both SAX/DOM style API"""
homepage = "http://rapidjson.org"
url = "https://github.com/Tencent/rapidjson/archive/v1.1.0.tar.gz"
git = 'https://github.com/Tencent/rapidjson.git',
version('00db... |
import sqlite3
import numpy as np
from convlab2.policy.mdrg.multiwoz.utils.nlp import normalize
# loading databases
domains = ['restaurant', 'hotel', 'attraction', 'train', 'taxi', 'hospital']#, 'police']
dbs = {}
for domain in domains:
db = 'db/{}-dbase.db'.format(domain)
conn = sqlite3.connect(db)
c = ... |
def moeda(preco=0, moeda='R$', format=False):
return f"{moeda}{preco:.2f}".replace(".", ",")
def aumentar(preco=0, taxa=0, format=False):
resp = preco + (preco * taxa/100)
return resp if format == False else moeda(resp)
def diminuir(preco=0, taxa=0, format=False):
resp = preco - (preco * taxa/100)
... |
import argparse, time, logging
import os
# Disable Autotune
os.environ['MXNET_CUDNN_AUTOTUNE_DEFAULT'] = '0'
import numpy as np
import mxnet as mx
from mxnet import gluon
from mxnet import autograd as ag
from mxnet.gluon.model_zoo.vision import get_model
import horovod.mxnet as hvd
# CLI
def parse_args():
parse... |
from .segmenter import *
from .argument_classes import *
from .translator import * |
def fun():
i = 10 # local scope
print("i=", 10)
fun()
print(i) # this leads to error because i is local scope
|
#!/usr/bin/python
# ==============================================================================
# Author: Tao Li (taoli@ucsd.edu)
# Date: May 5, 2015
# Question: 129-Sum-Root-to-Leaf-Numbers
# Link: https://leetcode.com/problems/sum-root-to-leaf-numbers/
# ==================================================... |
from ufoLib2.objects import Anchor, Component, Glyph, Guideline, Image
def test_copyDataFromGlyph(ufo_UbuTestData):
font = ufo_UbuTestData
a = font["a"]
a.height = 500
a.image = Image("a.png")
a.note = "a note"
a.lib = {"bar": [3, 2, 1]}
a.anchors = [Anchor(250, 0, "bottom")]
a.guidel... |
#!/usr/bin/env python3
#encoding=utf-8
#------------------------------------------
# Usage: python3 9-domparse.py
# Description: method2 of parse xml file
#------------------------------------------
from xml.dom.minidom import parse, Node
xmltree = parse('9-mybooks.xml')
for node1 in xmltree.getElementsByTagNam... |
# coding: utf-8
"""
Onshape REST API
The Onshape REST API consumed by all clients. # noqa: E501
The version of the OpenAPI document: 1.113
Contact: api-support@onshape.zendesk.com
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import re # noqa: F401
im... |
from typing import Dict
from pydantic import BaseModel
class UserInDB(BaseModel):
username: str
nombre: str
apellido: str
email: str
password: str
database_users = {
"camilo24": UserInDB(**{"username": "camilo24",
"nombre": "Camilo",
"a... |
## \file
## \ingroup tutorial_tmva
## \notebook
## TMVA example, for regression
## with following objectives:
## * Apply a BDT with TMVA
##
## \macro_image
## \macro_output
## \macro_code
##
## \author Lailin XU
from ROOT import TMVA, TFile, TTree, TCut, TH1F, TCanvas, gROOT, TLegend
from subprocess import call
from... |
import RPi.GPIO as GPIO
from .wake_button import WakeButton
class RaspberryPiWakeButton(WakeButton):
def __init__(self):
super().__init__()
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(
17, GPIO.FALLING,
ca... |
import numpy as np
class Entanglement:
def __init__(self, eigvec: np.ndarray):
self._eigvec = eigvec
@staticmethod
def singular_values(v: np.ndarray, position: int = 1) -> np.ndarray:
assert not np.isnan(v).any(), "v contains nan value"
assert v.ndim == 1, "v is supposed to be an... |
"""Move
"""
LOWER = 'lower'
UPPER = 'upper'
class Move(tuple):
"""Move"""
def __new__(cls, *args, case=LOWER):
x, y = cls._get_xy(*args)
cls = super().__new__(cls, (x, y))
return cls
def __init__(self, *args, case=LOWER):
self.__x, self.__y = self[:2]
self.__str ... |
import os
import random
import string
from captcha.audio import AudioCaptcha
from captcha.image import ImageCaptcha
from django.conf import settings
from . exceptions import AudioCaptchaLangPackNotFound
from . settings import CAPTCHA_DEFAULT_LANG
def get_captcha(text=None, lang=getattr(settings,
... |
# Generated by Django 2.2.4 on 2019-08-27 15:44
from django.db import migrations
import fontawesome.fields
class Migration(migrations.Migration):
dependencies = [
('gallery', '0005_image_image_url'),
]
operations = [
migrations.AddField(
model_name='image',
name=... |
from skhep_testdata import data_path
import pyhf
from pyhf.parameters import ParamViewer
def test_paramviewer_simple_nonbatched(backend):
pars = pyhf.tensorlib.astensor([1, 2, 3, 4, 5, 6, 7])
parshape = pyhf.tensorlib.shape(pars)
view = ParamViewer(
parshape,
{'hello': {'slice': slice(0... |
#!/usr/bin/env python
# encoding: utf-8
# pylint: disable=C0111
import sys
from collection import namedtuple
"""
generate log txt file with
git log --pretty=format:"# %at %an" --name-status > log.txt
Then run this script
"""
Change = namedtuple('Change', ['mod', 'file'])
class Commit(object):
def... |
"""add previous issnl field
Revision ID: 77c5d9aaf3c8
Revises: 78407d8c375a
Create Date: 2021-09-02 09:53:18.173929
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "77c5d9aaf3c8"
down_revision = "78407d8c375a"
branch_la... |
# Double For Loop
class Solution:
def longestPalindrome(self, s: str) -> str:
def is_palindromic(input_str):
if input_str == input_str[::-1]:
return True
else:
return False
if s is None:
raise ValueError
if len(s) <= 1:
... |
import sys
import numpy as np
import pytest
from polynomials_on_simplices.geometry.mesh.point_clouds import mean, principal_component_axis
from polynomials_on_simplices.linalg.rotation import random_rotation_matrix_2, random_rotation_matrix_3
def test_principal_axis_simple_2():
points = np.array([[2.0, 0.0],
... |
import requests
import json
import os
import boto3
from boto3.dynamodb.conditions import Key
def lambda_handler(event, context):
#DB設定
dynamodb = boto3.resource('dynamodb')
TABLE = dynamodb.Table('atcoder_info')
atcoder_id = event["atcoder_id"]
#現在の情報のリクエスト
url = 'https://kenkoooo.com... |
class Discriptor:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, cls=None):
print(f"Get {self.name}")
return instance.__dict__[self.name]
def __set__(self, instance, value):
print(f"Set {self.name} to {value!r}")
instance.__dict__[... |
# Copyright 2019 The TensorFlow 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 applica... |
# try:
# from . import _version
# except:
# from SBMLDiagrams import _version
# __version__ = _version.__version__
try:
from . import visualizeSBML
from . import drawNetwork
from . import processSBML
from . import editSBML
from . import exportSBML
from . import styleSBML
from. import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.