content stringlengths 5 1.05M |
|---|
'''
L-layer neural network
using built-in functions only for pre-processing
for predicting output of mnist datatset(http://yann.lecun.com/exdb/mnist/).
The dataset consists of 60,000 training
and 10,000 testing images and labels each of 28x28 pixels resolution.
'''
import numpy as np
import pandas as pd
import matplot... |
# 73. 矩阵置零
#
# 20210716
# huao
from typing import List
class Solution:
def setZeroes(self, matrix: List[List[int]]) -> None:
matrix_000 = 1
matrix_001 = 1
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
if ... |
# -*- coding: utf-8 -*-
"""
texture_style_3d.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/github/tensorflow/lucid/blob/master/notebooks/differentiable-parameterizations/style_transfer_3d.ipynb
Copyright 2018 Google LLC.
Licensed under the Apache L... |
import pandas as pd
import seaborn as sns
from matplotlib import rcParams
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
window_days = 21 * 12
ccy1 = 'JPY'
ccy2 = 'BRL'
file_path = r'/Users/gustavoamarante/Dropbox/CQF/Final Project/' # Mac
# file_path = r'/Users/gusamarante/Dropbox/CQF/Final Proje... |
#MenuTitle: Center Glyphs
# -*- coding: utf-8 -*-
__doc__="""
Center all selected glyphs inside their respective widths.
"""
import GlyphsApp
Font = Glyphs.font
selectedLayers = Font.selectedLayers
Font.disableUpdateInterface()
for thisLayer in selectedLayers:
thisGlyph = thisLayer.parent
thisGlyph.beginUndo()
ol... |
'''
UKF utility functions for parameter estimation implementations
'''
from collections import namedtuple
import numpy as np
from numpy import ma
from scipy import linalg
from ..SKLearn_utils import array2d
from ..KF_utils import _last_dims
# sigma points w/ associated weights, as a row
SP = namedtuple(
'SP',
... |
from django import forms
from django.contrib.auth.forms import UsernameField
from django.contrib.auth.models import User
class LogInForm(forms.Form):
username = forms.CharField(max_length=60)
password = forms.CharField(max_length=60)
next = forms.CharField(max_length=120, required=False)
class UserUpdat... |
#==============================================================================
# provision.py
# This is API library for Exosite's One-Platform provision interface.
#==============================================================================
##
## Tested with python 2.6
##
## Copyright (c) 2011, Exosite LLC
## All r... |
from __future__ import absolute_import
import six
from exam import fixture
from sentry.models import Monitor
from sentry.testutils import APITestCase
class OrganizationProjectsTest(APITestCase):
@fixture
def org(self):
return self.create_organization(owner=self.user, name='baz')
@fixture
d... |
from . import det
from . import dep
from . import adj
from . import meta
from .__wrapper__ import *
|
#!/usr/bin/env python3
"""
Node runner for /Classes/hands_calibrate.py
"""
import rospy
from Classes.hands_calibrate import HandCalibrate
from math import pi
def main():
Calibrator = HandCalibrate()
Calibrator.init_node(rate=100.0)
try:
while not rospy.is_shutdown():
Calibrator.update()
Calibrator.rate.... |
import copy
import math
import random
import sys
import time
from functools import partial # pip install functools
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import onnxruntime as ort
import torch
from gym import spaces
from l... |
from abc import abstractmethod
from keras.models import Model
from categorical_embedder.embedders.core.training.TrainerABC import TrainerABC
from categorical_embedder.embedders.core.aux.loss_factory import get_loss_function
# _extract_embedder_model knows the structure of the model!!
# _get_model is for filling cust... |
from typing import Dict, NamedTuple
from os import environ
DEPOSIT_CLI_VERSION = '1.2.0'
class BaseChainSetting(NamedTuple):
ETH2_NETWORK_NAME: str
GENESIS_FORK_VERSION: bytes
GNOSIS_TESTNET = 'gnosis-testnet'
GNOSIS = 'gnosis'
TEST = 'test'
# Gnosis Beacon Chain testnet setting
GnosisTestnetSetting = ... |
import time
import multiprocessing
import pytest
from flask import Flask, request, jsonify
from livy.client import LivyClient
from livy.models import Session, SessionKind, Statement, StatementKind
MOCK_SESSION_JSON = {'mock': 'session'}
MOCK_SESSION_ID = 5
MOCK_STATEMENT_JSON = {'mock': 'statement'}
MOCK_STATEMENT_... |
# Generated by Django 3.0.8 on 2020-08-01 19:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("rovers", "0006_rover_image"),
]
operations = [
migrations.AddField(
model_name="rover",
name="status",
f... |
import datetime
from datetime import date as std_date
from enum import Enum, auto
from typing import Dict, Optional
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import F
from ctrack.caf.models import CAF
from ctrack.organisations.models import Person
from ctrack.us... |
from __future__ import print_function, unicode_literals
try:
from urllib.parse import urljoin, urlparse, urlunparse
except ImportError:
from urlparse import urljoin, urlparse, urlunparse
try:
from urllib.request import urlopen, Request
from urllib.error import HTTPError
except ImportError:
from ur... |
# Copyright Claudio Mattera 2019.
# Copyright Center for Energy Informatics 2018.
# Distributed under the MIT License.
# See accompanying file License.txt, or online at
# https://opensource.org/licenses/MIT
from datetime import datetime, timezone
import pandas as pd
from pandas.util.testing import assert_series_equal... |
#coding:utf-8
def get_value(i):
if i % 4 == 0: return i
if i % 4 == 1: return 1
if i % 4 == 2: return i + 1
if i % 4 == 3: return 0
for _ in xrange(input()):
l, r = map(int, raw_input().split())
num_of_2 = r/4 - l/4 - 1
mid = 0 if num_of_2%2 == 0 else 2
lam = lambda x,y: x^y
prin... |
import os
from PIL import Image
import math
import time
time0 = time.time()
pic = Image.new('RGB',(250,250), (255,255,255))
width, height = pic.size
center = [int(width/2), int(height/2)]
x = 0
y = 0
pic.putpixel((center[0] + x, center[1] + y), (0,0,0))
size = 251
for step in range(0,size):
r... |
#! /usr/bin/env python
import os
import argparse
from pkg_resources import resource_filename, Requirement
from baracus.predict import predict_brain_age_single_subject
from baracus import models_list, __version__
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='BARACUS: Brain-Age Regression ... |
# Brute force
class Solution1:
def uniquePaths(self, m: int, n: int) -> int:
if m == 0 or n == 0:
return 0
if m == 1 or n == 1:
return 1
return self.uniquePaths(m - 1, n) + self.uniquePaths(m, n - 1)
# Reserve memorization:
class Solution2:
def uniquePaths(self,... |
import os
from time import localtime, strftime
import base_classes as bc
from tex import TeX
from base_classes import Role
from config import configuration as conf
from pathlib import Path
class Material:
# TODO: This class should perhaps inherit from the completely general
# TeX class, as this is basically ... |
"""
Хэширование сессионого идентификатора
Revision ID: daa42690de81
Revises: 71bcf0a63639
Create Date: 2021-07-17 09:08:19.502376
"""
from alembic import op
import sqlalchemy as sa
import cyberdas.utils.hash_type
# revision identifiers, used by Alembic.
revision = 'daa42690de81'
down_revision = '71bcf0a63639'
branc... |
from datetime import timedelta
import unittest
from astronomical.model.custom_types import mass, radius
from astronomical.model.mechanics import (
RotationalMechanicsService,
OrbitalMechanicsService
)
from astronomical.model.solar_system import Star
class TestRotationalMechanicsServiceClass(unittest.TestCase... |
__version__ = '0.384.0'
|
from abc import abstractmethod
class InvalidSequenceLengthException(Exception):
def __init__(self, message):
super()
self.message = message
class Synthesizer:
STOP = '_'
DNA = 'DNA'
RNA = 'RNA'
PROTEIN = 'PROTEIN'
@classmethod
def accepting(cls, synth_type, seq):
... |
from violas_client.canoser import Struct, Uint8
from violas_client.move_core_types.account_address import AccountAddress as Address
from violas_client.lbrtypes.bytecode import get_code, CodeType
class Module(Struct):
_fields = [
("code", bytes)
]
def get_code(self):
return self.code.hex()
... |
from app import create_app, make_celery
app = create_app()
celery = make_celery(app)
app.app_context().push()
# Importing the api routes. You can also use blueprint for routing in larger applications.
from app import run
if __name__ == '__main__':
# Running the application in the given port
print("Running t... |
# -*- coding: utf-8 -*-
import os
from uuid import uuid4
from django.db import models
from django.contrib.auth.models import User
from sortedm2m.fields import SortedManyToManyField
import session
def update_filename(instance, filename):
path = "papers/"
ext = filename.split('.')[-1]
format_ = "{}.{}".fo... |
import logging
from typing import Callable, NewType, Awaitable, Dict
from verity_sdk.utils import Context, unpack_message, MsgType
HandlerFunction = NewType('HandlerFunction', Callable[[str, dict], Awaitable[None]])
DefaultHandlerFunction = NewType('DefaultHandlerFunction', Callable[[dict], Awaitable[None]])
class ... |
#!/usr/bin/env python
"""extremely simple demonstration playing a soundfile
and waiting for it to finish. you'll need the pygame.mixer
module for this to work. Note how in this simple example we
don't even bother loading all of the pygame package. Just
pick the mixer for sound and time for the delay function.
Optiona... |
"""
file: teambuilder/build.py
Implements processes that relate to building a team to use in an
Arena battle
"""
import jsonschema
from jsonschema.exceptions import ValidationError
import logging
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from typing import Dict, ... |
# -*- coding: utf-8 -*-
"""
markupsafe._compat
~~~~~~~~~~~~~~~~~~
Compatibility module for different Python versions.
:copyright: (c) 2013 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import sys
PY2 = sys.version_info[0] == 2
if not PY2:
text_type = str
string_type... |
# Created by Haorui Chen
# Updated by 05/15/2020
import time
import json
import random
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By # find by name, id, ..
from selenium.webdriver.support import expected_conditions as EC
def get_p... |
from flask import g
from app.helper.response import *
def login_required(func):
"""
登录权限检查装饰器
"""
def check_auth(*args, **kwargs):
if not g.account or not g.account.get("user_id"):
return json_fail_response(2102)
return func(*args, **kwargs)
return check_auth
|
from NLPAR import *
import tkinter as tk
from tkinter import *
class NLPCS(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("GUI")
self.geometry("250x100")
self.f1=tk.Frame(self)
self.f2=tk.Frame(self)
self.f3=tk.Frame(self)
self.f1.pack()
self.f2.pack()
self.f3.pack()
self.l1=tk.La... |
'Re-estimate a unigram LM.'
import argparse
import logging
import os
import pickle
import sys
import numpy as np
import torch
import beer
log_format = "%(asctime)s %(levelname)s: %(message)s"
logging.basicConfig(level=logging.INFO, format=log_format)
def main():
parser = argparse.ArgumentParser()
parser... |
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
import numpy as np
from scipy.special import kn, k1
from scipy.integrate import quad # simps
from scipy.interpolate import UnivariateSpline
from scipy.integrate import solve_ivp
from scipy.optimize import root_scalar
from hazma.parameters import plank_mass, rho_crit, sm_entropy_density_today
import os
import warnings
... |
#!/usr/bin/env python
# Written against python 3.3.1
# Matasano Problem 48
# Bleichenbacher's PKCS 1.5 Padding Oracle (Complete)
from prob41 import generate_rsa_key
from prob33 import mypow
from prob47 import bb98_2a, bb98_2b, bb98_2c, bb98_3
# This is a continuation of challenge #47; it implements the comple... |
'''
Created on May 21, 2018
@author: helrewaidy
'''
# sub-parts of the U-Net model
import torch
import torch.nn as nn
import torch.nn.functional as F
class DoubleConv(nn.Module):
'''(conv => ReLU => BN) * 2'''
def __init__(self, in_ch, out_ch):
super(DoubleConv, self).__init__()
self.conv ... |
import pygame
from ..events import DEBUG_AI
from .agent import Agent
class AI:
def __init__(self, width, height, chamber, hero, cheats):
self.view_width = width
self.view_height = height
self.agents = []
self.chamber = chamber
self.hero = hero
self.layer = pygame.Su... |
tempo = int(input('qubatos anos tem seu carro? '))
print('carro novo' if tempo<=3 else 'carro velho')
print('--FIM--')
nome = input('qual é o seu nome? ')
if nome == 'Marina':
print('que nome lindo você tem')
print(f'Bom dia {nome}')
n1 = float(input('digite a nota 1: '))
n2 = float(input('digite a nota 2: '))
m =... |
'''
Created on March 20, 2018
@author: Alejandro Molina
'''
import numpy as np
from spn.structure.Base import Leaf
from spn.structure.StatisticalTypes import Type
class Parametric(Leaf):
def __init__(self, type, scope=None):
Leaf.__init__(self, scope=scope)
self._type = type
@property
d... |
from .keyboard import ButtonColor
from .keyboard import ButtonType
from .keyboard import Keyboard
from .keyboard import Template
|
#!/usr/bin/env python3
""" This additional file is needed to avoid circular imports, because metric.py
has dependencies on the DWE class.
"""
# 3rd
import scipy.spatial
import functools
from typing import Callable
import numpy as np
# ours
def condense_distance_matrix(matrix):
"""Convert a square-form distance... |
"""
Modules containing database models for MyBot and Message objects
"""
import random
import logging
from datetime import datetime, timedelta
from botapp import db
from helper.helper_functions import generate_secret_key
# Setup logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s -... |
import httplib
import urllib
from BeautifulSoup import BeautifulSoup
import re
class GoogleScholarSearch:
"""
@brief This class searches Google Scholar (http://scholar.google.com)
Search for articles and publications containing terms of interest.
Usage example:\n
<tt>
> from google_search import *\n
> search... |
# -*- coding: utf-8 -*-
from django.views.generic import TemplateView, ListView, DeleteView
from django.core.urlresolvers import reverse
from fm.views import AjaxCreateView, AjaxUpdateView
from .base import BaseStockMixin, BaseIngredientViewMixin, BaseStockIngredientFormMixin
class StockHomeView(BaseStockMixin, Templ... |
from unittest import TestCase
# from configfinder.pcap_parser import Overmind, FileBackend
import os
from fexm.configfinder.pcap_parser import Overmind
class TestPcapParser(TestCase):
def test_pcap_analysis(self):
h = Overmind(backend=FileBackend(outfilder="/dev/null")).analyze(file="mock_data/pcap_samp... |
#EMPTY
# pylint: disable=missing-function-docstring
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# =========================================================================== #
# Project : Drug Approval Analytics #
# Version : 0.1.0 #
# File : \src\main.py ... |
import numpy as np
import pytplot
from scipy import signal
# First pass at the power spectrum function. This is still missing several features of the IDL power spectrum routine, such as
# bin, nohanning, notperhertz, and tm_sensativity. The IDL routine is located in dpwrspc.pro.
# There is also the issue of this n... |
# encoding: utf-8
import pyxel
pyxel.init(160, 120, caption="Pong")
# **** Számold a pontokat! ****
# Legyen az app osztálynak egy-egy mezője, ami a jobb ill. bal
# játékos pontját tárolja.
# Legyen az app osztálynak egy-egy metódusa, ami a jobb ill. bal
# játékos pontszerzését kezeli le.
# Egy pont után induljon a la... |
# Generated by Django 3.1.13 on 2021-12-13 20:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0003_auto_20211208_1247'),
]
operations = [
migrations.AlterField(
model_name='project',
name='project_... |
import numpy as np
import pandas as pd
import sys
import csv
from scipy import io as sio
from scipy import stats
from sklearn import svm, preprocessing, base, datasets, feature_selection, linear_model, decomposition
from sklearn.metrics import roc_curve,auc,classification_report,f1_score,accuracy_score,roc_auc_score
fr... |
from os.path import dirname, realpath
import pandas as pd
def get_path(path):
base_path = dirname(realpath(__file__))
return '{}/{}'.format(base_path, path)
def transform_data(input_path, output_path):
df = pd.read_csv(get_path(input_path), header=[0, 1, 2], index_col=[0, 1])
df.columns.names = ['A... |
import numpy as np
import numba
from math import radians, cos, sin, asin, sqrt
def distance(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radi... |
from urllib.error import URLError
from django.contrib import messages
from django.contrib.auth import authenticate, get_user_model, login
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect, HttpResponseServerError
from django.short... |
import json
from operator import itemgetter
from itertools import tee
from typing import Optional
import jsonschema
from kwebmon_producer.json_schemas import SITES_JSON_SCHEMA
class BadSitesList(Exception):
"""
Exception for badly formatted or invalid JSON sites list.
"""
def _first_duplicate_url(site... |
print("Hello")
print("may")
|
class CancelPendingOrderError(BaseException):
html: str
def __init__(self, message: str, html: str = None):
self.html = html
super().__init__(message)
|
import json
from pathlib import Path
from itertools import repeat
from collections import OrderedDict
import pandas as pd
import os
import warnings
def check_input(text_list):
"""
检查预测的输入list
:param text_list:
:return:
"""
# 一个str的话,转list
if isinstance(text_list, str):
text_list ... |
import sys
def warning(str):
print("WARNING: ", str, file=sys.stderr)
def error(str):
print("ERROR: ", str, file=sys.stderr)
|
import re
with open('hi_full.txt', 'r') as file:
data = file.read()
data = str(data)
reg = re.findall(r'\D+', data)
new_string = ''
for word in reg:
if word and not word == ' ' and not word == '\n' and not word == '.':
new_string += word
print(new_string)
with open('new_hi.txt', 'w') as file:
fi... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# BSD 3-Clause License
#
# Copyright (c) 2020-2021, Faster Speeding
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of sour... |
#!/usr/bin/env python
#coding:utf-8
"""
对http://www.bittorrent.org/beps/bep_0005.html中DHT Queries的实现
使用链表优化了挑战-响应模式,使每一次的请求都对应唯一一个tid,可以对每一个收到的信息进行真实性检测
使用任务队列对任务的调控、以及流量的控制
通过Pipe实现web对任务的控制
NormalDHT -> 正常模式
DHTSpider -> 爬虫模式
"""
import gevent
import logging
from random import choice
from struct import unpack
from s... |
#sleeping packages
from imutils.video import VideoStream
from imutils import face_utils
import numpy as np
import imutils
import time
import dlib
import cv2
#mouth packages
from scipy.spatial import distance as dist
from imutils.video import VideoStream
from imutils import face_utils
from threading import Thread
import... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import scipy.misc
def change_array(array):
rows = len(array)
cols = len(array[0])
for i in range(0, rows):
for j in range(0, cols):
val = array[i][j]
if (val == 0):
array[i][... |
import pytest
from entrypoints import EntryPoint as _EntryPoint
from poetry.__version__ import __version__
from poetry.core.packages.package import Package
from poetry.factory import Factory
from poetry.plugins.application_plugin import ApplicationPlugin
from poetry.plugins.plugin import Plugin
from poetry.repositori... |
# Interface for a location generator
class LocationGenerator:
def generate(self, timestamp=None):
raise NotImplementedError()
|
# Site URLs
# ******************************************************************************
OAUTH_AUTH = 'https://oauth.vk.com/authorize'
REDIRECT_URI = 'https://oauth.vk.com/blank.html'
# ******************************************************************************
VK_MOBILE = 'https://m.vk.com'
VK_FEED = 'https://v... |
# -*- coding: utf-8 -*-
import collections
from yandex_music.client import Client
import vk_api
from vk_api.audio import VkAudio
from .config import Default
import json
import re
import logging
# logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s - %(name)s - %(levelname)s - %(mes... |
student = {
'firstname': 'Pranjal',
'lastname': 'Patra',
'age': 35,
'college': 'CNA',
'vaccinated': True,
'courses': ['Python', 'Java', 'C++']
}
for david in student:
print(david, student[david])
for oliver, sabina in student.items():
print(oliver, sabina)
|
import cv2
import numpy as np
import time
import imutils
print("[INFO]: Loading models...")
path = 'face_recognition/Opencv_dnn_fr/images/known/'#Path of known images to compare from
modelFile = "face_recognition/Opencv_dnn_fr/model/res10_300x300_ssd_iter_140000.caffemodel"
configFile = "face_recognition/Opencv_dnn_fr... |
from .api import Api
from .authorization import Authorization
from .json import Json
from .params import Params
|
import subprocess
import time
proc = subprocess.Popen(['ffmpeg', '-f', 'gdigrab', '-framerate', '15', '-offset_x', '0', '-offset_y', '0', '-video_size', '1920x1080', '-i', 'desktop', '-c:v', 'libx264', '-vprofile', 'baseline', '-g', '15', '-crf', '1', '-pix_fmt', 'yuv420p', '-threads', '4', 'output.mp4'])
# Start ... |
from twisted.internet import defer
from siptrackdlib.objectregistry import object_registry
from siptrackdlib import treenodes
from siptrackdlib import container
from siptrackdlib import attribute
from siptrackdlib import permission
from siptrackdlib import counter
from siptrackdlib import device
from siptrackdlib impo... |
def calculation():#mainCalculationFunction
d = ((1367-1274)+((2546-2341)/2))*12
return d
while True:
print(calculation()) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np;
a = np.array([3.0, 3.0, 2.0, 4.9, 100.2, -8.9]);
# 数值微分求标准差梯度
def gradient ():
d = 1e-5;
grad = np.zeros(a.size);
func = lambda : np.sqrt(np.sum((a - np.mean(a)) ** 2) / a.size);
# func = lambda : np.std(a, ddof = 1);
# func = lam... |
import struct
INITIAL_HEADER_FORMAT = "!3sB64s32sB"
INITIAL_HEADER_SIZE = struct.calcsize(INITIAL_HEADER_FORMAT)
PROVIDER_HEADER_FORMAT = "!BH"
PROVIDER_HEADER_SIZE = struct.calcsize(PROVIDER_HEADER_FORMAT)
MAGIC = b"AE|"
VERSION = 1
class InsufficientDataError(RuntimeError):
pass
class UnrecognizedMagicErro... |
# Copyright 2021 The Distla 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 applicable ... |
import random
from splunk import ResourceNotFound
import splunk.admin as admin
import splunk.entity as en
import core.remote_auth as auth
from dbx_logger import logger
DBPOOL_ENDPOINT = 'db_connect/dbpool'
RESOURCEPOOL_ENDPOINT = 'db_connect/resourcepool'
POOLHEALTH_ENDPOINT = 'db_connect/poolhealth'
class JobDispat... |
#!/bin/env python3
import os
import re
import sqlite3
database_name = 'autocomplete.sqlite'
try:
os.remove(database_name)
except:
pass
#create a data structure
conn = sqlite3.connect(database_name)
conn.text_factory = str
c = conn.cursor()
print(f"Creating tables")
#c.execute(f"CREATE TABLE {tablename}(curi... |
""" Module for loading PypeIt files
"""
import os
import numpy as np
from astropy import units
from astropy.time import Time
from astropy.io import fits
from astropy.table import Table
from linetools.spectra.xspectrum1d import XSpectrum1D
from linetools.spectra.utils import collate
import linetools.utils
from pype... |
# only import from cv2 what we need - need opencv > 3.4
from cv2 import imread
from cv2.dnn import readNetFromDarknet, blobFromImage, NMSBoxes
# some minor matrix stuff
from numpy import argmax, array
from numpy.random import randint
# and we'll be constructing predictions
from .prediction import Prediction, NMS
# a... |
# Copyright (c) Amber Brown, 2015
# See LICENSE for details.
"""
towncrier, a builder for your news files.
"""
from ._version import __version__
__all__ = ["__version__"]
|
from django.db import models
# Create your models here.
class ScoreData(models.Model):
name = models.CharField(max_length=255)
points = models.FloatField()
def __repr__(self):
return 'ScoreData<{0.name}:{0.points}>'.format(self)
def __str__(self):
return 'Score by {0}'.format(self.... |
from datetime import datetime
import requests
import time
import polyline
from os.path import exists
from os import environ
import json
import sys
import webbrowser
from builtins import input as askForInput
from activity_db_client import ActivityDBClient
from dotenv import load_dotenv
load_dotenv()
CLIENT_ID = enviro... |
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the BSD 3-Clause or the CeCILL-B License
# (see codraft/__init__.py for details)
"""
CodraFT unit tests
"""
from contextlib import contextmanager
from guidata.guitest import run_testlauncher
from qtpy import QtCore as QC
import codraft.config # Loading icons
... |
# Copyright 2016 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... |
class Button:
def __init__(self, str, text_size, text_color, fill_color, padding = 10, radius = 5):
self.text = str
self.text_size = text_size
self.text_color = text_color
self.fill_color = fill_color
self.padding = padding
self.radius = radius
textS... |
# Copyright (c) 2019-2021 The EDID JSON Tools authors. All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# TODO when we can say "python 3.8 required" we can use this
# from typing import Literal
# EdidVersion = Literal['1.3', '1.4']
from typing import Dict, List
EdidVersion = str
ByteList = List[int]
... |
"""Unit test for treadmill.scheduler
"""
import time
import unittest
import sys
# Disable too many lines in module warning.
#
# pylint: disable=C0302
import mock
import numpy as np
from treadmill import scheduler
from functools import reduce
_TRAITS = dict()
# Helper functions to convert user readable traits to... |
'''This problem was recently asked by Facebook:
Given an undirected graph, determine if a cycle exists in the graph.
Here is a function signature:
'''
def find_cycle(graphe):
def dfs(graph, visited):
for k, v in graph.items():
if k in visited:
print(k)
return... |
import os
from mipsplusplus import utils
from mipsplusplus import definitions
from mipsplusplus import functions
from mipsplusplus import general
from mipsplusplus import expressions
from mipsplusplus import parser
def compile(lines, comments=1, registers=['$t0', '$t1', '$t2']):
if not isinstance(lines, list): lines... |
from .ase import *
import bpy
import bmesh
import math
from mathutils import Matrix
class ASEBuilderError(Exception):
pass
class ASEBuilderOptions(object):
def __init__(self):
self.scale = 1.0
class ASEBuilder(object):
def build(self, context, options: ASEBuilderOptions):
ase = ASE()
... |
import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_Run2_2017_cff import Run2_2017
process = cms.Process("RaddamMuon",Run2_2017)
process.load("FWCore.MessageService.MessageLogger_cfi")
process.load("Configuration.StandardSequences.GeometryDB_cff")
process.load("Configuration.StandardSequences.Geometr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.