content stringlengths 5 1.05M |
|---|
qcvardefs = {}
#.. include:: autodoc_abbr_options_c.rst
#
#.. _`apdx:psivariables_alpha`:
#
#PSI Variables by Alpha
#======================
#
#.. note:: Lowercase letters in PSI variable names represent portions of
# the variable name that vary by root number, calculation order, etc.
# See text for fuller descripti... |
import os
import subprocess
import time
class setConf():
def __init__(self):
# 数据库获取
self.raw_conf_path = '/usr/local/etc/nginx'
self.conf_dir = '/usr/local/etc/nginx/servers'
self.conf_name = ''
self.ssl_certificate = '.crt'
self.ssl_certificate_key = '.key'
d... |
from nose.tools import *
import scipy.stats
import torch
import numpy as np
from stable_nalu.dataset import SimpleFunctionRecurrentDataset
def test_batch_shape():
dataset = SimpleFunctionRecurrentDataset(
operation='add', seed=0
)
dataset_test = iter(dataset.fork(seq_length=16).dataloader(batch_... |
# Copyright (c) 2010-2020 openpyxlzip
from openpyxlzip.xml.constants import DRAWING_NS
from openpyxlzip.descriptors.serialisable import Serialisable
from openpyxlzip.descriptors import (
Typed,
Bool,
NoneSet,
Integer,
Set,
String,
Alias,
)
from openpyxlzip.descriptors.office_art import Off... |
from garden_lighting.web.web import new_group, new_device
root_display_name = "Alle"
port = 5000
token = ""
secret = ""
mcp23017_address_a = 0x20
mcp23017_address_b = 0x21
mcp23017_reset_a = 4
mcp23017_reset_b = 17
def register_devices(devices):
south = new_group("Süden", "south", devices)
west = new_grou... |
# The MIT License (MIT)
#
# Copyright (C) 2015 - Julien Desfossez <jdesfossez@efficios.com>
# 2015 - Antoine Busque <abusque@efficios.com>
#
# 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 t... |
import pytest
@pytest.mark.parametrize(
"data",
[
# Project settings
"repo_path",
"assets_path",
# Main windows settings
"width",
"height",
"title",
"full_screen",
"font_path",
],
)
def test_config_settings_attributes(data):
from ... |
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
# file to edit: dev_nb/104_new_data_API.ipynb
from fastai import *
from fastai.vision import *
class ItemList():
"A collection of i... |
import pandas as pd
import streamlit as st
from importlib.resources import path
# Adapted from
# https://stackoverflow.com/questions/29129095/save-additional-attributes-in-pandas-dataframe/29130146#29130146
def h5_store(filename, df, **kwargs):
store = pd.HDFStore(filename)
store.put('dataframe', df)
s... |
from django.db import IntegrityError
from django.shortcuts import get_object_or_404
from rest_framework import generics, status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from ..exceptions import RoleAlreadyAssignedException, RoleConstraintException
from ..model... |
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
from pants.backend.jvm.targets.java_library import JavaLibrary
from pants.build_graph.build_file_aliases import BuildFileAliases
from pants.testutil.task_test_base import TaskTe... |
from django.conf.urls import url
from django.conf.urls.static import static
from django.urls import path
from django.conf import settings
from files.views import ProvideFilesView
urlpatterns = [
path('', ProvideFilesView.as_view()),
] |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""This file contains code for use with "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function, division
import math
import sys
imp... |
# Copyright 2016 EMC Corporation
from os import getenv
from emc_vmax_smis.vmax_smis_base import VmaxSmisBase
from emc_vmax_smis.vmax_smis_masking import VmaxSmisMasking
if __name__ == '__main__':
host = getenv("ECOM_IP", default="10.108.247.22")
smis_base = VmaxSmisBase(host=host, port=5989, use_ssl=True)
... |
import json
class Link:
def __init__(self, triple: tuple, confidence: float):
assert(len(triple) == 3)
# TODO: Meh, this is not true becouse I changed literal score for numeric types, but even if it works better than before this should be considered a bug
# TODO: Check upper todo 'cos I thi... |
######## Snakemake header ########
import sys; sys.path.append("/home/cmb-panasas2/skchoudh/software_frozen/anaconda27/envs/riboraptor/lib/python3.5/site-packages"); import pickle; snakemake = pickle.loads(b'\x80\x03csnakemake.script\nSnakemake\nq\x00)\x81q\x01}q\x02(X\x06\x00\x00\x00outputq\x03csnakemake.io\nOutputFi... |
try:
from .board_tile import BoardTile
except ImportError:
from .board_tile import BoardTile
from typing import List
import random
import time
class Board:
def __init__(self, rows: int, cols: int, mines: int):
rows, cols, mines = int(rows), int(cols), int(mines)
if mines > ((rows * cols) -... |
# Rishav Nath Pati
# Pong game revisited
import turtle
import time
window_panel = turtle.Screen()
window_panel.title("PONG by Rishav")
window_panel.bgcolor("black")
window_panel.setup(width=800, height=600)
window_panel.tracer(0)
score_a = 0
score_b = 0
# Paddle A
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_... |
# Liam Kilcommons - University of Colorado, Boulder - Colorado Center for Astrodynamics Research
# May, 2016
# (C) 2016 University of Colorado AES-CCAR-SEDA (Space Environment Data Analysis) Group
import os
import glob
import textwrap
os.environ['DISTUTILS_DEBUG'] = "1"
from setuptools import setup, Extension
from s... |
"""
Given an absolute path for a file (Unix-style), simplify it. Or in other
words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current dir.
Furthermore, a double period .. moves the dir up a level.
Note that the returned canonical path must always b... |
# from pi88reader.plotter_styles import GraphStyler
from pptx_tools.position import PPTXPosition
from pptx_tools.table_style import PPTXTableStyle
def table_style_summary():
result = PPTXTableStyle()
result.position = PPTXPosition(0.44, 0.17)
result.set_width_as_fraction(0.54)
result.col_ratios = [3.95... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 13 14:28:50 2018
@author: brettwang
"""
import time
import os
def getGMTime():
t=time.gmtime()
year = str(t.tm_year)
month = str(t.tm_mon)
day = str(t.tm_mday)
hour = str(t.tm_hour)
minute = str(t.tm_min)
second = str(... |
#!/usr/bin/env python3
# coding: utf-8
import os
import sys
import subprocess
import logging
from logging import debug, info, warning, error
app_config_real = "gc-app-local.yaml"
app_config_template = "gc-app.yaml"
logging.basicConfig(level=logging.DEBUG)
def run(cmd):
debug(f"running: {cmd}")
return os.sys... |
from functools import wraps
from django.http import Http404
from corehq.apps.accounting.utils.account import (
request_has_permissions_for_enterprise_admin,
get_account_or_404,
)
def require_enterprise_admin(view_func):
@wraps(view_func)
def _inner(request, domain, *args, **kwargs):
if not h... |
from CommandBase import *
import json
from uuid import uuid4
from os import path
from sRDI import ShellcodeRDI
from MythicFileRPC import *
class AssemblyInjectArguments(TaskArguments):
def __init__(self, command_line):
super().__init__(command_line)
self.args = {
"pid": CommandParamet... |
"""
__version__ = "$Revision: 1.1 $"
__date__ = "$Date: 2003/04/22 02:32:48 $"
"""
from vb2py.PythonCardPrototype import model
#
# VB constants
True = 1
False = 0
class MAINFORM(model.Background):
"""The main form for the application"""
# CODE_GOES_HERE
if __name__ == '__main__':
app = model.vb2py.... |
from keras import backend as K
def channel_softmax_2d(alpha=1):
def _channel_softmax_2d(x):
assert K.ndim(x) in [4, 5], \
'Input tensor must have ndim 4 or 5 ({})'.format(K.ndim(x))
if alpha != 1:
x = alpha * x
e = K.exp(x - K.max(x, axis=(-3, -2), keepdims=Tru... |
try:
import sentencepiece
except ModuleNotFoundError:
import os
os.system('pip install sentencepiece')
try:
import transformers
except ModuleNotFoundError:
import os
os.system('pip install transformers')
import torch
# from torch.utils.data import Dataset, DataLoader
from transformers import M... |
from uuid import uuid4
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.dispatch.dispatcher import receiver
class User(AbstractUser):
token = models.CharField(
max_length=36, unique=True, blank=True, default=uuid4)
user_clas... |
import pycuda.gpuarray as gpuarray
import pycuda.autoinit
import numpy
from pycuda.reduction import ReductionKernel
vector_length = 400
input_vector_a = gpuarray.arange(vector_length, dtype=numpy.int)
input_vector_b = gpuarray.arange(vector_length, dtype=numpy.int)
dot_product = ReductionKernel(numpy.int,
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-03-17 23:31
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('measure_mate', '0020_auto_20160314_1209'),
]
operations = [
migrations.RemoveField(
... |
import streamlit as st
import json
import json
import pandas as pd
import sys
from matplotlib import pyplot as plt
def app():
cols = st.beta_columns(3)
with cols[1]:
st.title('Inicio')
st.image('src/dashboard_pages/imgs/logo.png')
st.header('¿Qué es esto?')
st.write('HAR-Tastic es... |
import os
from django.contrib.auth import get_user_model
from django.db import models
from datetime import datetime
import random
User=get_user_model()
class Team(models.Model):
employee = models.ForeignKey(User, on_delete=models.CASCADE)
teamname = models.CharField(max_length=50)
def __str__(self):
return '%s %... |
import data
import config
from base import nbprint
from util import iterate, ProgressIterator
from embedding.common import EmbeddingError
from tokenizer.common import join_tokens, get_tokenizer
from tokenizer.token_util import check_requirements
def tokenize(info):
if not check_requirements(info):
... |
#!/usr/bin/env python
# Dominik Gronkiewicz (c) 2017
# this source is distributed under MIT License
# gronki@camk.edu.pl
import re
from typing import Dict
def pyminiconf_dict(f):
buf = f.read() + "\n"
d = {}
# multiline strings
rp = r'([a-zA-Z0-9\_\-\:]+)(?:[ ]+|[ ]*\=[ ]*)\"([^\"]*)\"\s+'
for k... |
## Advent of Code 2018: Day 4
## https://adventofcode.com/2018/day/4
## Jesse Williams
## Answers: [Part 1]: 77941, [Part 2]: 35289
import re
import datetime
from collections import Counter
class LogDay(object):
'''
An object representing one full day of logs, or equivalently, a guard's behavior for one day.
... |
class Default:
reserved = {'DEFAULT': 'DEFAULT'}
tokens = ('DEFAULT',)
# Tokens
t_DEFAULT = r'DEFAULT'
|
"""
server moderation tools
"""
import json
import discord
from discord.ext import commands
class Mod:
def __init__(self, bot_):
self.bot = bot_
with open('config.json') as file_in:
self.config = json.load(file_in)
def is_mod(self, context):
if context.message.channel.permissions_for(context.... |
#!/usr/bin/env python
import sys
fname = sys.argv[1]
def torgb5(v):
r = (v >> 16) & 0xFF
g = (v >> 8) & 0xFF
b = (v >> 0) & 0xFF
low = ((g << 3) & 0xC0) | (b >> 2) | 1
high = (r & 0xF8) | (g >> 5)
return (high << 8) | low
with open(fname, 'r') as f:
words = [word for line in f for word in line.split() ]
d... |
import sys
from time import strftime
try:
from . import lib_util
from . import i18n
except ModuleNotFoundError:
import lib_util
import i18n
class level(object):
TRACE = 1
DEBUG = 2
INFO = 3
# 由外部代入的 log
OUTSIDE = 3.1
SILENT = 4
min_value = TRACE
max_value = SILENT
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: AlwaysLivid
@description: Perform administrative tasks remotely via Discord, without the need of port forwarding and other complicated networking stuff.
'''
if __name__ != "__main__":
# Bot Configuration
prefix = "s!"
description = "Remotely admin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
gnpy.core.utils
===============
This module contains utility functions that are used with gnpy.
'''
import json
import numpy as np
from numpy import pi, cos, sqrt, log10
from scipy import constants
def load_json(filename):
with open(filename, 'r') as f:
... |
from ..sensordata import SensorData
class GnssSensor(SensorData):
"""
Parameters
----------
altitude : float
Height regarding ground level.
latitude : float
North/South value of a point on the map.
longitude : float
West/East value of a point on the map.
... |
"""Script to animate GAN generative samples."""
import pandas as pd
import matplotlib.animation as animation
import seaborn as sns
from visualize_basic_gan import plot_axes, create_grid_spec, get_sample_columms
dpi = 300
def animate_gan_distribution():
sns.set_style("white")
run_metadata = pd.read_csv("gan... |
input()
a = list(map(int, input().split()))
a.sort()
print(' '.join(map(str, a)))
|
from __future__ import unicode_literals
import os
import unittest
from prometheus_client import CollectorRegistry, ProcessCollector
class TestProcessCollector(unittest.TestCase):
def setUp(self):
self.registry = CollectorRegistry()
self.test_proc = os.path.join(os.path.dirname(os.path.realpath(_... |
"""
Experimental network layers.
TODO: GCN
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from global_configs import MAX_PITCH_YAW_ANGLE
from utils.processing import affine_transform_sequence
class GaussianNoise(nn.Module):
def __init__(self, stddev: fl... |
# SPDX-License-Identifier: BSD-3-Clause
from collections import defaultdict
from time import localtime
from typing import ClassVar, DefaultDict, Iterable, List, Optional
from softfab.CSVPage import CSVPage
from softfab.Page import PageProcessor
from softfab.joblib import DateRangeMonitor, Job, JobDB, Task
from softfa... |
import os
import peewee
from django.core.files.temp import NamedTemporaryFile
from django.core.management import call_command
from django.test import TestCase
from django_datajsonar.models import Node, Catalog, Field, Metadata
from elasticsearch_dsl.connections import connections
from faker import Faker
from series_t... |
def pattern_thirty_seven():
'''Pattern thirty_seven
1 2 3 4 5
2 5
3 5
4 5
5
'''
num = '12345'
for i in range(1, 6):
if i == 1:
print(' '.join(num))
elif i in range(2, 5):
space = -2 * i + 9 # using -2*n + 9 for ge... |
from ..tre_elements import TREExtension, TREElement
__classification__ = "UNCLASSIFIED"
__author__ = "Thomas McCullough"
class USE00AType(TREElement):
def __init__(self, value):
super(USE00AType, self).__init__()
self.add_field('ANGLE_TO_NORTH', 's', 3, value)
self.add_field('MEAN_GSD', ... |
# -*- coding: utf-8 -*-
"""The app module, containing the app factory function."""
import logging
import sys
from flask import Flask, jsonify, render_template
from flask_wtf.csrf import CSRFError
from brewpi import commands, devices, recipes
from brewpi.extensions import celery, csrf_protect, db, ma, migrate, restx
... |
# Criar uma função que imprima variaveis 2.0
# A atividade deve ter 3 variáveis: nome, sobrenome e idade
# Nome e sobrenome tem que ser impresso na mesma linha e idade na linha de baixo |
import numpy as np
import win32gui, win32ui, win32con
class WindowCapture:
# properties
w = 0
h = 0
hwnd = None
cropped_rectangle = None
cropped_x = 0
cropped_y = 0
cropped_w = None
cropped_h = None
offset_x = 0
offset_y = 0
# constructor
def __init__(self, window... |
from django.apps import AppConfig
class StrongpocConfig(AppConfig):
name = 'strongpoc'
|
# Copyright (c) Microsoft Corporation
# Licensed under the MIT License.
# Defines common utilities for error analysis tests
import numpy as np
import pandas as pd
import shap
from lightgbm import LGBMClassifier
from pandas import read_csv
from sklearn import svm
from sklearn.compose import ColumnTransformer
from sklea... |
"""Fixes for CMCC-CM2-SR5 model."""
from ..common import ClFixHybridPressureCoord
class Cl(ClFixHybridPressureCoord):
"""Fixes for ``cl``."""
def fix_metadata(self, cubes):
"""Fix vertical hybrid sigma coordinate (incl. bounds).
Parameters
----------
cubes : iris.cube.CubeLis... |
from django.test import TestCase
from .models import *
# Create your tests here.
class ImageTestClass(TestCase):
def setUp(self):
self.image= Image(name = 'black',caption ='image of a black man')
def test_instance(self):
self.assertTrue(isinstance(self.image,Image))
def test_save_image(self... |
""" Test the Sensor class.
"""
import numpy as np
import torch
from meslas.means import ConstantMean
from meslas.covariance.spatial_covariance_functions import Matern32
from meslas.covariance.cross_covariances import UniformMixing
from meslas.covariance.heterotopic import FactorCovariance
from meslas.geometry.grid impo... |
##ELECTRONIC SHOP MANAGEMENT SYSTEM##
##DB.py##
import mysql.connector as b
c=b.connect(host='localhost',user='root',passwd='admin')
d=c.cursor()
d.execute('create database ESMS;')
d.execute('create database BILLS;')
print('Database creation successful')
|
"""Routes for user authentication."""
from datetime import datetime
from flask import redirect, Blueprint, url_for
from flask_login import current_user, login_user
from sync_calendars.models import User
from sync_calendars.extensions import db, login_manager, oauth
# Blueprint Configuration
auth_bp = Blueprint(
... |
#!/usr/bin/env python
"""
File: update_pandoc_latex_template.py
Author: Guillaume Allain
Email: guillaum.allain@gmail.com
Github: https://github.com/guillaumeallain
Description: Inject your own template into pandoc's default
"""
import argparse
from re import split, findall, MULTILINE, sub
from codecs import decode
... |
import argparse, imutils, time, cv2, sys, numpy, io, glob
from imutils.video import VideoStream
from PIL import Image
class Videofeed:
def __init__(self, name = "test"):
self.name = name
self.frame = None
def start(self):
for index in glob.glob("/dev/video?"):
self.vs ... |
#!/usr/bin/python3
import sys
from random import choice
from random import seed
import os
availiblefortunefiles = []
availiblefortunefileslistforprinting = []
d = os.path.abspath(__file__)
d= os.path.dirname(d)
def load(d):
global FortunesDir
FortunesDir = d
for i in os.listdir(d):
x = os.path... |
import os
import semantic_version
import yaml
import guild.log
import guild.user
import guild.util
class NoSuchPackageError(Exception):
def __init__(self, spec):
super(NoSuchPackageError, self).__init__(self)
self.spec = spec
class MultiplePackagesError(Exception):
def __init__(self, spec,... |
import logging
import os.path
from argparse import Namespace
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Union, Iterator, Callable, Any
import math
import warnings
import torch
from omegaconf import II, DictConfig
from torchtyping import TensorType
from speech_transl... |
from django.test import TestCase
from ..models.tag import Tag
class TagTestCase(TestCase):
def setUp(self):
"""
Create objects here...
Example:
Tag.objects.create()
"""
pass
def test_create_tag(self):
"""
Run assertions here...
Exampl... |
from django.conf import settings
from django.db import models
from django.contrib.auth.models import User
from datetime import date
#********************CyberUser********************
from django.utils import timezone
class Profile(models.Model):
genders = (
('F', 'F'),
('M', 'M'),
)
user ... |
"""Voucher and batch API method."""
from ibsng.handler.handler import Handler
class voucherAddBatch(Handler):
"""Voucher and batch method class."""
def control(self):
"""Validate inputs after setup method.
:return: None
:rtype: None
"""
self.is_valid(self.batch_dict, ... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .sublayers import SelfAttention, PointWiseFeedForward
from .utils.gpt_config import GPTconfig
class Block(nn.Module):
def __init__(self, config: GPTconfig) -> None:
super().__init__()
self.attn = SelfAttention(config)
... |
# -*- coding: utf-8 -*-
# Copyright 2019 The Matrix.org Foundation C.I.C.
#
# 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 require... |
# 面试题11:数值的整数次方
# 题目:实现函数 double Power(double base, int exponent),求 base的exponent次方。
# 不得使用库函数,同时不需要考虑大数问题。
def PowerWithUnsignedExponent(base,exp):
if exp == 0:
return 1
if exp == 1:
return base
result = PowerWithUnsignedExponent(base,exp>>1)
result *= result
i... |
import sched
import datetime, time
class PeriodicScheduler(object):
def __init__(self):
self.scheduler = sched.scheduler(time.time, time.sleep)
... |
#!/usr/bin/env python3
"""
Programmer: Chris Blanks
Last Edited: 11/3/2018
Project: Automated Self-Serving System
Purpose: This script defines the AppWindow Class, which
the Employee and Customer windows inherit from.
Note:
-The spacing of the buttons is inconsistent when the drink profile is up for either
em... |
from setuptools import setup, find_packages
from os.path import join, dirname
import Pyiiko
setup(
name='Pyiiko',
description='Library for iikoAPI',
url='https://github.com/gadzhi/pyiiko',
author='Gadzhibala Pirmagomedov',
author_email='gadzhibala@protonmail.com',
version=Pyiiko.__version__,
... |
"""
This module creates the interface to the GBIF API via a [download/doi functionality](https://www.gbif.org/data-processing).
Give a link to a GBIF darwincore archive, users can use this module to obtain lists of urls of media data
to be downloaded using the [io](gbif_dl.io) module.
"""
import pygbif
from pathlib i... |
import os
import requests
from datetime import datetime as dt, timedelta
# === Setup ===================================================================
pixela = "https://pixe.la"
version = "v1"
username = os.environ["username"]
token = os.environ["token"]
graph_id = "flossing101"
graph_name = "Flossing"
today = d... |
# program to illustrate if statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am NOT in if")
print('\n')
# program to illustrate if else statement
#!/usr/bin/python
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if block")
else:
print("i is greater than 15")
print(... |
# stdlib
from typing import Union
# third party
from google.protobuf.reflection import GeneratedProtocolMessageType
from syft_proto.execution.v1.placeholder_id_pb2 import PlaceholderId as PlaceholderIdPB
# syft relative
from ...core.common.object import Serializable
from .common import get_protobuf_id
from .common im... |
from .email import Email
class From(Email):
"""A from email address with an optional name."""
|
class DemoError(Exception):
pass
|
from distutils.core import setup
from Cython.Build import cythonize
setup(name='cythonsum app',
ext_modules=cythonize("cythonsums.pyx"))
|
from flask import Flask
from flask_caching import Cache
from flask_cors import CORS
from flask_pymongo import PyMongo
def create_app():
flask_app = Flask('app')
flask_app.config.from_object('config.Config')
return flask_app
app = create_app()
db = PyMongo(app).db
cache = Cache(app)
CORS(app)
|
import tensorflow as tf
import os, time
import random
import numpy as np
# from data_init import get_alldatapath_big, load_datas_npy, batch_datas_random, load_labelimg
from model import UNET_sr as G
import config
from data_init import Datas_nd2
from pathlib import Path
# param
STEPS = int(1e5)
def train():
data ... |
from scipy import stats
import numpy as np
# This method computes entropy for information gain
def entropy(class_y):
# Input:
# class_y : list of class labels (0's and 1's)
# Example:
# entropy([0,0,0,1,1,1,1,1,1]) = 0.92
entropy = 0
if len(class_y) == 0:
return 0
... |
import capstone
from capstone import *
from capstone.x86_const import *
import logging
import collections
import struct
from ..constructs import *
from .base_analyzer import BaseAnalyzer
class X86_Analyzer(BaseAnalyzer):
def __init__(self, executable):
super(X86_Analyzer, self).__init__(executable)
... |
# Generated by Django 3.0.5 on 2020-04-17 22:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lrapp', '0005_auto_20200417_2302'),
]
operations = [
migrations.AlterField(
model_name='comment',
name='type',
... |
import tensorflow as tf
class EfficientNet(tf.keras.Model):
def __init__(self, IMG_WIDTH, IMG_HEIGHT, n_meta_features):
super(EfficientNet, self).__init__()
# from pretrained network
self.n_meta_features = n_meta_features
self.IMG_WIDTH = IMG_WIDTH
self.IMG_HEIGHT = IM... |
"""Constants for the Monoprice Blackbird Matrix Switch component."""
DOMAIN = "blackbird"
SERVICE_SETALLZONES = "set_all_zones"
|
# -*- coding: utf-8 -*-
"""
White Shark CNN labeling script
Last updated: 7/14/2020
Author: Chris Rillahan
Dependent packages:
OpenCV version 3.4.2
FastAI version 1.0.57
iptcinfo3
tqdm
"""
# Import packages
import os, cv2, logging, re, sys
import fastai.vision as ai # CNN
# from fastai.vision import *
from iptcinf... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
import os
from setuptools import find_packages, setup
install_requires = [
'keras',
'scikit-learn'
]
VERSION = '0.0.2'
# read the contents of your README file
this_directory = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_directory, 'REA... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Super Blogger'
SITENAME = 'Super Site'
PATH = 'content'
TIMEZONE = 'Europe/Berlin'
DEFAULT_LANG = 'en'
LOCALE = 'C'
META_DESCRIPTION = '''Blog, Superman, Spiderman '''
META_KEYWORDS = ['blog']
#########################... |
"""uninews URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
#Title: PValue.py
#Author: Stephen Tanner, Samuel Payne, Natalie Castellana, Pavel Pevzner, Vineet Bafna
#Created: 2010
# Copyright 2007,2008,2009 The Regents of the University of California
# All Rights Reserved
#
# Permission to use, copy, modify and distribute any part of this
# program for e... |
import os
os.system('mcrl22lps -v scheduler.mcrl2 scheduler.lps')
os.system('lps2pbes -v -f nodeadlock.mcf scheduler.lps scheduler.nodeadlock.pbes')
os.system('pbes2bool -v scheduler.nodeadlock.pbes')
os.system('lps2pbes -v -f infinitely_often_enabled_then_infinitely_often_taken_a.mcf scheduler.lps scheduler.infinit... |
from flask import Blueprint, render_template, redirect, url_for, request
from flask_login import login_required, current_user, login_user, logout_user
from secrets import token_hex
from project.models import db, User, Post, Board
from project.forms import EnterForm
main = Blueprint('main', __name__)
@main.route('/', ... |
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional
from dacite import Config
from ..common import *
__all__ = [
"ProfileStatus",
"Profile",
]
@dataclass
class Profile(ModelBase):
@dataclass
class Achievement:
na... |
import os
from flask import request, redirect, url_for, render_template, flash, session
from controlapp import app, client
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('entries/index.html')
elif request.method == 'POST':
if re... |
import os
import random
import cv2
import torch
import torchvision
from PIL import Image
from torch.utils.data import Dataset
class PolypDataset(Dataset):
def __init__(self, image_path, mask_path, image_transforms=None, mask_transforms=None, test=False):
super(PolypDataset, self).__init__()
self.... |
"""empty message
Revision ID: 88f313fe1de5
Revises: 2e44c02f1626
Create Date: 2018-07-26 02:16:11.851221
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '88f313fe1de5'
down_revision = '2e44c02f1626'
branch_labels = None
depends_on = None
def upgrade():
# ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.