content stringlengths 5 1.05M |
|---|
"""
Slixmpp: The Slick XMPP Library
Copyright (C) 2011 Nathanael C. Fritz
This file is part of Slixmpp.
See the file LICENSE for copying permission.
"""
from slixmpp.xmlstream import ElementBase
class Bind(ElementBase):
"""
"""
name = 'bind'
namespace = 'urn:ietf:params:xml:ns:xmp... |
# -*- coding: utf-8 -*-
from numpy.random import random
from numpy.linalg import norm
from numpy import zeros
from numpy import reshape
from numpy import column_stack
from numpy import logical_not
from numpy import logical_and
from numpy import array
from numpy import pi as PI
from numpy import cos
from numpy import s... |
#!/usr/bin/env python
import argparse
import mdtraj as md
import numpy as np
import random
from LLC_Membranes.llclib import transform, file_rw, topology
import subprocess
import copy
import os, glob
import sys
import time
import tqdm
location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) #... |
# -*- coding: utf-8 -*-
"""
Created on Tue May 21 10:00:52 2019
@author: S.P. van der Linden
"""
import pygame
import numpy as np
from scipy.interpolate import interp1d
from renderbase import RenderBase
BLACK = (0, 0, 0)
PADDING = 20
THICKNESS = 3
class RenderLinePlot(RenderBase):
def __init__(self, x: np.arra... |
from setuptools import setup
setup(name='qreport',
version='0.6',
description='Simple Report',
url='https://github.com/rvettori/qreport',
author='Rafael Vettori',
author_email='rafael.vettori@gmail.com',
license='MIT',
packages=['qreport'],
install_requires=[
... |
from ..models import models
class RasterModel(models.Model):
rast = models.RasterField('A Verbose Raster Name', null=True, srid=4326, spatial_index=True, blank=True)
class Meta:
required_db_features = ['supports_raster']
def __str__(self):
return str(self.id)
|
def main():
# comment line
print("Hello World!")
|
import re
from thefuck import shells
from thefuck.utils import sudo_support
@sudo_support
def match(command, settings):
return (command.script.startswith('cd ')
and ('no such file or directory' in command.stderr.lower()
or 'cd: can\'t cd to' in command.stderr.lower()))
@sudo_support
def get_... |
# -*- coding:utf-8 -*-
__author__ = 'nathan'
import six
from abc import ABCMeta, abstractmethod
class BaseNotifier(six.with_metaclass(ABCMeta, object)):
"""Abstract base class that defines the interface that every serializer must implement."""
def notify(self):
self._notify()
@abstractmethod
... |
# Q S M L
# Token Class
# michaelpeterswa 2020
# for the format
STAR = "STAR" # *
DOLLAR = "DOLLAR" # $
COLON = "COLON" # :
EOS = "EOS" # end of stream
# for the values
COMMENT = "COMMENT"
TEXT = "TEXT"
VALUE = "VALUE"
# for the future
SLASH = "SLASH" # /
# not currently in use
L_BRACK = "L_BRACK" # <
R_BRACK... |
# -*- coding: utf-8 -*-
"""
party.py
:copyright: (c) 2015 by Fulfil.IO Inc.
:license: see LICENSE for more details.
"""
from trytond.pool import PoolMeta, Pool
from trytond.model import fields
from trytond.rpc import RPC
from trytond.exceptions import UserError
import braintree
from braintree.exceptions.b... |
"""Utilities."""
import contextlib
import os
from pathlib import Path
from typing import Iterator
def removeprefix(string: str, prefix: str) -> str:
"""Remove prefix from string, if present."""
return string[len(prefix) :] if string.startswith(prefix) else string
def removesuffix(string: str, suffix: str) -... |
#!/usr/bin/env python
# vim:set softtabstop=4 shiftwidth=4 tabstop=4 expandtab:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import chr
import sys
import os
import re
import socket
import tempfile
impo... |
from contextlib import contextmanager
import shlex
import os
import subprocess
from cookiecutter.utils import rmtree
from pytest_cookies.plugin import Cookies
@contextmanager
def inside_dir(dirpath):
"""
Execute code from inside the given directory
:param dirpath: String, path of the directory the command ... |
class DepSolverError(Exception):
def __str__(self):
return self.message
class InvalidVersion(DepSolverError):
pass
class MissingRequirementInPool(DepSolverError):
def __init__(self, requirement):
self.requested_requirement = requirement
self.message = "This pool does not have any p... |
import os
import csv
from encryption import *
from datetime import date
from prettytable import from_csv
from prettytable import PrettyTable
from bullet import Password
details = "details.csv"
inv = "inventory.csv"
warning = "warning.csv"
def view_stat(sl):
x = PrettyTable()
x.field_names = ["SL.NO"... |
# 1 - Print 10 lijnen. Op elke lijn staat er 10 keer hetzelfde nummer, namelijk het nummer van de lijn. We beginnen
# te tellen bij 0
# 0 0 0 0 0 0 0 0
for i in range(10):
for j in range(10):
print(i, end="\t")
print()
# 2 - Print 10 lijnen. Op de eerste lijn print je enkel "0", op de tweede lijn... |
class Discount:
def __init__(self):
self.total = int(input("how many packages did you buy? "))
def softwarediscount(self):
if self.total >= 100:
print("your discount is 50%")
elif self.total >= 50 or self.total <= 99:
print("your discount is 40%")
elif ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual 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 L... |
from pytorch_lightning.metrics.metric import Metric
from pytorch_lightning.metrics.classification.accuracy import Accuracy
from pytorch_lightning.metrics.regression import (
MeanSquaredError,
MeanAbsoluteError,
MeanSquaredLogError,
ExplainedVariance,
)
|
# Copyright 2021 European Centre for Medium-Range Weather Forecasts (ECMWF)
#
# 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 requi... |
'''
Create the MainWindow for the application, it contains ui and action
'''
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QVariant
#from actions import *
import qrc_app
from workSpace import *
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow... |
"""
Convenience functions that provide a much simpler interface to Emitters and Particles.
These trade away some flexibility in favor of simplicity to allow beginners to start using particle systems.
"""
import arcade
import random
from typing import Sequence
from arcade.arcade_types import Point
from arcade.particle... |
import logging
from tornado.tcpserver import TCPServer
from core.marshalling import pack_stats
from core import Supervisor
logger = logging.getLogger(__name__)
class WatcherServer(TCPServer):
def __init__(self, watchers, sources_statistics, **kwargs):
super().__init__(**kwargs)
self.watchers = ... |
from .SB_Test_runner import get_test_dict
import numpy as np
import pandas as pd
import pickle
import requests
from io import BytesIO
from zipfile import ZipFile
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects
import rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVe... |
# -*- coding:utf-8 -*-
__author__ = 'yangjian'
"""
"""
from hypernets.experiment.experiment import Experiment
from sklearn.model_selection import train_test_split
class CompeteExperiment(Experiment):
def __init__(self, hyper_model, X_train, y_train, X_test, X_eval=None, y_eval=None, eval_size=0.3,
... |
n = int(input())
for i in range(n):
e = str(input())
v = 1
for j in e:
if j in 'AaEeIiOoSs': v *= 3
else: v *= 2
print(v)
|
#
# __init__.py
#
VERSION = '1.4.2'
__commands = set( ['build', 'flags'] )
def dispatchCommand( argv ):
if len(argv) < 2 or argv[1] not in __commands:
from . import win_app_package_builder
win_app_package_builder.AppPackage().usage()
from . import win_app_package_exe_config
win_... |
from django.contrib import admin
from .models import Song
admin.site.register(Song)
# Register your models here.
|
import pyipmi
import pyipmi.interfaces
import os
import re
import datetime
import os.path
import time
import math
import numpy
import mmap
import array
import getopt
import sys
#Inmport path
sys.path.append('../src')
from aardvark_initial import *
#Inmport path
sys.path.append('../')
from os_parameters_define import... |
class Celsius0:
def __init__(self, temperature=0):
self.set_temperature(temperature)
def to_fahrenheit(self):
return self.get_temperature() * 1.8 + 32
def get_temperature(self):
return self._temperature
def set_temperature(self, value):
if value < -273.15:
... |
from particle import foodSource
class Population:
def __init__(self, pop_size, min_layer, max_layer, input_width, input_height, input_channels, conv_prob, pool_prob, fc_prob, max_conv_kernel, max_out_ch, max_fc_neurons, output_dim):
# Compute maximum number of pooling layers for any given particle
... |
from pymongo import MongoClient
from bs4 import BeautifulSoup
import requests
import json
import urllib3
urllib3.disable_warnings()
client = MongoClient('mongodb+srv://TestUser:Test1234@cluster0.dqz9b.mongodb.net/VehiclesData?retryWrites=true&w=majority')
db = client["<database>"]
collection = db["<collection>"]
Data ... |
"""
OpenCL-specific part of the module.
"""
import pyopencl as cl
import warnings
if cl.VERSION < (0, 92):
raise ImportError("PyOpenCL 0.92 or newer is required")
import sys
import numpy
from .plan import FFTPlan
from .kernel_helpers import log2
class Function:
"""Wrapper for kernel function"""
def __init__(s... |
import matplotlib.pyplot as plt
#history = {'loss': [0.0562 ,0.0482 ,0.0453 ,0.0436,0.0422 ,0.0414 ,0.0407 ,0.0401 ,0.0398,0.0394,0.0391,0.0388,0.0385 ,0.0383 ,0.0382,0.0380,0.0378,0.0377 ,0.0376,0.0374],
# 'val_loss': [0.0517,0.0494,0.0477,0.0475,0.0469,0.0467,0.0464,0.0465,0.0470,0.0459,0.0464,0.0509,0.0472,0.... |
"""
MIT License
Copyright (c) 2021 Obi-Wan3
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, merge, publish, dist... |
"""
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated,
and only the integer part of the result is returned.
"""
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""... |
# Copyright 2015 Bradley Rowe
#
# 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, ... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is govered by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Cron and task handlers for email notifications of issue date value arrival.
If an issue has ... |
from mysql.connector.errors import OperationalError, ProgrammingError
class CantCreateTableError(OperationalError):
""" Raised when a table cannot be created.
https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_cant_create_table
"""
code = 1005
class BadNullError(Operationa... |
import time
import logging
from typing import List
from spaceone.inventory.connector.aws_acm_connector.schema.data import Certificate, Tags
from spaceone.inventory.connector.aws_acm_connector.schema.resource import ACMResource, CertificateResource, ACMResponse
from spaceone.inventory.connector.aws_acm_connector.schema... |
from PyQt5.QtWidgets import QLineEdit, QDialog, QPushButton, QVBoxLayout, QLabel, QHBoxLayout, QMessageBox
from PyQt5.QtGui import QIcon
from Crypto.PublicKey import RSA
from ...algos import get_new_number
from ...const import Copy_Logo, New_User_Logo, Wrong_Logo, log_file, std_settings, Gen_Logo, Information_Logo
fro... |
from .quota_check import QuotaCheck, QuotaScope
class StackCountCheck(QuotaCheck):
key = "cf_stack_count"
description = "Cloud Formation Stack count"
scope = QuotaScope.ACCOUNT
service_code = 'cloudformation'
quota_code = 'L-0485CB21'
@property
def current(self):
return len(self.b... |
import math
numero = int(input('Digite um numero: '))
dobro = numero * 2
triplo = numero * 3
raiz = math.sqrt(numero)
print('O numero digitado {} tem o seu dobro {}, o seu triplo {}, e a sua raiz {}'.format(numero,dobro,triplo,raiz)) |
from peewee import *
import datetime
import hashlib
from . import db_wrapper
class User(db_wrapper.Model):
username = CharField()
password = CharField()
group = IntegerField()
@staticmethod
def encrypt(passwd):
return hashlib.sha256(passwd.encode('utf-8')).hexdigest()
class Repository(d... |
import datetime as dt
import pathlib
from typing import Dict, List, Optional
import jinja2 as jinja
from metno_locationforecast import Forecast
from .helper_functions import (
cardinal_name_of,
change_units,
max_temp_of,
max_wind_speed_of,
min_temp_of,
sum_rain,
)
def get_context(forecasts: ... |
import copy
import math
from geometry_utils.maths_utility import is_int_or_float, DOUBLE_EPSILON, sqr, PI, is_float, HALF_PI, ONE_AND_HALF_PI, \
CIRCLE_DIVISIONS, TWO_PI, CIRCLE_FACTORS
from geometry_utils.three_d.matrix4 import Matrix4
from geometry_utils.three_d.point3 import Point3, is_point3
from geometry_util... |
# coding=utf-8
from OTLMOW.OEFModel.EMObject import EMObject
# Generated with OEFClassCreator. To modify: extend, do not edit
class TraCoLegacy(EMObject):
"""Trajectcontrole (meet gemiddelde snelheid van voertuigen over een bepaald traject)"""
typeURI = 'https://lgc.data.wegenenverkeer.be/ns/installatie#TraC... |
import argparse
import logging
import os
import signal
import subprocess
import sys
import py2_logger
from pathlib import Path
import yaml
from datetime import datetime
from minicps.mcps import MiniCPS
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.link import TCLink
from topo.simple_topo im... |
# this is taken directly from Daniel Harkness:
# http://artandmath.wordpress.com/
# he is the creator of this but I loved it so much (and needed it) that I wanted to include it
# Thanks to Daniel!!
import nuke
def AM_Rename3DNodeToFBXNodeName():
nuke.Undo.name("Rename selected geo")
nuke.Undo.begin()
all... |
import distutils.version
import re
import shutil
import subprocess
import sys
import textwrap
from typing import List, Dict, Tuple
from . import log
from . import table
SOFTWARE_DEPENDENCIES: Dict[str, Dict] = {
'aws': {
'min': '2.0.0',
'max': None,
'arg': '--version',
'regex': '... |
import operator as op
import time
import uuid
import networkx as nx
import numpy as np
from bluesky.plans import scan
from rapidz import Stream
from shed.simple import walk_to_translation, _hash_or_uid
from shed.translation import FromEventStream, ToEventStream, merkle_hash
from shed.utils import unstar
from databroke... |
import numpy as np
import timeit
from waveletFunctions import wavelet, wave_signif
import matplotlib.pylab as plt
import matplotlib
from mpl_toolkits.axes_grid1 import make_axes_locatable
__author__ = 'Evgeniya Predybaylo'
# WAVETEST Example Python script for WAVELET, using NINO3 SST dataset
#
# See "htt... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 10:37:23 2019
@author: Dell
"""
import random
l=[2,3,4,3,3,4,1,2,3]
random.shuffle(l)
print(l)
random.randint(2,3)
s="hello"#firstly string is converted to lower case firstly and output is always in uppercase
s.startswith('h')#check whether starting wo... |
from importlib import import_module
from urllib.request import urlopen
import cv2
import numpy as np
from classification_models.tfkeras import Classifiers as QubvelClassifiers
from keras_applications import imagenet_utils
from tensorflow.python.keras.applications import keras_modules_injection
class KerasApplication... |
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver import ActionChains
from profile_detail import profile
from match_detail import match
... |
import random
import re
import threading
import time
import wikipedia
from nltk.chunk import ne_chunk
from nltk.tag import pos_tag
from nltk.tokenize import word_tokenize
from attention_keeper.model.city import City
from attention_keeper.model.question import Question, QuestionOption
from attention_keeper.util import... |
#!/usr/bin/env python3
import numpy as np
import pandas as pd
import database_driver
import datetime
from pathlib import Path # <= Added Line
import process_adjustments as pa
dbname = 'harbour.db'
db = database_driver.database(dbname)
if __name__ == '__main__':
sql_create_imports_table = "CREATE TABLE IF NOT EX... |
from enum import Enum
class CrawlTask(Enum):
"""
Represents a task (job) that should be executed by the crawler,
i.e. "SIMILAR" task means that the crawler should find all the
packages similar to the given one
"""
SIMILAR = "CRAWL_SIMILAR"
CREATOR = "CRAWL_CREATOR"
DETAILS = "CRAWL_DET... |
"""Utilities audio convert."""
from __future__ import absolute_import
from __future__ import print_function
import array
import os
import numpy as np
def split(filePath, step = 200000):
file = open(filePath, 'rb')
base = 1 / (1<<15)
shortArray = array.array('h') # int16
size = int(os.path.getsize(fil... |
import argparse
import logging
import os
import sys
import traceback
from colorlog import ColoredFormatter
from sawtooth_intkey.cli.generate import add_generate_parser
from sawtooth_intkey.cli.generate import do_generate
from sawtooth_intkey.cli.load import add_load_parser
from sawtooth_intkey.cli.load import do_load... |
'''
Created on Feb 20, 2017
@author: riaps
'''
import logging
import pprint
from time import time
import requests
from influxdb import InfluxDBClient
from influxdb.client import InfluxDBClientError
import datetime
import random
import time
class Database(object):
def __init__(self):
super(Database, sel... |
from .clear import CacheClearCommand
|
"""This module contains the general information for HcCatalog ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class HcCatalogConsts():
pass
class HcCatalog(ManagedObject):
"""This is HcCatalog class.""... |
# Copyright (c) 2013 OpenStack Foundation
# 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 ... |
#!/usr/bin/env python3
'''
Move a motor back and forth using velocity and position mode of the TMC5161
Created on 30.01.2020
@author: JM
'''
import time
import PyTrinamic
from PyTrinamic.connections.ConnectionManager import ConnectionManager
from PyTrinamic.evalboards.TMC5161_eval import TMC5161_eval
connectionMana... |
# SOURCE: https://github.com/tiangolo/typer-cli#user-content-awesome-cli
import typer
import asyncio
from html_to_markdown_cli.tweetpik import TweetpikHTTPClient, HTTPException, async_download_file
import sys
import rich
import snoop
import signal
import multiprocessing as mp
# from concurrent.futures import ProcessPoo... |
"""
Common constants used in tjunlp.
"""
# class _Const:
# class ConstError(TypeError):
# pass
#
# class ConstCaseError(ConstError):
# pass
#
# def __setattr__(self, name, value):
# if name in self.__dict__:
# raise self.ConstError("Can't change const(%s) value" % name)
... |
from datetime import datetime
from decimal import Decimal
from typing import Optional, Dict
from lib.candle.candle import Candle
from lib.exchange.upbit.model.get_ticker_response import GetTickerResponse
class GetTickerResponseAdapter(Candle):
response: GetTickerResponse
def __init__(self, response: Dict):
... |
# -*- coding: utf-8 -*-
from .store import store
from MySQLdb import IntegrityError
from ORZ import OrzField, OrzBase
from ORZ.klass_init import OrzMeta
from datetime import datetime
__all__ = []
__dict__ = []
class ModelField(OrzField):
def __init__(self, *args, **kwargs):
self.auto_now = kwargs.get('au... |
# Copyright 2014 Josh Pieper, jjp@pobox.com.
#
# 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... |
# coding: utf-8
"""
gae-init
~~~~~~~~
Google App Engine with Bootstrap, Flask and tons of other cool features.
https://github.com/gae-init
https://gae-init.appspot.com
"""
__version__ = '5.6.2'
|
from flask_sqlalchemy import SQLAlchemy
import re
from models import *
import nltk
from nltk.corpus import cmudict
import curses
from curses.ascii import isdigit
d = cmudict.dict()
def scrubText(text, punctuation):
separatedLines = [line.split(punctuation) for line in text]
separatedLines = [string for sublist in ... |
class BetterSolution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
max_difference = len(candies) / 2
d = len(set(candies))
if d > max_difference:
return max_difference
else:
return d... |
import telebot
from amigo.models import User, Participation, ModelManager
from amigo.views.base import BaseView
class EditView(BaseView):
@classmethod
def info(cls):
return "message", {"commands": ["edit", ]}
def group(self, message):
self.bot.reply_to(message, "This command works only ... |
from django import template
from django.contrib.auth.models import Group
from django.db.models import Q
from ticket.models import Ticket
from itertools import chain
register = template.Library()
@register.filter(name='groups')
def groups(user):
"""
Returns all groups the user is a member of.
:param user:... |
# Copyright 2018 Braxton Mckee
#
# 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 t... |
#!/usr/bin/env python
import itertools
import os
import numpy as np
import tensorflow as tf
import tensorflow.contrib.seq2seq as seq2seq
from tensorflow.contrib.rnn import GRUCell
from tensorflow.python.layers.core import Dense
from tqdm import tqdm, trange
from qgen.embedding_vis import prepare_embeddings_for_tenso... |
import os
import shlex
import argparse
import datetime
import subprocess
from typing import IO
from io import TextIOWrapper
from threading import Thread
from balancer_routine import balancer_routine
from balancer_routine import env_data
class Iperf_wrapper():
def __init__(self, parameters: str = "-s -u", verbos... |
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""Shared functionality and helpers for the unit tests."""
from enum import Enum
import functools
import inspect
import logg... |
from datastack import DataTable, DataColumn, label, col, desc
import pytest
import numpy as np
def test_one():
tbl = (DataTable(a=(1,2,1,2,3,1), b=(4,5,6,3,2,1),c=(6,7,8,1,2,3))
.order_by(desc(label("b")))
)
exp = DataTable(a=(1,2,1,2,3,1), b=(6,5,4,3,2,1), c=(8,7,6,1,2,3))
assert tbl... |
from ruamel.yaml import YAML, dump, RoundTripDumper
from raisimGymTorch.env.bin import lbc_husky
from raisimGymTorch.env.RaisimGymVecEnv import RaisimGymVecEnv as VecEnv
import raisimGymTorch.algo.ppo.module as ppo_module
import os
import math
import time
import torch
import argparse
import datetime
# configuration
pa... |
import inspect
import torch.nn as nn
class Sequential(nn.Sequential):
def __init__(self, *args, inverse=False):
super().__init__(*args)
self.inverse = inverse
def forward(self, *input):
if self.inverse:
*others, input = input
else:
input, *others = inpu... |
from operator import getitem
from distutils.version import LooseVersion
import pandas as pd
import pandas.util.testing as tm
import numpy as np
import pytest
import dask
from dask.async import get_sync
from dask.utils import raises, ignoring
import dask.dataframe as dd
from dask.dataframe.core import (repartition_di... |
""" Popup and modal messages """
import pymysql.cursors
from sa_func import get_random_str
from sa_db import sa_db_access
ACCESS_OBJ = sa_db_access()
DB_USR = ACCESS_OBJ.username()
DB_PWD = ACCESS_OBJ.password()
DB_NAME = ACCESS_OBJ.db_name()
DB_SRV = ACCESS_OBJ.db_server()
def check_popup_blocked(var_name, notificati... |
from typing import Dict, Optional, Tuple
import numpy as np
from numpy import ndarray
from .form import Form, FormExtraParams
from ..basis import AbstractBasis
from ...element import DiscreteField
class Functional(Form):
"""A functional for postprocessing finite element solution.
Used similarly as :class:`... |
#!/usr/bin/env python3
"""
Find and list USB devices that have a serial port or a certain vendor ID
Match the devices with the serial port and mount point if possible
The main objective is to get informations about Circuitpython boards in particular and Arduino, Adafruit, and microcontroller boards in general
I foun... |
from numba import njit, generated_jit, vectorize, types
import numpy as np
from . import settings
from .constants import _MAXCOSH
@njit('float64(float64)', cache=settings.CACHE)
def _dsinpi(x):
"""Compute sin(pi*x) for real arguments."""
s = 1.0
if x < 0.0:
x = -x
s = -1.0
r = np.fmo... |
from scipy.fft import fft, fftfreq
import numpy as np
import matplotlib.pyplot as plt
#Chebyshev Filter Coefficients
b = [ 0.00757702, -0.02666634, 0.06433529, -0.09739344, 0.11965053, -0.10339635,
0.07472005, -0.0214037, -0.0214037, 0.07472005, -0.10339635, 0.11965053,
-0.09739344, 0.06433529, -0.02666634, ... |
# encoding: utf-8
#
# setup.py
#
from setuptools import setup
setup()
|
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from . import views
urlpatterns = [
path('signup/', views.signup, name='signup'),
path('login/', views.signin, name='signin'),
path('logout/', views.logout, name='logout'),
path('mypage/', views.myp... |
import uuid
import time
from mfecfe import ClienteVfpeLocal
from mfecfe import BibliotecaSAT
cliente = ClienteVfpeLocal(
BibliotecaSAT('/opt/Integrador'), # Caminho do Integrador
chave_acesso_validador = '25CFE38D-3B92-46C0-91CA-CFF751A82D3D'
)
resposta = cliente.enviar_pagamento(
... |
# Copyright (c) 2022 Cisco Systems, Inc. and its affiliates
# 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... |
import copy
import json
import pytest
import anytree
from anytree.exporter import JsonExporter
from mykrobe.metagenomics import LineagePredictor
def test_lineage_to_itself_plus_parents():
f = LineagePredictor._lineage_to_itself_plus_parents
assert f("a") == ["a"]
assert f("a.1") == ["a", "a.1"]
asse... |
#!/usr/bin/env python3
import sys
seq_list = dict()
f_cons = open('GTDB_r89.GENUS_cons.fa', 'r')
for line in f_cons:
if line.startswith('>'):
tmp_h = line.strip().lstrip('>')
seq_list[tmp_h] = ''
else:
seq_list[tmp_h] += line.strip()
f_cons.close()
p_files = dict()
c_files = dict()
o_f... |
import pandas as pd
import ipywidgets as widgets
from IPython.display import display
class PolicyChecklist():
def __init__(self, controls):
self.controls = controls
self.progress = self._create_progress()
def _checkboxes_to_df(self, checkboxes):
return pd.DataFrame([{'key': c.key,
... |
from logging import getLogger
from typing import List
import ed25519
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
from cryptography.hazmat.primitives.ciphers.aead im... |
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
from vqvae import VQVAE
import pytorch_lightning as pl
def main():
args = dict(
batch_size=32,
lr=0.000056,
epochs=10
)
transform = transforms.Compose([transforms.ToTensor(),
... |
#!/usr/bin/env python3.8
# -*- coding: utf-8 -*
import argparse
import os
import errno
import shutil
from ..__version__ import __version__
from ..logger import log
from .. import make_index
from .. import preprocess
from .. import make_correspondances
from .. import process
from .. import match
from .. import resamp... |
import numpy as np
import cv2
def abs_sobel_thresh(img, sobel_kernel=3, orient='x', thresh=(0,255)):
# Apply the following steps to img
# 1) Convert to grayscale
# 2) Take the derivative in x or y given orient = 'x' or 'y'
# 3) Take the absolute value of the derivative or gradient
# 4) Scal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.