text stringlengths 3.07k 12.6k |
|---|
from django.contrib.auth import logout, login
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView
from django.http import HttpResponse, HttpResponseNotFound, Http404, HttpResponseRedirect
fro... |
import errno
import unittest
import os
from platform import python_version
import re
import shutil
import subprocess
import sys
from contextlib import contextmanager
from pkg_resources import parse_version
import pytest
sys.path = [os.path.join(os.path.dirname(os.path.realpath(__file__)),'..')]+sys.path
@contextmana... |
#!/usr/bin/python
# Copyright 2013 Google Inc. 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... |
"""Async HTTP requests to the Youtube API"""
import asyncio
import re
import requests
import urllib.parse
import youtube_dl
from typing import Any, Dict, List, Optional
from typing_extensions import Final
import uita.exceptions
import logging
log = logging.getLogger(__name__)
# API config definitions
BASE_HEADERS: ... |
from __future__ import print_function
import argparse
import os
import h5py
import numpy as np
from neuralnets.graph_autoencoder import GraphVAE
from neuralnets.utils import one_hot_array, one_hot_index, from_one_hot_array, \
decode_smiles_from_indexes, load_graph_dataset
from keras.callbacks import ModelCheckpoi... |
"""
'Border crossing analysis' coding challenge for
Insight data engeneering program.
Author: <NAME>
Email: <EMAIL>
Date: 10/28/2019
"""
import csv
import time
from math import floor
from argparse import ArgumentParser
def load_data(path="./input/Border_Crossing_Entry_Data.csv"):
"""
Read... |
import mock
import pytest
from hcloud.servers.domain import Server
from hcloud.load_balancers.domain import LoadBalancerAlgorithm, LoadBalancer, LoadBalancerTarget, LoadBalancerService, \
LoadBalancerHealthCheck
from hcloud.load_balancer_types.domain import LoadBalancerType
from hcloud.load_balancers.client i... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
__all__ = ['plot_local_direction', 'plot_variable_importance',
'plot_local_direction_histogram', 'plot_single_direction']
def label(x, color, label):
ax = plt.gca()
ax.text(0, 0.2, label, color='black', #... |
import math
from time import monotonic
from typing import Callable, Dict, Optional, Tuple
import numpy as np # type: ignore
from scipy.special import softmax # type: ignore
from board import BOARD_SQUARES, Board, Loc, PlayerColor
from player import PlayerABC
# Map from boards to (policy, value) pairs
Evaluator = C... |
from channels.auth import AuthMiddlewareStack
from channels.exceptions import StopConsumer
from channels.consumer import AsyncConsumer
from django.conf import settings as django_settings
from django.http.request import validate_host
from django.utils.functional import cached_property
from urllib.parse import urlparse
f... |
import re
import jwt
from flask import request, make_response, jsonify
from flask_mail import Message
from flask_cors import cross_origin
from .utils import validate_password, generate_token, jsonify_user, error_response, decode_user, SECRET_KEY
from app import app, mail
from app.models import User
fixed_token = '60... |
import datetime
from django.db import models
from django.contrib.auth.models import AbstractUser
from modules.base.consts import (
USER_TYPE_NORMAL,
USER_TYPE_CHOICES,
USER_CHALLENGE_STATUS_CHOICES,
USER_CHALLENGE_STATUS_UNSOLVED,
USER_BADGE_TYPE_CHOICES,
USER_BADGE_TYPE_NORMAL,
USER_REGIO... |
"""
Manage the reading and writing of local files.
"""
from typing import Iterable, Tuple, List, Dict, Optional, Any
import os
import json
from ...backend.api.data_store import (
GatewayConfigEntity,
ServiceIdConfigEntity,
TemplateEntity,
NamespaceTemplateEntity,
as_namespace_template_entity,
... |
#! /usr/bin/env python
# Abunai v2.2
# IRC translator bot
# call with python abunai.py server nick channel USER USERLANGUAGE CHANNELLANGUAGE
# do not include the # sign in the channel arg
# as is, this script won't play nicely with servers that need nickserv or sasl
# quit by entering q at the terminal
import ... |
import numpy as onp
from autograd import numpy as np
import pymbar
from pkg_resources import resource_filename
from bayes_implicit_solvent.utils import apply_per_particle_params_to_GB_force
from bayes_implicit_solvent.utils import get_gbsa_force, get_nb_force
from simtk.openmm import app
from simtk import openmm as m... |
# Encoding: UTF-8
# Copyright (c) <NAME>, University of Antwerp
# Distributed under the terms of the MIT License
import os, subprocess
from cage.cli.commands.setup import optimize, chainsetup, spheresetup
from cage.core import Cage
from fireworks import Firework, LaunchPad, PyTask, FWorker, \
Workflow, ScriptTas... |
#
# (C) Copyright 2000- NOAA.
#
# (C) Copyright 2000- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of ... |
"""
Build a sitemap.
This script builds a conglomerate site-map from a set of marXdown sites. It
is assumed that these sites are under Git version control, and that the
person/process running this script has authorization to read from them.
This script reads from a config file that contains a set of site
specificatio... |
# -*- coding: utf-8 -*-
"""
Created on 2019/10/3 上午8:50
@author: mick.yi
"""
from sqlalchemy import Column, String, Text, BigInteger, FLOAT, SMALLINT, \
DateTime, Date, PrimaryKeyConstraint, create_engine, and_
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base ... |
from __future__ import absolute_import
from datetime import datetime
import logging
from django.core.exceptions import PermissionDenied
from django.conf import settings
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
f... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted.
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANT... |
from django.core.exceptions import SuspiciousOperation
from django.forms.models import model_to_dict
from django.shortcuts import get_object_or_404, redirect
from django.views.generic import FormView
from django.utils.translation import ugettext as _
from guardian.mixins import LoginRequiredMixin
from tally_ho.apps.ta... |
import subprocess
import os
from shutil import which
from time import sleep
from shlex import quote
from .logging import clog
from .config import get_ssh_key, SSH_SERVERALIVEINTERVAL, BASH_MIN_VERSION, ver_re
from .exception import (
ShellError,
MissingDependency,
DependencyVersionError,
SSHError,
R... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author : <NAME>
# E-mail : <EMAIL>
# Description:
# Date : 14/10/2020 11:39 AM
# File Name : pre_process_sdf_obj_normals.py
import os
import multiprocessing
import subprocess
from vstsim.grasping import GraspableObject3D
from meshpy.obj_file import ObjFile
... |
import numpy as np
from sklearn.naive_bayes import MultinomialNB
from sklearn.tree import _tree, DecisionTreeClassifier
import sys
sys.path.append("../../../")
from _Dist.NeuralNetworks.c_BasicNN.NNCore import NNCore
from _Dist.NeuralNetworks.c_BasicNN.NNWrapper import NNWrapper
# Transformation Core
class Transfor... |
__copyright__ = "Copyright (C) 2019 <NAME>"
__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
in the Software without restriction, including without limitation the rights
to use, copy, modif... |
__all__ = [
"Storage",
]
from enum import IntEnum
from collections import namedtuple
from typing import List
from rangers.io import AbstractIO, Stream, Buffer
from rangers.blockpar import BlockPar
_header = namedtuple('DataBufHeader',
('alloc_table_offset',
'arrays_num... |
"""
goes and does "the work", scraping the
page and returning the two primary values.
"""
import json
import os
from random import choice
from bs4 import BeautifulSoup
from requests import get
from lib.headerparse import fromFile
get_data = lambda: json.loads(open("data.json", "r").read())
__location__ = os.path.rea... |
#!/usr/bin/env python
# Copyright Red Hat, Inc. 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 ... |
from rest_framework import generics, serializers
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from .controller.ControllerHistTurno import ControllerHistTurno
fr... |
import math
from cwbot.modules.BaseDungeonModule import BaseDungeonModule, eventDbMatch
def killPercent(n):
return int(max(0, min(99, 100*n / 500.0)))
class PldModule(BaseDungeonModule):
"""
A module that tracks the club opening in the PLD. There is some persistent
state here, because a ... |
from typing import Union
import matplotlib.pyplot as plt
import pytorch_lightning as pl
import torch
import torch.distributions as D
import torch.nn
import torch.optim
import torch.utils.data
from torch.distributions.distribution import Distribution
from torch.utils.data.dataloader import DataLoader
from .. import lo... |
from random import random
import discord
from discord import client
from discord import guild
from discord.ext import commands, tasks
from datetime import timedelta, timezone
import datetime
import json
from dotenv.main import set_key
from six import with_metaclass
from src.helper import _textFormatting, _isValid, _u... |
from datetime import datetime
from datetime import timedelta
from copy import deepcopy
import pandas as pd
class TimeBubble:
def __init__(self, lower: datetime, upper: datetime, delta=timedelta(days=1)):
if lower > upper:
raise ValueError(
'Upper {} is less then lower {}.'.fo... |
import numpy as np
from scipy.special import eval_hermite, factorial
def hermite_functions(n, x, all_n=True, move_axes=(), method="recursive"):
"""
Calculate the Hermite functions up to the nth order at position x, psi_n(x).
For details see:
https://en.wikipedia.org/wiki/Hermite_polynomials#Hermite_f... |
from collections import defaultdict
from itertools import combinations
import numpy as np
from pymatgen.core.sites import PeriodicSite
from pymatgen.analysis.graphs import StructureGraph
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer, SymmetrizedStructure
from crystal_toolkit.core.scene import Scene
from c... |
import numpy
import numpy as np
from dolo.numeric.global_solution import step_residual
def simulate(cmodel, dr, s0=None, sigma=None, n_exp=0, horizon=40, parms=None, seed=1, discard=False, stack_series=True,
solve_expectations=False, nodes=None, weights=None, use_pandas=True):
'''
:param cmodel:... |
# (c) Continuum Analytics, Inc. / http://continuum.io
# All Rights Reserved
#
# conda is distributed under the terms of the BSD 3-clause license.
# Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause.
from __future__ import absolute_import, division, print_function
from locale import getpreferredencodi... |
from time import sleep
import hashlib
from os import urandom
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
def digest(alg, bytearr):
dig = getattr(hashlib, alg)
return dig(bytearr).hexdigest()
def get_exponents(dig, w):
mask = 0
for _ in range(w):
mask = (ma... |
'''
@Xint: https://www.jianshu.com/p/f12b545c63a4
@博客园: http://www.cnblogs.com/q735613050/
实现使用 dHash 除去本地重复图片
'''
import cv2
from matplotlib import pyplot as plt
import numpy as np
import os
class XHash:
'''
感知 Hash 算法
'''
def __init__(self, image_path, hash_type):
self.image_path = image_... |
import sys
import pickle
import os
from os.path import join
from color import RED, GREEN, YELLOW, RESET
from textual_feature import decorated_features, clear_cache, tokenize_types, debug_output
from progress_bar import print_progress_bar
from io import StringIO
def parse_tess(file_name):
file_text = StringIO()
with ... |
import discord
from discord.ext import commands
from urllib.parse import quote as uriquote
from utils.paginator import Paginator
import json
import asyncio
import re
from datetime import datetime
import html2text
class Internets(commands.Cog):
def __init__(self, bot):
self.bot = bot
UDREGEX = re.compi... |
import datetime
import re
import copy
from iso8601 import iso8601
from pytz import timezone
from checks import CheckException
class SplunkSavedSearch(object):
def __init__(self, instance_config, saved_search_instance):
if "name" in saved_search_instance:
self.name = saved_search_instance['nam... |
"""
gfswind2png creates a TMS like pyramid of GFS wind data where the red and green
bands represent the u and v vector components.
Level 0 = 1 degree spatial resolution
Level 1 = 0.5 degree spatial resolution
Level 2 = 0.25 degree spatial resolution
setup: create python virtualenv with dependencies using Pipenv and th... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
from http.client import HTTPResponse
from urllib import request
from django.http import HttpResponseRedirect
from django.shortcuts import redirect, render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.messages.views import SuccessMessageMixin
from ... |
# coding=utf-8
"""
GraN-DAG
Copyright © 2019 Authors of Gradient-Based Neural DAG Learning
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
ri... |
# -*- coding: utf-8 -*-
from django.db import models
from django.template.defaultfilters import slugify
from django.core.exceptions import ValidationError
from django.utils.safestring import mark_safe
from django.utils.encoding import smart_str, force_unicode
from django.utils.translation import ugettext_lazy as _
fro... |
import plotnine as p9
from ..utilities.agg_data import agg_data
from ..utilities.utils import unname
from ..utilities.labellers import percent_labels
from ..utilities.colors import ez_colors
from ..utilities.themes import theme_ez
from .ezplot import EZPlot
from .line_plot import line_plot
from sklearn.metrics import ... |
import time
import os
import inspect
from sys import stderr
ENV_DEBUG_MODE = 'VERBOSE'
ENV_ENABLE_TIME_PREFIX = 'ENABLE_TIME_PREFIX'
ENV_LINE_INFO_TO_STDERR = 'LINE_INFO_TO_STDERR'
ENABLE_DEBUG_MODE = os.environ.get(ENV_DEBUG_MODE)
ENABLE_TIME_PREFIX = os.environ.get(ENV_ENABLE_TIME_PREFIX)
ENABLE_LINE_INFO_TO_STDERR... |
# coding=utf-8
# Copyright 2020 The Trax 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 or a... |
import click
import pandas
from time import time
import sys
import re
from histoptimizer import histoptimize, get_partitioner_dict
import histoptimizer.historical.enumerate_pandas
import histoptimizer.historical.enumerate
import histoptimizer.historical.recursive_cache
import histoptimizer.historical.recursive_verbos... |
import glob
from inceptionv3 import *
import numpy as np
import urllib
import torch
import cv2
import argparse
import time
import random
from tqdm import tqdm
from torchvision import transforms as trn
import os
from PIL import Image
from sklearn.preprocessing import StandardScaler
from torch.autograd import Variable a... |
from tkinter import Tk, RIGHT, LEFT, BOTH, X, RAISED, TOP, StringVar
from tkinter.ttk import Frame, Button, Style, Entry, Label, OptionMenu
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from sklearn.model_selection import t... |
"""
This module provides a few lightweight wrappers around probabilistic
programming primitives from Pyro.
"""
import math
from typing import Dict, List
import pandas as pd
import pyro
from pyro.contrib.autoname import name_count
import pyro.distributions as dist # type: ignore
from pyro.infer import SVI, Predictive... |
# ============================
# fractoolbox Function Library
# ============================
'''
Tools to convert between the various ways fracture geometry are described
Structural Data Format Examples
-------------------------------
The following examples all using the same fracture plane
Borehole image log an... |
import random
import sys
import os
from rdkit import Chem
from rdkit.Chem import rdChemReactions
from rdkit.Chem import AllChem
from rdkit.Chem import Recap
from rdkit.Chem.Scaffolds import MurckoScaffold
from rdkit.Chem import rdMolDescriptors
from rdkit.Chem import Descriptors
def multi_react(argv):
with open(ar... |
'''Train CIFAR10 with PyTorch.'''
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from torch.nn import TripletMarginLoss
import torchvision
import torchvision.transforms as transforms
import torch... |
import time
import matplotlib.pyplot as plt
import numpy as np
# 成本資訊
orderingCostEachTime = 2
shortageCostPerUnit = 2
materialCostPerUnit = 1000
APR = 0.073
# 其他限制
initialInventory = 80
maxOrderLimit = 100
dayToSimulate = 500
# 生成並整數化歷史資料
historicalSalesData = np.random.normal(loc=20, scale=5, size=dayToSimulate)
f... |
from .GCGregorianDate import GCGregorianDate,Today
from .GCEarthData import EARTHDATA
from .GCPancangaDate import GCGaurabdaDate
from .GCLocation import GCLocation
from .GCDayData import GCDayData,GetFirstDayOfYear
from .GCEnums import MasaId
from . import GCTithi as GCTithi
from . import GCStrings as GCStrings
from ma... |
import argparse
import datetime
import logging
import time
from tqdm import tqdm
import torch
from apex import amp
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SequentialSampler
from ssd.config import cfg
from ssd.utils.checkpoint_util import restore_training_checkpoint
from ssd.mo... |
#
# A Sample Notes App
#
# Copyright (c) 2020 by <NAME>
#
# <EMAIL>
#
from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
import os
# Root Config
root = Tk()
root.title("Perfect Notes")
root.iconbitmap("images/logo.ico")
root.state('zoomed')
# Global variables
flags = os.O_RDWR | os.... |
import rsa
import base64
import random
__all__ = ('passworldEncode', 'randomTemperature', 'getIMEI', 'USER_AGENT', 'USER_AGENT_YIBAN','getCheckData','randomTemperature')
pubkey = '''-----<KEY>
-----END PUBLIC KEY-----'''
key:rsa.PublicKey = rsa.PublicKey.load_pkcs1_openssl_pem(pubkey)
USER_AGENT:str = 'Mozilla/5.0 (... |
"""
Imports analysis data from a bnida json file into a Binary Ninja database
"""
import json
from collections import OrderedDict
from binaryninja import (OpenFileNameField, get_form_input,
BackgroundTaskThread, types, Type, SymbolType, Symbol,
Architecture)
class Ge... |
from __future__ import print_function
from __future__ import unicode_literals
import scipy.stats
import sklearn.ensemble
"""
Helpers for feature selection. Not entirely generalized from Mars Express Challenge code.
"""
import numpy
import sklearn.feature_selection
import sklearn.linear_model
def score_features_ela... |
import numpy as np
from copy import copy
from time import time
from itertools import chain, izip, repeat
from contextlib import contextmanager
# identity map, constant maps, negation
id = lambda x: x
const = lambda c: lambda *_, **k: c
true, false = const(True), const(False)
void = const(None)
not_ = lambda f: lambda ... |
# standard library imports
from functools import reduce
from numbers import Number
# package imports
import torch
from torch.distributions import constraints
from torch.distributions.transforms import SigmoidTransform
from torch.distributions.normal import Normal
from torch.distributions.transformed_distribution impor... |
# pylint: disable=C0301, R1702, R0912, R0914, W0122, W1401, W0703
"""Main entrypoint into Calligraphy that handles CLI parsing"""
from __future__ import annotations
import sys
import os
from calligraphy_scripting import parser
from calligraphy_scripting import runner
from calligraphy_scripting import transpiler
from c... |
'''
Scripts for detecting and moving leser
towards target
Created by: <NAME>
<EMAIL>
Github: https://github.com/tomash1234/
See: https://www.youtube.com/watch?v=S3CwzkT6cK4
'''
import numpy as np
import cv2
import control
import time
class Target:
def __init__(self):
self.target = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# Quotebacks extension for Python-Markdown
Use by including `QuotebacksExtension()` in the extensions list.
Converts Markdown of the form:
```markdown
> QUOTED-CONTENT
>
> -- AUTHOR, [LINKTEXT](URL)
```
to the quotebacks format.
"""
import logging
import markdow... |
'''
==========================================================================
MeshRouterMflitRTL_test.py
==========================================================================
Test cases for mesh router that supports multi-flit packet.
Author : <NAME>
Date : Feb 13, 2020
'''
import pytest
from pymtl3 import *
f... |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... |
from django.apps import apps
from django.contrib.auth import get_user_model
from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import TemplateView, FormView
from django.apps import apps
from .current_stats import get_results_and_labels
from .data_saver import DataType
fr... |
"""
This file allows you to access semantic relationships from WordNet.
Gets all meronyms from all noun synsets in WordNet.
Also has a method that filters word pairs if they are meronyms, according to WordNet.
"""
from nltk.corpus import wordnet as wn
from collections import defaultdict
import json
def get_synonyms(n... |
from configparser import ConfigParser, MissingSectionHeaderError
import logging
import codecs
from logging.handlers import RotatingFileHandler
from time import strftime, sleep
from os import stat, mkdir, rename, listdir, remove, fspath
from os.path import isfile, join, splitext, split, dirname, exists
logger = None
c... |
# -*- coding: utf-8 -*-
from ismn.meta import MetaVar, MetaData
from ismn.components import Depth
import pytest
import unittest
import numpy as np
# todo: test negative depth
class Test_MetaVar(unittest.TestCase):
def test_MetaVar(self):
var = MetaVar("myvar", 1.1, Depth(0, 1))
assert str(var) == ... |
# coding: utf-8
import logging
import matplotlib.pyplot as plt
import numpy
from astropy import constants
from astropy import units as u
from astropy.coordinates import SkyCoord, EarthLocation
from wrappers.arlexecute.simulation.configurations import create_named_configuration
from processing_library.util.coordinate... |
import os
import numpy as np
import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import glob
import parameters as pa
import matplotlib
matplotlib.use('Agg')
def load_label(csv_file):
"""
Label file is a csv file using number to mark gesture for each fr... |
from __future__ import annotations
from typing import TYPE_CHECKING
from uuid import UUID
from tortoise.exceptions import IntegrityError, NoValuesFetched
from tortoise.fields.base import RESTRICT
from tortoise.fields.data import BooleanField, CharField, IntField, JSONField, TextField
from tortoise.fields.relational i... |
#!/usr/bin/env python3
"""
Quickly fetch your WiFi password and if needed, generate a QR code
of your WiFi to allow phones to easily connect
by <NAME>
Feature List:
version 1.1.2
- Added fixes from the commit from [GoDoVoReZ:feature](https://github.com/GoDoVoReZ/wifi-password/tree/feature)
- Added support f... |
#!/usr/bin/env python
#
# -------------------------------------------------------------------------------------
#
# Copyright (c) 2016, ytirahc, www.mobiledevtrek.com
# All rights reserved. Copyright holder cannot be held liable for any damages.
#
# Distributed under the Apache License (ASL).
# http://www.apache.org... |
import inspect
from importlib import import_module
from secure_scaffold.config import get_setting
try:
_DATABASE_SETTINGS = get_setting('DATABASE_SETTINGS')
except AttributeError:
raise AttributeError('DATABASE_SETTINGS setting not defined. '
'For the database system to work the '
... |
# Copyright (c) 2017-2018 Via Technology Ltd. All Rights Reserved.
# Consult your license regarding permissions and restrictions.
"""
Fields of Eurocontrol PRU refined trajectory data and associated functions.
See: Eurocontrol PRU Trajectories Production Data Merging Report, section 2.
"""
from enum import IntEnum, u... |
import numpy as np
import torch
import torch.nn as nn
from torchvision import models
class Vgg19(torch.nn.Module):
def __init__(self, requires_grad=False):
super(Vgg19, self).__init__()
vgg_pretrained_features = models.vgg19(pretrained=True).features
self.slice1 = torch.nn.Sequential()
... |
from requests_futures.sessions import FuturesSession
import boto3
import time
import math
from boto3.dynamodb.conditions import Key
from random import randint
from uuid import uuid4
from datetime import datetime
session = FuturesSession()
dynamodb = boto3.resource('dynamodb', region_name='us-east-1')
structures_table... |
import socket
import cv2
import numpy
import face_recognition
from datetime import datetime, timedelta
import numpy as np
import platform
import pickle
import sys
import struct
import base64
from PIL import Image
Image.LOAD_TRUNCATED_IMAGES = True
from io import BytesIO
from datetime import datetime
import time
import ... |
from typing import Any, Dict, List, Union
from functools import partial
import torch
from torch import nn
from torch.optim.lr_scheduler import CosineAnnealingLR, LinearLR, SequentialLR
import pytorch_lightning as pl
from vision_toolbox.backbones import BaseBackbone
from vision_toolbox.necks import BaseNeck
from visio... |
import threading
from django import template
from django.template.base import token_kwargs
register = template.Library()
_DEFINE_TAG = "definecomponent"
_USE_TAG = "usecomponent"
_DEFINE_SLOT_TAG = "defineslot"
_USE_SLOT_TAG = "fillslot"
@register.simple_tag(takes_context=True)
def generate_id(context, prefix):
... |
# 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... |
""" The primary function of the library: eafe_assemble """
from __future__ import division
import numpy as np
import logging
import dolfin
from petsc4py import PETSc
from dolfin import (
FunctionSpace,
Mesh,
TestFunction,
TrialFunction,
as_backend_type,
assemble,
assemble_local,
cells,
... |
__author__ = 'katharine'
import gevent
import gevent.pool
import os
import tempfile
import settings
import shutil
import socket
import subprocess
import itertools
_used_displays = set()
def _find_display():
for i in itertools.count():
if i not in _used_displays:
_used_displays.add(i)
... |
import os
import datetime
from functools import partial
from nose.tools import eq_, ok_
from flask import json
import psycopg2
import psycopg2.extras
import testing.postgresql
import app
db = None
client = None
def setUp(self):
global db, client
# Create a temporary PG database and populate it with the test ... |
from .helpers import Parsers, Kube
from kubernetes.client.rest import ApiException
from kubernetes import client
from colorama import Fore, Style
from prettytable import PrettyTable
class KubeResources:
def __init__(self, kubeClient : Kube):
self.__kubeClient = kubeClient
self.__getNodeData()
... |
import tests.context
import time
import logging
import os
import pytest
import numpy as np
import ipfsapi
from core.scheduler import DMLScheduler
from core.configuration import ConfigurationManager
from core.blockchain.blockchain_gateway import BlockchainGateway
from core.communica... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Project: http://cloudedbats.org
# Copyright (c) 2018 <NAME>
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
import math
import time
import pathlib
import datetime
import numpy as np
import pandas as pd
from dsp4bats import wave_file_utils
fr... |
import numpy as np
from noge.data_types import GoalPartialObservation, GraphObservation
from .base_memory import OnlineGraphMemory, OfflineGraphMemory
class CategoricalOnlineMemory(OnlineGraphMemory):
""" Maintain a node features array that is incrementally updated (no copy) """
def __init__(self, max_nodes... |
"""
Dataset and dataloader for imsitu experiments.
This allows us to:
1) Finetune on Imsitu
2) Finetune on a zero shot setting
"""
import spacy
import torch
import os
from config import IMSITU_TRAIN_LIST, IMSITU_VAL_LIST, IMSITU_TEST_LIST, IMSITU_IMGS
from torchvision.transforms import Scale, RandomCrop, CenterCrop, ... |
"""Data generation to be used in tests"""
import json
import os
import pathlib
from typing import Any, Dict, List
import numpy as np
from scipy import sparse
from linkedin.learner.ds.feature import Feature
from linkedin.learner.ds.indexed_dataset import IndexedDataset
from linkedin.learner.ds.record import TrainingR... |
import logging
from datetime import datetime
from collections import namedtuple
import pprint
from .map import Map
from .enums import GameMode
import pyaltitude.db as database
logger = logging.getLogger(__name__)
pp = pprint.PrettyPrinter(indent=4)
class PlayerTimer(object):
def __init__(self, enter):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.