content stringlengths 5 1.05M |
|---|
"""Integration test cases for the startlists route."""
from datetime import datetime
from json import dumps
import os
from typing import Any, Dict, List
from aiohttp import hdrs
from aiohttp.test_utils import TestClient as _TestClient
from aioresponses import aioresponses
import jwt
import pytest
from pytest_mock impo... |
'''
This script can be used to search for a number in a sorted 2D matrix.
Parameters:
- matrix: sorted 2D list
- target: number to be searched
'''
def searchMatrix(matrix, target: int) -> bool:
n, m = len(matrix), len(matrix[0])
for i in range(n): # finding the possible row
... |
# coding=utf-8
# Copyright 2021 The Edward2 Authors.
#
# 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 o... |
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2017 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... |
'''FUPQ leia um ano qualquer e mostre se ele é BISSEXTO'''
from datetime import date
ano = int(input('Digite um ano qualquer ou coloque 0 para analisar o ano atual: '))
if ano == 0:
ano = date.today().year
if ano%4 == 0 and ano%100!= 0 or ano%400 == 0:
print(f'O ano {ano} BISSEXTO')
else:
print(f'O ano {an... |
# Copyright (c) 2019-2021 - for information on the respective copyright owner
# see the NOTICE file and/or the repository
# https://github.com/boschresearch/pylife
#
# 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 co... |
import logging
import os
import shutil
import sys
import tempfile
import unittest
from unittest.mock import Mock, patch
from git import Repo
from tests.helpers.repo_utils import (
achieve_dirty_and_untracked_repo,
add_untracked,
create_clean_repo,
make_repo_dirty,
readonly_handler,
)
from torque i... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import torch.utils.model_zoo as model_zoo
class BaseConv(nn.Module):
"""A Conv2d -> Batchnorm -> silu/leaky relu block"""
def __init__(
self, in_channels, out_cha... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/Colin/Documents/hackedit/data/forms/settings_page_workspaces.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
... |
import torch
def foo(x, y):
return 2 * x + y
traced_foo = torch.jit.trace(foo, (torch.rand(3), torch.rand(3)))
torch.jit.save(traced_foo, 'jit-test.pt')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File coupling.py created on 20:47 2018/1/1
@author: Yichi Xiao
@version: 1.0
"""
import matplotlib.cm
import matplotlib.pyplot as plt
from scipy.stats import gaussian_kde
import time
import logging
from interfaces import *
from tree_search import *
from lispy import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Em on 2017/5/12
"""
分布式进程 -- 服务器端
"""
import random, multiprocessing
from multiprocessing.managers import BaseManager
from multiprocessing import freeze_support
# 从BaseManager继承的QueueManager:
class QueueManager(BaseManager):
pass
# 发送任务的队列:
task_queu... |
"""Decorator and utility functions for protecting access to endpoints."""
from connexion.exceptions import Unauthorized
from connexion import request
from flask import current_app
from functools import wraps
import logging
from typing import (Callable, List, Mapping, Union)
from jwt import (decode, get_unverified_hea... |
# -*- coding: utf-8 -*-
from os import path
from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE
from email.Utils import formatdate
from django.utils.deconstruct import deconstructible
import ... |
# coding: utf-8
import numpy as np
import math
import cv2
import os
from os import listdir
import json
import time
import sys
from MtcnnDetector import FaceDetector
#import Enhance_image
TRAINING = 0
TESTING = 1
CPU = 0
GPU = 1
CASIA = 0
REPLAYATTACK = 1
OULU = 2
def list2colmatrix(pts_list):
"""
conver... |
import base64
import hashlib
import struct
from os.path import basename
from cloudmesh.common.util import path_expand
from pathlib import Path
import requests
from cloudmesh.configuration.Config import Config
# noinspection PyBroadException
class SSHkey(dict):
def __init__(self, name=None):
self.load()
... |
import argparse
import cv2
import matplotlib.pyplot as plt
import numpy as np
from kohonen import KohonenNetwork
def mse(X, Y):
return np.mean((X.astype(np.float32) - Y.astype(np.float32)) ** 2)
def psnr(X, Y):
return 10 * np.log10(255.0 ** 2 / mse(X, Y))
def compress_image(filename,
n... |
import torch
from utils.torch_utils import BatchIter
def train_network_flexible(loss_function, parameters, data_tuple, n,
data_tuple_dev=None, max_epochs=10000,
batch_size=128, max_no_improve=20):
optim = torch.optim.Adam(parameters)
batch_iter = BatchIte... |
# -*- coding: utf-8 -*-
T = int(input())
temp = list(range(T))
for i in range(1000):
print("N[%d] = %d" % (i, temp[i % T])) |
import cv2
import os
import numpy as np
import glob
results = "/data/vpta/dataset/results/VOC2012/Main/car.txt"
source_path = "/data/vpta/dataset/VOC2012/JPEGImages-test"
dest_path = "/data/vpta/dataset/results/VOC2012/output"
def draw():
with open(results, 'r') as f:
lines = f.readlines()
for line... |
# Auto generated configuration file
# using:
# Revision: 1.19
# Source: /local/reps/CMSSW/CMSSW/Configuration/Applications/python/ConfigBuilder.py,v
# with command line options: Configuration/Generator/python/fragment_T2ttZH_mStop-600.py --filein file:test.lhe --fileout file:gensim.root --mc --eventcontent RAWSIM --... |
#!/usr/bin/python3
import numpy,hashlib,appdirs,os.path,os
from .. import helpers
import re
cacheDir = appdirs.user_cache_dir('XpyY',appauthor='Arian Sanusi')
try: os.mkdir(cacheDir)
except FileExistsError: pass
digitre=re.compile(rb'\d')
def parse(infile):
''' returns an array of the given LVMs data
caches ... |
class MyCircle(object):
def __init__(self, center=(0.0,0.0), radius=1.0, color='blue'):
self.center = center
self.radius = radius
self.color = color
def _repr_html_(self):
return "○ (<b>html</b>)"
def _repr_svg_(self):
return """<svg width="100px" height="10... |
## módulo eulerimplicito
''' método de Euler implicito para resolver el PVI
X,Y = integrate(F,x0,y0,xfinal,N).
{y}' = {F(x,{y})}, donde
{y} = {y[0],y[1],...y[N-1]}.
x0,y0 = condiciones iniciales
xfinal = valor final de la variable x
h = incremento de x usado para la integrac... |
import numpy as np
from .BaseTransformer import BaseTransformer
from .Standardizer import Standardization
import numpy as np
class SGD:
def __init__(self, variables, lr=None, decay=0.,):
self.lr = lr
self.variables = variables
self.decay = decay
def update(self, lr=None, ):
if ... |
from time import sleep
from ssd1306 import SSD1306_I2C
from machine import Pin, I2C
def send(lora):
counter = 0
print("LoRa Sender")
#display = Display()
rst = Pin(16, Pin.OUT)
rst.value(1)
scl = Pin(15, Pin.OUT, Pin.PULL_UP)
sda = Pin(4, Pin.OUT, Pin.PULL_UP)
i2c = I2C(scl=scl, sda=sd... |
"""generate random conformations from pdbbind ligands for test.
"""
import json
import argparse
import numpy as np
from tqdm import tqdm
from pathlib import Path
from rdkit import Chem
from rdkit.Chem import AllChem
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
parser = argparse.ArgumentPar... |
import rocksdb
import os
import json
from . import datalayer
class History:
def __init__(self, base_path):
self.base_path = base_path
self.db_path = os.path.join(self.base_path, "sheets-history.db")
self.db = rocksdb.DB(self.db_path, rocksdb.Options(create_if_missing=True))
def save_c... |
import os
import numpy as np
import wandb
from src.globals import archive_dir, current_dir, deskew_path, mini_path, \
network_path
from src.gui import run_gui
from src.network import NeuralNetwork
from src.train import train
from src.utils import deskew_data, load_data
def main():
if os.path.isfile(network_path):... |
from ens import ENS as _ens
from web3 import Web3
from termcolor import cprint
from nubia import command, argument
from legions.commands.commands import w3
import requests
import json
from tabulate import tabulate
from datetime import datetime
@command
class ens:
"Ethereum Name Service Tools"
def __init__(se... |
# The MIT License (MIT)
# Copyright (c) 2021 Tom J. Sun
# 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, ... |
from src.base.tile import Tile
from src.base.bbox import Bbox
from src.base.node import Node
from src.base.tag import Tag
from src.data.orthofoto.wms.wms_api import WmsApi
from src.train.coord_walker import CoordWalker
from src.train.osm_object_walker import OsmObjectWalker
import argparse
def main(args):
coord... |
# import pytest
# from Full_setup_tests_todomvc.helpers.allure.gherkin import when, given, then
# from Full_setup_tests_todomvc.helpers.pytest.skip import pending
from full_setup_tests_todomvc.model import todos
def test_add_first_todo():
todos.open()
todos.should_be_empty()
todos.add('a')
todos.sh... |
# lightManager_gui.py
import sys
import random
from PyQt5 import QtWidgets, QtCore, QtGui
from lightManager_main import readDictionnary, getDictBasedOnName
lightDictionnary = readDictionnary()
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Light Ma... |
from __future__ import print_function, division, absolute_import
import time
import matplotlib
matplotlib.use('Agg') # fix execution of tests involving matplotlib on travis
import numpy as np
import six.moves as sm
from imgaug import augmenters as iaa
from imgaug import parameters as iap
from imgaug.testutils impor... |
from __future__ import absolute_import
from exception_wrappers.database.apsw.base import APSWBaseWrapper
from exception_wrappers.database.apsw.raw import APSWConnectionWrapper
from exception_wrappers.libraries.playhouse import apsw_ext
from exception_wrappers.manager import ExceptionSource
from peewee import _sqlite_... |
from enum import Enum
from typing import Optional, Any
from FlaUILibrary.flaui.exception import FlaUiError
from FlaUILibrary.flaui.interface import (ModuleInterface, ValueContainer)
from FlaUILibrary.flaui.util.treeitems import TreeItems
from FlaUILibrary.flaui.util.converter import Converter
class Tree(ModuleInterfa... |
import json
import time
import copy
import os, sys
import datetime
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(1, os.getcwd())
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils import data
from torch.utils.tensorboard import SummaryWri... |
"""
This module include the cost sensitive decision tree method.
"""
# Authors: Alejandro Correa Bahnsen <al.bahnsen@gmail.com>
# License: BSD 3 clause
import numpy as np
import copy
from ..metrics import cost_loss
from sklearn.base import BaseEstimator
from sklearn.externals import six
import numbers
class CostSens... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import multiprocessing
import os.path as osp
import gym,sys
from collections import defaultdict
import tensorflow as tf
import numpy as np
import pickle
from baselines.common.vec_env import VecFrameStack,VecEnv, VecNormalize
from baselines.run import parse_cmdline_kwargs, build_env, configure_logger, get_default_networ... |
import sys
import os
import unittest
import shutil
from io import StringIO
sys.path.append(".")
from mock_gff3 import Create_generator
from mock_helper import gen_file
import annogesiclib.plot_coverage_table as pct
class Mock_func(object):
def mock_fig(self, rowlabels, collabels, cells, filename,
... |
""" CISCO_IP_LOCAL_POOL_MIB
This MIB defines the configuration and monitoring capabilities
relating to local IP pools.
Local IP pools have the following characteristics\:
\- An IP local pool consists of one or more IP address ranges.
\- An IP pool group consists of one or more IP local pools.
\- An IP local pool ... |
#!/usr/bin/env python3
import pytest
from tidyexc.views import *
def test_data_view():
d = [{'a': 1, 'b': 2}, {'b': 3, 'c': 4}]
v = data_view(d)
assert repr(v) == "data_view([{'a': 1, 'b': 2}, {'b': 3, 'c': 4}])"
assert v == {'a': 1, 'b': 3, 'c': 4}
assert len(v) == 3
assert set(v) == {'a', '... |
# URLs for Podcasts
from django.conf import settings
from django.conf.urls.static import static
from django.urls import include, path
from rest_framework import routers
from podcasts.views.page_views import EpisodeDetail, PodcastDetail, PodcastList, HomePage
from podcasts.views.rest_api_views import PodcastViewSet
ap... |
# Copyright (C) 2018-2021, Raffaele Salmaso <raffaele@salmaso.org>
#
# 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, cop... |
# Project libraries
from . import BaseResource
from .buildpack import Buildpack
class BuildpackInstallation(BaseResource):
"""Heroku Buildpack Insallation."""
_map = {"buildpack": Buildpack}
_ints = ["ordinal"]
_pks = ["ordinal"]
def __repr__(self):
return "<buildpack-installation '{}'>"... |
TOKEN = "put your token here" |
class OrdenaLista():
def ordenaDecrescente(lista):
for i in range(1, len(lista)):
key = lista[i]
j = i-1
while j >=0 and key < lista[j] :
lista[j+1] = lista[j]
j -= 1
lista[j+1] = key
def ordenaCre... |
import matplotlib.pyplot as plt
from simple import load_training_data as simple_h
from LeNet import load_training_data as LeNet_h
def comparison_plot(simple_history, lenet_history):
"""
:param simple_history: training data (dict)
:param lenet_history: training data (dict)
:return: matplotlib-... |
"""------------------------------------------------------------------------------------------------
Program: registry.py
Security: NONE
Purpose: This module provides a simple interface to the Windows
registry. It contains a Registry class that can be used
to interact with the re... |
from lltk.imports import *
class TextNewCorpus(Text):
def text_plain(self,*x,**y):
# By default will load from file
txt=super().text_plain(*x,**y)
# Any last minute fixes here?
# txt = ...
return txt
def xml2txt(xml_txt_or_fn,*x,**y):
return default_xml2txt(xml_txt_or_fn,*x,**y)
class NewCorpus(Corpu... |
import networkx as nx
from api.models import Person, Photo
import itertools
def build_social_graph():
G = nx.Graph()
people = Person.objects.all()
person_names = [person.name for person in people]
photos = Photo.objects.all()
G.add_nodes_from(person_names)
name_sets = []
for photo in photos:
names = []
... |
import math
import re
def percentile(values, percent, key=lambda x: x):
"""
Find the percentile of a list of values.
Params:
values (list): Sorted list of values.
percent (float): A value from 0.0 to 1.0.
key (function): Optional key function to compute value from each value on li... |
l=sorted(map(int,input().split()))
a=2*l[2]-l[1]-l[0]
print((a+3)//2 if a%2 else a//2) |
#__BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance ... |
import os
import sys
from jk_hwriter import HWriter
from .HAbstractElement import HAbstractElement
from .HAttribute import HAttribute
from .HAttributeList import HAttributeList
from .HText import HText
from .HElement_HAbstractElementList import HElement, HAbstractElementList
class HToolkit_Write_Dump(object):
... |
# -*- coding: UTF-8 -*-
import base64
import os
from aliyun_encryption_sdk.cache.local import LocalDataKeyMaterialCache
from aliyun_encryption_sdk.ckm.cache import CachingCryptoKeyManager
from aliyun_encryption_sdk.client import AliyunCrypto
from aliyun_encryption_sdk.kms import AliyunConfig
from aliyun_encryption_sd... |
from flask_classful import FlaskView
from flask import render_template
class TestClass(FlaskView):
def index(self):
return "<h1>This is my index page</h1>"
def welcome(self): #/welcome
return "<h1>This is my Welcome page</h1>"
def ariwelcome(self):
return render_template('index_o... |
##########################################
## Author: Piotr Szczypta ##
## Lidar L515 distance on image ##
## Company: A4BEE ##
##########################################
import cv2 as cv
import pyrealsense2 as rs
import numpy as np
import json
# Some of the para... |
import json
import uuid
from typing import Optional
import requests
from ravendb.http.misc import ClusterTopologyResponse
from ravendb.http.raven_command import RavenCommand
from ravendb.http.server_node import ServerNode
from ravendb.http.topology import Topology
from ravendb.tools.utils import Utils
class GetData... |
from bullet import Bullet
from pixels_manager import PixelsManager
from player import Player
class Shooter:
@staticmethod
def can_spawn_bullet(direction):
if Player.get_instance().get_health() <= 1:
return False
return direction == direction.LEFT and Player.get_instance().get_curr... |
#!/usr/bin/env python3
import os
import argparse
import numpy as np
import torch
from collections import OrderedDict
from xfr import xfr_root
from xfr import inpaintgame_saliencymaps_dir
from xfr.inpainting_game.plot_inpainting_game import make_inpaintinggame_plots
from create_wbnet import create_wbnet
human_net_la... |
import os
def is_running_locally():
"""
Tells if an experiment is running on a local machine or not
:return:
"""
local = False
if "POLYAXON_NO_OP" in os.environ:
local = True
return local
def get_username():
username = os.getlogin()
return username |
#encoding=utf8
'''
Detection with SSD
In this example, we will load a SSD model and use it to detect objects.
'''
import os
import sys
import argparse
import numpy as np
import cv2
from PIL import Image, ImageDraw
# Make sure that caffe is on the python path:
caffe_root = '../../../../caffe_train/'
sys.path.insert(0, ... |
#!/usr/bin/python
import os
import time
import sys
import re
import globus_sdk
from datetime import datetime
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
import ast
import ConfigParser
from optparse import OptionParser
args=None
parser = OptionParser()
parser.add_option("--transfer-i... |
from collections import deque
from random import randint
from threading import local
def expose(func):
func.exposed = True
return func
class flattener(object):
def __init__(self, iterator):
while type(iterator) == flattener:
iterator = iterator.iterator
self.iterator = iterat... |
import tensorflow as tf
import numpy as np
test_arr = [[np.zeros(shape=(2, 2), dtype="float32"), 0], [np.ones(shape=(2, 2), dtype="float32"), 1]]
def input_gen():
for i in range(len(test_arr)):
label = test_arr[i][1]
features = test_arr[i][0]
yield label, features
dataset = tf.data.Data... |
# ----------------------------------------------------------------------
# Auth Profile Loader
# ----------------------------------------------------------------------
# Copyright (C) 2007-2016 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# NOC modu... |
"""
Write a function to compute 5/0 and use try/except
to catch the exceptions.
Hints : try/except to catch exceptions.
"""
# Solution :
def throw():
return 5 / 0
try:
throw()
except ZeroDivisionError:
print("Division by zero")
except Exception:
print("Caught an exception")
finally:
... |
from parsedatetime.pdt_locales import (
de_DE, en_AU, en_US,
es, nl_NL, pt_BR,
ru_RU, fr_FR)
from PyQt5.QtWidgets import (QMainWindow, QTextEdit,
QAction, QFileDialog, QApplication, QWidget, QLabel,
QComboBox, QHBoxLayout, QVBoxLayout, QPushButton,
QTableWidget,QTableWidgetItem, QGridLayout,... |
import sys
sys.path.append("${CMAKE_BINARY_DIR}")
import os
import pickle
import tempfile
import unittest
import math
import pyrfr.regression as reg
class TestBinaryRssRegressionForest(unittest.TestCase):
def setUp(self):
data_set_prefix = '${CMAKE_SOURCE_DIR}/test_data_sets/'
self.data = reg.default_data_con... |
# Virtualized High Performance Computing Toolkit
#
# Copyright (c) 2018-2019 VMware, Inc. All Rights Reserved.
#
# This product is licensed to you under the Apache 2.0 license (the
# "License"). You may not use this product except in compliance with the
# Apache 2.0 License. This product may include a number of subcomp... |
# -*- coding: utf-8 -*-
"""Source code for abstract observation noise.
Author: Yoshinari Motokawa <yoshinari.moto@fuji.waseda.jp>
"""
from abc import ABC, abstractmethod
from typing import List
from core.worlds.abstract_world import AbstractWorld
from omegaconf import DictConfig
class AbstractObservationNoise(ABC... |
import Item
def setter():
x = Item.weaponItem('Iron Sword',1,0,10,"Swing")
return x
|
import itertools as it
LOW = 172851
HIGH = 675869
doubles = set()
for i in range(10):
doubles.add(str(i)*2)
triples = set()
for i in range(10):
triples.add(str(i)*3)
def main():
score = 0
for i in range(LOW, HIGH +1):
flag = True
s = str(i)
s_list = list(s)
s_list_s... |
def apply_async(func, args, *, callback):
result = func(*args)
callback(result)
def print_result(result):
print('Got:', result)
def add(x, y):
return x + y
apply_async(add, (2, 3), callback=print_result)
# Got: 5
apply_async(add, ("hello", "world"), callback=print_result)
# Got: helloworld
cla... |
# Copyright 2020 Makani Technologies 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... |
import pytest
from bmipy import Bmi
class EmptyBmi(Bmi):
def __init__(self):
pass
def initialize(self, config_file):
pass
def update(self):
pass
def update_until(self, then):
pass
def finalize(self):
pass
def get_var_type(self, var_name):
p... |
# Natural Language Toolkit: Word Sense Disambiguation Algorithms
#
# Authors: Liling Tan <alvations@gmail.com>,
# Dmitrijs Milajevs <dimazest@gmail.com>
#
# Copyright (C) 2001-2015 NLTK Project
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
from nltk.corpus import wordnet
def lesk(cont... |
from ...gpstime import GPSTime
from ..utils import Enums, TestCaseFailure
from .standby import DualSatStandbyCase
from .utils import log_fc_data, log_psim_data
class DualSatFarFieldCase(DualSatStandbyCase):
def post_boot(self):
"""To put us in fair field, we need to be able to initialize each
sat... |
#!/usr/bin/env python
from methods import (
PlanToConfigurationTest,
PlanToConfigurationStraightLineTest,
PlanToConfigurationCompleteTest,
PlanToEndEffectorPoseTest,
PlanToEndEffectorOffsetTest,
)
from planning_helpers import BasePlannerTest
from prpy.planning.cbirrt import CBiRRTPlanner
from unitte... |
import MySQLdb
db_connection = MySQLdb.connect(
host="localhost",
user="tycho_dev",
passwd="dev123",
db="tycho"
)
def fatality_data():
cursor = db_connection.cursor()
cursor.execute("SELECT AVG(CountValue) FROM noncumulative_all_conditions WHERE Fatalities = 1;")
average_fatalities = curs... |
# -*- coding: utf-8 -*-
"""Tests for Predicates, mostly took from repoze.what test suite"""
##############################################################################
#
# Copyright (c) 2007, Agendaless Consulting and Contributors.
# Copyright (c) 2008, Florent Aide <florent.aide@gmail.com>.
# Copyright (c) 2008-20... |
from pathlib import Path
import shutil
import re
import nbformat as nbf
from wrap_notebook_lines import find_links
from link_fix import markdown_cells
input_nb_pattern = r'0[0123].*.ipynb'
p = Path('.')
(p / 'converted').mkdir(exist_ok=True)
input_notebooks = p.glob(input_nb_pattern)
def nuke_dir_tree(top):
s... |
from openvino.inference_engine import IENetwork, IEPlugin
from argparse import ArgumentParser
from PIL import Image, ImageDraw
import logging as log
import numpy as np
import time
import cv2
import sys
import os
def build_argparser():
parser = ArgumentParser()
parser.add_argument("-m", "--model", help="Path to an .x... |
# -*- coding: utf-8 -*-
__version__ = '0.0.0'
__author__ = 'Mike Bland'
__license__ = "CC0-1.0"
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 31 13:10:48 2018
@author: kazuki.onodera
"""
import gc, os
from tqdm import tqdm
import pandas as pd
import numpy as np
import sys
sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary')
import lgbextension as ex
import lightgbm as lgb
from... |
from io import StringIO
from django.apps import apps
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import connection
from ....account.utils import create_superuser, create_user
from ...utils.random_data import (
add_address_to_admin
)
class Co... |
from numpy import genfromtxt
import numpy as np
from time import sleep
from sklearn.datasets import make_regression as mr
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
class WML(object):
'''
Class to solve a linear regression problem using
calculating the maximum likelihood and solv... |
#----------------------------------------------------------------------------------------------------------
#
# AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX
#
# NAME: Link CornerPin
# COLOR: #5a892b
# TEXTCOLOR: #ffffff
#
#------------------------------------------------------------------------------------------... |
import numpy as np
import cv2
import staple
from sklearn.metrics import jaccard_score
import SimpleITK as sitk
from LabelFusion.wrapper import fuse_images
from skimage.filters import threshold_otsu
def to3(src, axis=2):
return np.stack((np.zeros_like(src), src.max() - src, src), axis=axis)
def get_majority_vote... |
import paramiko
import tarfile
import sys
import socket
import nmap
import os
import sys
import struct
import fcntl
import netifaces
import urllib
import shutil
from subprocess import call
# Make a list of credentials
login_list= [('this', 'one?'),
("hell0", "Adel3"),
('admin', 'admin'),
('root', '94849390')
]
#This ... |
"""The top level of the package contains functions to load and save
data, display rendered scores, and functions to estimate pitch
spelling, voice assignment, and key signature.
"""
import pkg_resources
from .io.musescore import load_via_musescore
from .io.importmusicxml import load_musicxml, musicxml_to_notearray
f... |
#!/usr/bin/env python
# coding: utf-8
#
# Get key to relevant CARD products in CREODIAS catalog
# Version 1.3 - 2020-05-14
# - Make end date inclusive
#
# Version 1.2 - 2020-04-14
# - Changed to JSON format parsing
# - added s1 selection
#
# Version 1.1 - 2020-03-24
# - Include intersection calculation
#
import reque... |
#
# テンプレート構成
#
from typing import List, Optional
from .argument import Argument
from .content import Content
class Config:
"""パッケージテンプレートの構成.
"""
def __init__(self,
name: str,
args: List[Argument],
contents: List[Content],
args_handler... |
import jwt
from flask import current_app
from datetime import datetime, date, timedelta
from marshmallow import Schema, fields, validate, validates, ValidationError
from werkzeug.security import generate_password_hash, check_password_hash
from book_library_app import db
class Author(db.Model):
__tablename__ = '... |
import json
import inspect
from datetime import datetime
import itertools
import requests
##########################################
# Utility functions
#
def _str_or_none(value: any) -> any:
"""will convert any value to string, except None stays None"""
return None if value is None else str(value)
#######... |
import compute_merw as merw
import scipy.sparse as sparse
import metrics
import dataset
def print_similarity_matrix(S):
if not sparse.issparse(S):
S = sparse.csr_matrix(S)
n, m = S.get_shape()
for row in range(n):
print('[', end='')
for col in range(m):
print('{:6.3f} '... |
# Generated by Django 3.1 on 2021-01-02 12:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('chat', '0006_message'),
]
operations = [
migrations.RemoveField(
model_name='room',
name='staff_only',
),
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.