content stringlengths 5 1.05M |
|---|
from __future__ import division, absolute_import
__copyright__ = """
Copyright (C) 2017 Andreas Kloeckner
Copyright (C) 2018 Alexandru Fikl
"""
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
i... |
# from here: https://github.com/hamx0r/stocktwits
import logging as log
from requestors import ST_BASE_PARAMS, ST_BASE_URL
# Select which library to use for handling HTTP request. If running on Google App Engine, use `GAE`.
# Otherwise, use `Requests` which is based on the `requests` module.
from requestors import ... |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from gstools import SRF, Gaussian
import os
import sys
import sklearn
from sklearn.preprocessing import MinMaxScaler as MinMaxScaler
from datetime import datetime
def scale(x, max_CRU, exp):
out_range = ((0.95 * (1 - (max_CRU - 1)) * exp), (0.95 *... |
import random
from django.test import RequestFactory, TestCase
from model_bakery import baker
from social_core.backends.google import GoogleOAuth2
from social_core.storage import BaseStorage
from social_core.tests.strategy import TestStrategy
from .. import social_pipeline
class PipelineTests(TestCase):
def set... |
# Copyright (C) 2002-2007 Python Software Foundation
# Contact: email-sig@python.org
"""Email address parsing code.
Lifted directly from rfc822.py. This should eventually be rewritten.
"""
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ i... |
import datetime
import functools
import itertools
import logging
import pandas as pd
from . import config
logger = logging.getLogger('lacework_sdk.jupyter.utils')
def dataframe_decorator(function):
"""
A decorator used to convert Lacework JSON API output into a dataframe.
"""
@functools.wraps(func... |
from picamera import PiCamera
from time import sleep
camera=PiCamera()
camera.start_preview()
sleep(2)
camera.capture('/home/pi/Desktop/test.jpg')
camera.stop_preview() |
import os
import playsound
import speech_recognition as sr
from gtts import gTTS
from datetime import datetime
def speak(text, play_aloud=True):
tts = gTTS(text=text, lang='en')
filename = 'voice.mp3'
os.remove(filename) # removes file if it already exists from previous execution
tts.save(... |
from __future__ import unicode_literals, division, absolute_import
import logging
import re
from flexget import plugin
from flexget.event import event
from flexget.plugins.plugin_urlrewriting import UrlRewritingError
from flexget.utils.requests import Session, TimedLimiter
from flexget.utils.soup import get_soup
log ... |
import os
fp = open("db.sqlite3",'w')
fp.close()
print(os.popen('python manage.py migrate').read()) |
import numpy as np
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
from keras.utils.vis_utils import plot_model
from keras.models import Sequential
from keras.layers import LSTM, Dense, Embedding, RepeatVector, TimeDistri... |
"""
Trading-Technical-Indicators (tti) python library
File name: run_all_calculation_times.py
Run example code for all the trading technical indicators and return
calculation times. To be used as source for the optimization of indicators
calculation.
Use as:
python run_all_calculation_times.py
"""
im... |
###############################################################################
# EnsembleRegressor
from nimbusml import Pipeline, FileDataStream
from nimbusml.datasets import get_dataset
from nimbusml.feature_extraction.categorical import OneHotVectorizer
from nimbusml.ensemble import EnsembleRegressor
from nimbusml.e... |
"""
【2】使用selenium+浏览器 登录网易163邮箱 : https://mail.163.com/
"""
from selenium import webdriver
class WangyiSpider:
def __init__(self):
# self.options = webdriver.ChromeOptions()
# self.options.add_argument('--headless')
self.driver = webdriver.Chrome(executable_path="/Users/aiden_zcf/PycharmPr... |
from abc import ABC, abstractmethod
from typing import Dict, Tuple, Union, List
from pathlib import Path
from importlib import import_module
import ast
import logging
import discord
from movienightbot.db.controllers import ServerController
__ALL__ = ["KNOWN_ACTIONS", "unknown_default_action"]
logger = logging.getLog... |
import pkgutil, inspect, sys,os, importlib,json,enum,warnings,nbformat,re
from IPython.core.display import display, Markdown
from nbconvert.preprocessors import ExecutePreprocessor
import nbformat.sign
from pathlib import Path
from .core import *
from .nbdoc import *
__all__ = ['create_module_page', 'generate_all', 'u... |
#!/usr/bin/env python3
# coding: utf-8
# In[1]:
from pyspark.sql.functions import array, col, explode, lit, struct, regexp_replace, to_date, desc
from pyspark.sql import DataFrame, SparkSession
from pyspark.context import SparkContext
# In[2]:
from config import datalake_raw_path, datalake_staged_path, staged_countr... |
from __future__ import unicode_literals
from moto.core.responses import BaseResponse
from moto.ec2.utils import route_table_ids_from_querystring, filters_from_querystring, optional_from_querystring
class RouteTables(BaseResponse):
def associate_route_table(self):
route_table_id = self.querystring.get('Ro... |
import unittest
from flask import Flask
from flask_sieve.exceptions import ValidationException, register_error_handler
class TestErrorHandler(unittest.TestCase):
def test_error_handler(self):
app = Flask(__name__)
register_error_handler(app)
self.assertIn(ValidationException, app.error_h... |
# MIT License
#
# Copyright (c) 2020 Arkadiusz Netczuk <dev.arnet@gmail.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 the Software without restriction, including without limitation the rights
# t... |
import numpy
from utils import shared_zeros,shared_glorot_uniform
from theano import theano
import theano.tensor as T
def model(x, embedding_size, n_hidden):
# input gate
W_xi = shared_glorot_uniform(( embedding_size,n_hidden))
W_hi = shared_glorot_uniform(( n_hidden,n_hidden))
W_ci = shared_glorot_un... |
import json
class messaging(object):
def __init__(self, ws_interface):
self.ws_interface = ws_interface
# WS functions
def global_controller_msgevent(self, is_rpc, message_event_type, message_payload):
message_info = dict()
message_info['message_type'] = 'global_controller_msgeven... |
import subprocess
import time
import sys
"""
Kicks off a pipeline that schedules Turk jobs for tool 1D,
collects results in batches and collates data.
1. Read in newline separated commands and construct CSV input.
2. Create HITs for each input command using tool 1D template.
3. Continuously check for completed assign... |
# Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from yacs.config import CfgNode as CN
__C = CN()
cfg = __C
__C.META_ARC = "TCTrack_alexnet"
__C.CUDA = True
# ------... |
from age.entities import get_basket
from age.rules import (UpdateRule, RuleSequence, MODES, RuleSaveWalkers, RuleSetWalkers)
from aiida.backends.testbase import AiidaTestCase, check_if_tests_can_run
from aiida.common.exceptions import TestsNotAllowedError
from aiida.common.links import LinkType
from aiida.orm import ... |
from itertools import combinations
from tqdm import tqdm
import numpy as np
import scipy as sp
from sklearn.preprocessing import MinMaxScaler
def get_complements(x_union_y):
'''Generator function that yields pairs of equal-size disjoint subsets
of x_union_y.
x_union_y should a set type.'''
for seq in c... |
"""Filter to convert booleans to icons."""
import json
from django.template import Library
register = Library()
@register.filter(is_safe=True)
def fontawesomize(val):
"""Convert boolean to font awesome icon."""
if val:
return '<i class="fa fa-check" style="color: green"></i>'
return '<i class=... |
import sys
import os
import time
from src.model import *
from src.util import *
import numpy as np
import pandas as pd
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
label_path = "/public... |
import re
try:
from mock import mock_open
except ImportError:
from unittest.mock import mock_open
from hq.hq import main
from test.common_test_util import simulate_args_dict, wrap_html_body, capture_console_output
def test_preserve_space_flag_turns_off_space_normalization(capsys, mocker):
hquery = '`${/... |
# <pep8-80 compliant>
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# ... |
# import time
# import socket
import re
from JumpScale import j
class HostFileFactory:
def __init__(self):
self.__jslocation__ = "j.sal.hostsfile"
def get(self):
return HostFile()
class HostFile:
def __init__(self):
self.hostfilePath = "/etc/hosts"
self.logger = j.log... |
#!/usr/bin/env python
from flask import Flask, send_from_directory
import sys
app = Flask(__name__)
lang = 'en'
@app.route('/')
def show_index():
return send_from_directory(basedir,'index.html')
@app.route("/resources/<path:filename>")
def custom_static(filename):
return send_from_directory(basedir + 'resources/',... |
# Copyright 2020 DataStax, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
#!/usr/bin/env python3
import sys
def main():
h = 0
d = 0
d2 = 0
a = 0
with open(sys.argv[1], 'r') as fhan:
for line in fhan.readlines():
[move, delta] = line.split(' ')
if move == 'forward':
h += int(delta)
d2 += a * int(delta)
... |
"""This problem was asked by Microsoft.
Implement the singleton pattern with a twist. First, instead of storing one instance, store two instances.
And in every even call of getInstance(), return the first instance and in every odd call of getInstance(),
return the second instance.
"""
class Signleton():
def __ini... |
"""
Server layout:
~/services/
This contains two subfolders
/apache/
/supervisor/
which hold the configurations for these applications
for each environment (staging, demo, etc) running on the server.
Theses folders are included in the global /etc/apache2 and
... |
from setuptools import setup
setup(
name='datetime-interval',
version='0.2',
description='A representation of a duration of time',
long_description=open('README.rst').read(),
author='Kyle Marek-Spartz',
author_email='kyle.marek.spartz@gmail.com',
url='https://www.github.com/zeckalpha/dateti... |
"""
Returns a NSGP model object.
"""
import GPy
import tqdm
from _core import *
import itertools
import time
from pyDOE import *
import scipy
from scipy.stats import multivariate_normal
from scipy.stats import norm
from scipy.optimize import check_grad
__all__ = ['NSGPModel']
class NSGPModel(object):
"""
NSGP mode... |
import asyncio
from threading import Thread
from apscheduler.schedulers.blocking import BlockingScheduler
from config.configManager import *
from module.ccsun import *
from module.cqEncoder import *
from module.functions import *
scheduler = BlockingScheduler()
configManager = Config()
CQEncoder = CQEncoder()
CCSUN = ... |
from django.db import models
from moondance.meta_models import MetaModel
from operations.models import Product, UNIT_OF_MEASURES
from simple_history.models import HistoricalRecords
from django.utils import timezone
LOCATION_LIST = [
("Bondo - Garage", "Bondo - Garage"),
("Bondo - 2nd Floor", "Bondo - 2nd Floo... |
class OrderingError(Exception):
"""
Class used to define an exception when there's any kind of problem
during the ordering process. In general, used when the configuration
file has problems.
"""
def __init__(self, message):
self.message = message
|
import json
import db
import os
import random
import time
from flask import Flask, redirect, url_for, request, g
app = Flask(__name__)
upload_folder = "upload_folder"
def upload_file():
start = time.time()
if request.method == 'POST':
print(request.get_json())
files = request.files
... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 appli... |
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
import numpy as np
from config import *
import pickle
class TextTokenizer:
def __init__(self, df):
if df.empty:
return "Data Frame is Empty... |
# Generated by Django 2.2.13 on 2020-10-29 19:14
from django.db import migrations
import django.db.models.manager
class Migration(migrations.Migration):
dependencies = [
('datasets', '0001_initial'),
]
operations = [
migrations.AlterModelManagers(
name='dataset',
... |
from django.shortcuts import render_to_response, HttpResponseRedirect, render, redirect, HttpResponse
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.core.urlresolvers import reverse
from django.contrib.auth.decorato... |
# -*- coding: utf-8 -*-
from importlib import import_module
def get_class(dot_path):
# get path
dot_path = dot_path.split(".")
path = ".".join(dot_path[:-1])
# get class name
dot_path.reverse()
class_name = dot_path[0]
# return Class
module = import_module(path)
return getattr(m... |
# Programar em Python #21 - Variáveis Globais e Locais
acesso = 'Global';
def mudarAcesso():
acesso = 'Local';
print('Acesso no interior da função:', acesso);
mudarAcesso();
print('Acesso no exterior da função:', acesso); |
import numpy as np
from tqdm import tqdm
import shutil
import torch
from torch.backends import cudnn
from torch.autograd import Variable
from graphs.models.erfnet import ERF
from graphs.models.erfnet_imagenet import ERFNet
from datasets.voc2012 import VOCDataLoader
from graphs.losses.cross_entropy import CrossEntrop... |
#!/usr/bin/env python3
import os, sys, re, requests, json, shutil, traceback, logging, hashlib, math
import math
from glob import glob
from UrlUtils import UrlUtils
from subprocess import check_call, CalledProcessError
from datetime import datetime
import xml.etree.cElementTree as ET
from xml.etree.ElementTree import ... |
""" Research module.
.. note::
This module requries multiprocess package <http://multiprocess.rtfd.io/>`_.
"""
from .domain import Alias, Domain, Option, ConfigAlias
from .named_expr import E, EC, O, EP, R
from .research import Research
from .results import ResearchResults
from .experiment import Experiment, Execu... |
import sys
from tracing.graph import Graph
if len(sys.argv) != 2:
print("Please provide the path to the graph definition text file (and nothing else)")
exit(1)
path = sys.argv[1]
with open(sys.argv[1], 'r') as file:
graph_definition = file.read()
graph = Graph(graph_definition)
print(f'1. {graph.t... |
# %%
import torch
from UnarySim.stream.gen import RNG, SourceGen, BSGen
from UnarySim.stream.shuffle import Uni2Bi
from UnarySim.metric.metric import ProgError
import matplotlib.pyplot as plt
import time
# %%
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# %%
rng = "Sobol"
in_dim = 1024
bi... |
import json
import os
from pyecharts import options as opts
from pyecharts.charts import BMap, Page
from pyecharts.faker import Collector, Faker
from pyecharts.globals import BMapType
C = Collector()
BAIDU_MAP_AK = os.environ.get("BAIDU_MAP_AK", "FAKE_AK")
@C.funcs
def bmap_base() -> BMap:
c = (
BMap()
... |
#!/usr/bin/env python
from graphslam.robot import Robot
import random
import math
import matplotlib.pyplot as plt
import seaborn as sns
class World(object):
def __init__(self, world_size, num_landmarks):
self.world_size = world_size
self.num_landmarks = num_landmarks
self.distance = 20.0
... |
import os
from conans import ConanFile, CMake
class Recipe(ConanFile):
name = "example01"
settings = "os", "arch", "compiler", "build_type"
generators = "cmake", "cmake_find_package"
exports = "*"
requires = "protobuf/0.1@xbuild/scenario"
build_requires = "protobuf/0.1@xbuild/scenario"
d... |
from . import startup
flaskapp = startup() |
# Ref: https://graphics.stanford.edu/~mdfisher/cloth.html
import taichi as ti
ti.init(arch=ti.cuda)
# Air resistance
A = 0.01
massLengthA = 0.1
massLengthB = ti.sqrt(2 * massLengthA * massLengthA)
massK = 50000.0
pointMass = 0.2
widthSize,heightSize = 127, 127
faceSize = widthSize * heightSize * 2
pointSiz... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2018 by
# Sergiy Gogolenko <gogolenko@hlrs.de> HLRS
# Fabio Saracco <fabio@imt.it> IMT
# All rights reserved.
#
# Authors: Sergiy Gogolenko <gogolenko@hlrs.de>
# Fabio Saracco <fabio@imt.it>
"""
.. module:: sn4sp
... |
# Generated by Django 2.2 on 2020-01-25 13:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Contact', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='message',
name='created_at',
... |
from django.shortcuts import render
import service
from constants import beanstalkd_description, beanstalkd_enabled
# Create your views here.
def index(request):
stats = service.server_stat()
display_stats = []
for k, v in stats.items():
if k in beanstalkd_enabled:
display_stats.append(
{
'key': k,... |
from math import floor
class Crosshairs(object):
def __init__(self, ax, visible=True):
self.ax = ax
self.vl = ax.axvline(0, color='0.7', ls=':')
self.vl.set_visible(visible)
def get_xpos(self):
x = self.vl.get_xdata()[0]
x = x if self.vl.get_visible() else None
return x
def ... |
import json
from django.shortcuts import render
from django.contrib import messages
import geojson
from tethys_sdk.routing import controller
from tethys_sdk.gizmos import MapView, MVView, MVDraw, MVLayer, MVLegendClass
from .common import docs_endpoint
def get_geoserver_wms():
"""
Try to get the built in geos... |
import utils
import numpy as np
import csv
from tensorflow.keras.models import load_model
from tensorflow.keras.callbacks import LambdaCallback,EarlyStopping,ModelCheckpoint
#%% single node sensing
# hyperparameters
lr = 0.0003
drop_ratio = 0.2
sample_length = 128
max_epoch = 100
batch_size = 200
pati... |
##
import matplotlib.pyplot as plt
import numpy as np
x=np.linspace(0,5)
y=np.sin(x)
plt.plot(x,y)
plt.grid()
plt.savefig('test.pdf')
|
from numpy import hstack
from numpy.random import normal
import numpy as np
# Generate two lists of values with different scale and loc using normal distribution
X1 = np.round(normal(loc=10, scale=2.2, size=6),2)
X2 = np.round(normal(loc=70, scale=2.5, size=6),2)
X = hstack((X1, X2))
X = X.reshape((len(X), 1))... |
#! /usr/bin/python
# Filename: using_mymodule.py
# Description: This script is used to test
# the module I wrote in mymodule.py
import mymodule
mymodule.sayHello() # using . to set which module to use
print mymodule.version
### Note: if using from mymodule import *, then we could
### use every function and varible... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objs as go
# import plotly.express as px
import pandas as pd
from data_link import *
from ecg_app import EcgApp
DISPLAY_RANGE_INIT = [
[0, 100000], # 100s
... |
import os
from glob import glob
from distutils.core import setup
from site import getusersitepackages
resource_dir = getusersitepackages()
def find_packages():
def convert(x):
x = x.replace('/__init__.py', '')
x = x.replace('/', '.')
return x
raw_pkgs = glob('**/__init__.py', recurs... |
import sys
from rotor import Rotor
def main():
arguments = len(sys.argv) - 1
leftRotor = Rotor(0, 'abcdefghijklmnopqrstuvwxyz')
if (sys.argv[1] == '-e' and arguments >= 2):
rightRotor = Rotor(0, 'tlmvpcbsuofnaqdhweiyrjzxgk')
ciphertext = encode(sys.argv[2], leftRotor, rightRotor)
... |
# This GYP file stores the dependencies necessary to build Skia on the Chrome OS
# platform. The OS doesn't provide many stable libraries as part of the
# distribution so we have to build a few of them ourselves.
{
'includes': [
'../platform_tools/chromeos/gyp/dependencies.gypi',
],
}
|
# Copyright (c) 2020. JetBrains s.r.o.
# Use of this source code is governed by the MIT license that can be found in the LICENSE file.
from .im import *
__all__ = im.__all__
|
# -*- coding: utf-8 -*-
"""
Helper function for training and testing
"""
import os
import glob
import re
from datetime import datetime
import torch
def load_saved_model(saved_path, model):
"""
Load saved model if exiseted
:param saved_path: model saved path, str
:param model: model object
:ret... |
# as you can see, I am able to import directly from the `app` module, this corresponds to the `app/__init__.py` file
from app import run_app
run_app()
|
class Authentication:
def __init__(self, userid, password):
self._userid=userid
self._password=password
self._token=None
def get_token(self):
return self._token
def set_token(self, token):
self._token=token
|
from z_src.utils.voc_utils import create_loss_and_optimizer
import os
import pathlib
from z_src.utils import config as cfg
import torch
import time
from torch.autograd import Variable
import numpy as np
from z_src.utils.voc_utils import colorize_mask
import torchvision.transforms as transforms
def train_net(net, n_ep... |
from flask import Flask, render_template, redirect, url_for, session, flash, request, make_response
from flask_session import Session
from flask_wtf import FlaskForm, CSRFProtect
from wtforms import StringField, PasswordField, validators
import re
import os
import subprocess
from datetime import datetime
from . import ... |
from django.contrib.auth import authenticate, login, logout, get_user_model
import graphene
from graphql_relay import from_global_id
from graphene import relay
from graphene_django.types import DjangoObjectType
from graphene_django.filter import DjangoFilterConnectionField
import graphene_django_optimizer as gql_optim... |
import sys
import nipype
import nipype.pipeline as pe
# import the defined workflow from the func_preproc folder
import PUMI.utils.Concat as conc
import PUMI.anat_preproc.Better as bet
import PUMI.func_preproc.MotionCorrecter as mc
import PUMI.func_preproc.Compcor as cmpcor
import PUMI.func_preproc.NuissanceCorr as nui... |
import torch
import argparse
import numpy as np
import utils
from pathlib import Path
from datetime import datetime
from network import ContactsNet
from dataset import ProteinDataLoader
def run_eval(target_path, model_path, replica, out_dir, device):
config = utils.build_config(model_path, replica)
dataloader ... |
#!/usr/bin/env python3
'''
Shapeless bot for MsgRoom @ Windows96.net
Shapeless bot © Diicorp95. MIT License
Windows 96 © Mikesoft. All rights reserved, except for some parts
Open-Source Part: Configuration API
'''
import base64 # not implemented
import os.path # not implemented
global con,config_storage_demo
con={... |
import socket
import random
s = socket.socket(
family=socket.AF_INET,
type=socket.SOCK_STREAM,
proto=socket.IPPROTO_TCP,
)
s.bind(('', 8000))
s.listen()
def handle_connection(conx):
req = conx.makefile("rb")
reqline = req.readline().decode('utf8')
method, url, version = reqline.split(" ", 2)
... |
from matplotlib import pyplot as plt
from collections import OrderedDict
import json
colors = ['b', 'r', 'k', 'g', 'y', 'c', 'm']
line_style = ['--', '-.', ':', '-']
model_size = 31400
server_num = 36
underlay = 'geantdistance'
file_name = "%d-%s-%d.json.1" % (model_size, underlay, server_num)
with open(... |
from cohortextractor import (
codelist,
codelist_from_csv,
)
ethnicity_codes = codelist_from_csv(
"codelists/opensafely-ethnicity.csv",
system="ctv3",
column="Code",
category_column="Grouping_6",
)
dementia_codes = codelist_from_csv(
"codelists/opensafely-dementia-complete.csv",
syst... |
import boto3
from sys import argv
from time import time
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Music')
indices = {
'Artist': None,
'Song': 'Song-Artist-index',
'Year': 'Year-Song-index',
}
def performance(method):
def wrapped(*args, **kw):
start_time = time()
r... |
import tensorflow as tf
import tensorlayer as tl
import numpy as np
import os
from data import data
print("=======TEST.PY IMPORTED WHAT THE FUCK=======")
metadata, idx_q, idx_a = data.load_data(PATH='data/')
w2idx = metadata['w2idx'] # dict word 2 index
idx2w = metadata['idx2w'] # list index 2 word
print("Loadi... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the extraLongFactorials function below.
def extraLongFactorials(n):
f = n * fact(n-1)
print(f)
def fact(n):
if n > 1:
return n * fact(n-1)
else :
return 1
if __name__ == '__main_... |
from .dukemtmcreid_interpretation import DukeMTMC_Interpretation
from .market1501_interpretation import Market1501_Interpretation
from .duketomarket_interpretation import DukeToMarket_Interpretation
from .markettoduke_interpretation import MarketToDuke_Interpretation
# AND
from .market1501_and_interpretation import M... |
import os
import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import json
import logging
from configuration import getConfiguration
from github import getPool, parsePayload
from irc import sendMessages
from validation import validatePayload
from __init__ import __version__
def handler(event, conte... |
"""The various clients that help you send stats."""
import itertools
import socket
import time
from . import packets
from .helpers import dot_join
class StatsClient:
"""Basic stats client.
Holds some functionality, but is not recommended for direct use.
"""
def __init__(self, prefix, host=None, por... |
from test.BaseTest import BaseTest
from src.gui.Server import Server
class VideoStreamerTest(BaseTest):
def setUp(self):
self.server = Server()
#self.server.run(host="0.0.0.0", threaded=True)
def test_init(self):
self.assertIsInstance(self.server, Server, "Server should be a videost... |
from .decoding_strategy import DecodingStrategy
__all__ = [
'DecodingStrategy'
] |
MODEL_HYPERPARAMETERS = {
"num_class": 91, # number of class, denoted C in paper, must include the background class (id: 0)
"input_size": 512,
"grid_sizes": [24], # Grid number, denoted S in the paper
"backbone": "resnet50", # resnet50, mobilenet, mobilenetv2, xception
"head_style": "vanilla", # d... |
import numpy as np
from .RelVelocity import RelVelocity
from .RelEnergy import RelEnergy
from .PSDtoFlux import PSDtoFluxE
from scipy.optimize import minimize
kB = np.float64(1.38064852e-23)
e = np.float64(1.6022e-19)
def _MB_psd(E,n,T,m,CountConst=1.0):
'''
M-B dist outputting PSD
'''
#convert Energy to Joules... |
import numpy as np
import pandas as pd
def find_best_linear_combination(df1, df2, actual, metric_fn, start, end, stepsize):
"""
df1 and df2 have to be pd.Series.
actual can be a df/series. it will be used only in metric_fn:
metric_fn(actual,prediction_df)
"""
assert start >= 0
ass... |
import json
from tola_management.models import ProgramAuditLog
class GlobalConstantsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
js_globals = request.session.get('js_globals', {})
js_globals.update(self.get_js_globals())
... |
import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
# Create blanks
display = []
for _ in range(word_length):
display += "_"
# TODO-1: - Use a while loop to let the user guess again. The loop should only stop once the user has... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import logging
from typing import (
Any, Iterator, Optional, Union,
)
from databuilder.models.dashboard.dashboard_metadata import DashboardMetadata
from databuilder.models.graph_node import GraphNode
from databuilder.models.gr... |
"""PSF module
This module provides a class implementing a spatially varying PSF.
Intended usage is:
>>> unknown ***
"""
import pdb
import numpy
def shift(im, offset, **kw):
"""Wrapper for scipy.ndimage.interpolation.shift"""
from scipy.ndimage.interpolation import shift
if 'order' not in kw:
kw... |
#encoding: utf-8
from __future__ import print_function
from keras.callbacks import Callback
from keras import backend as K
import warnings
from sklearn.metrics import roc_auc_score, roc_curve, auc
import numpy as np
import os
from matplotlib import pyplot as plt
class MultiGPUCheckpoint(Callback):
"""save weights... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.