content
stringlengths
5
1.05M
#!/usr/bin/env python import os import sys import dbus import time import urllib2 import subprocess import ConfigParser from bs4 import BeautifulSoup from os.path import expanduser item = "org.freedesktop.Notifications" path = "/org/freedesktop/Notifications" interface = "org.freede...
class SuperError(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return repr(self.msg) class DownloadError(SuperError): pass class ParseError(SuperError): pass
import json import scipy.stats import matplotlib.pyplot as plt import numpy as np def open_file(nameFile): try: f = open(nameFile + ".json", "r") dados = json.loads(f.read()) f.close() except: dados = 0 pass return dados def mean_confidence_interval(data, confide...
from .activations import * from ..layers.convolutions import Convolutional, Cond_Convolutional import math import numpy as np class Shuffle_new(nn.Module): def __init__(self, filters_in, filters_out, kernel_size=3 ,c_tag=0.5, groups=3, dila=1): super(Shuffle_new, self).__init__() self.left_part = ro...
#Import necessary package import requests import re from bs4 import BeautifulSoup import json import html import pandas as pd import numpy as np import datetime as dt import configparser import os #Configure parameter config = configparser.ConfigParser() config.read(os.path.join(os.path.dirname(__file__), 'config.ini'...
from dataclasses import dataclass, field from enum import auto, Enum from typing import Dict, Optional from cu_pass.dpa_calculator.cbsd.cbsd import CbsdCategories from cu_pass.dpa_calculator.number_of_aps.number_of_aps_calculator import NumberOfCbsdsCalculatorOptions NEIGHBORHOOD_DISTANCES_TYPE = Dict[CbsdCategories,...
""" Sponge Knowledge Base Removing scheduled events """ from java.util.concurrent.atomic import AtomicInteger def onInit(): global eventEntry, eventCounter eventEntry = None eventCounter = AtomicInteger(0) sponge.setVariable("eventCounter", eventCounter) sponge.setVariable("allowNumber...
import unittest from conans.util.misc import make_tuple class MakeTupleTestCase(unittest.TestCase): def test_corner_cases(self): self.assertIsNone(make_tuple(None)) self.assertTupleEqual(make_tuple("one"), ("one",)) def test_iterable(self): self.assertTupleEqual(make_tuple([1, 2, 3])...
from django.test import TestCase, Client from django.contrib.auth.models import User from ..models import ( DomainProvider, Contact, ) class TestSetup(TestCase): fixtures = ["test_auth.json", "contact_types.json", "providers.json", "tlds.json", ...
#!/usr/bin/env pytest ############################################################################### # $Id$ # # Project: GDAL/OGR Test Suite # Purpose: Test Zarr driver # Author: Even Rouault <even.rouault@spatialys.com> # ############################################################################### # Copyright ...
''' Created on 18-sep-2020 @author: david ''' import sys sys.path.append("/flash/userapp") from uvacbot.sensor.mpu6050 import Mpu6050 from math import radians from micropython import alloc_emergency_exception_buf from pyb import Pin, Switch from uasyncio import run as uasyncio_run, sleep_ms from uvacbot.engine.driver...
from os import path from collections import namedtuple import click import graphviz from functional import seq ENGINES = ['dot', 'neato', 'twopi', 'circo', 'fdp', 'sfdp', 'patchword', 'osage'] Edge = namedtuple('Edge', 'left right label') def split_edge(edge): edge_label = None if ':' in edge: edge, ...
# -*- coding: utf-8 -*- class Default: """ It is used to replace `None` or `object()` as a sentinel that represents a default value. Sometimes we want to set a value to `None` so we cannot use `None` to represent the default value, and `object()` is hard to be typed. """ pass DefaultValu...
import serial import deepstream NoOfValues = 14 #No of values written by Arduino to Serial ArduinoPort = '/dev/ttyACM0' BaudRate = 57600 def getArduinoValues(): printValues = False sensorValues = [] listIndex = 0 ser = serial.Serial(ArduinoPort,BaudRate) while True: if(se...
""" Two-Mention or two-Entity constraints. The first argument must always be the candidate antecedent, while the second argument must be the Mention/Entity occurring later. Not all constraints are necessarily available at both the Mention _and_ the Entity level. Moreover, some constraints may take an Entity as antece...
#!/usr/bin/env python3 from functools import reduce import operator import pygame test_points = [[50, 50], [500, 1500], [500, -800], [750, 750]] background_color = (100, 100, 100) game_clock = 60 quit_flag = False window_size = (800, 800) def memoize(f): memory = {} def memoized(*args): if args not...
# -*- encoding: utf-8 -*- # # The MIT License (MIT) # # Copyright (c) 2016-2018 Tobias Koch <tobias.koch@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, incl...
#!/usr/bin/env python from . import elk, elk_io
import math from typing import Dict, Any, Tuple def calculate_centroid(metadata: Dict[str, Any]) -> Tuple[float, float, int]: """Calculate a rough centroid for the metadata provided by rio-tiler. Args: metadata: the metadata generated by rio-tiler for a compliant image Returns: The centr...
import collections import chainer import numpy as np import onnx from typing import List, Mapping from chainer_compiler.ch2o import env from chainer_compiler.ch2o import utils def _is_float_value(v): # The latter is for numpy-like things. return isinstance(v, float) or int(v) != v class Value(object): ...
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class MessagesConfig(AppConfig): name = 'django.contrib.messages' verbose_name = _("Messages")
# -*- coding: UTF-8 -*- # @yasinkuyu # Define Python imports import os import sys import time import config import argparse import threading import sqlite3 # Define Custom imports from BinanceAPI import * # Define Custom import vars client = BinanceAPI(config.api_key, config.api_secret) conn = sqlite3.connect('order...
from sqlalchemy.orm import Query ''' https://stackoverflow.com/questions/15936111/sqlalchemy-can-you-add-custom-methods-to-the-query-object ''' class CustomQuery(Query): def filter_if(self: Query, condition: bool, *criterion): if condition: return self.filter(*criterion) else: ...
from rest_framework import serializers from clients.models import Profile class ProfileSerializer(serializers.HyperlinkedModelSerializer): id = serializers.IntegerField(read_only=True) class Meta: model = Profile fields = '__all__'
# ยฉ MNELAB developers # # License: BSD (3-clause) from PySide6.QtCore import Qt, Slot from PySide6.QtWidgets import ( QDialog, QDialogButtonBox, QGridLayout, QListWidget, QRadioButton, ) from .utils import select_all class PickChannelsDialog(QDialog): def __init__(self, parent, channels, typ...
from pycassa.types import Column __all__ = ['ColumnFamilyMap'] def create_instance(cls, **kwargs): instance = cls() instance.__dict__.update(kwargs) return instance class ColumnFamilyMap(object): def __init__(self, cls, column_family, columns=None, raw_columns=False): """ Construct a ...
# print('ๆ–‡่ƒฝๆ็ฌ”ๅฎ‰ๅคฉไธ‹') # print('ๆญฆ่ƒฝไธŠ้ฉฌๅฎšไนพๅค') # # print('''ๆ–‡่ƒฝๆ็ฌ”ๅฎ‰ๅคฉไธ‹ # ๆญฆ่ƒฝไธŠ้ฉฌๅฎšไนพๅค''') # wonderful = 66 # # num = int(input('่ฏท่พ“ๅ…ฅไธ€ไธชๆ•ฐ:')) # if num > 66: # print('็Œœๅคงไบ†') # elif num < 66: # print('็Œœๅฐไบ†') # else: # print('ๆญๅ–œไฝ .') # content = input('่ฏท่พ“ๅ…ฅ้บป่Šฑ่—ค:') # if content == '้บป่Šฑ่—ค': # print('็œŸ่ชๆ˜Ž') # else: # print('ไฝ ๆ˜ฏSBไนˆ?...
import json import logging import os import pathlib import shutil import sys import jsonschema from players import PlayerLookup def config_binary(json_content, binary): for config_binary in json_content.get('executables', {}): if config_binary['name'] == binary: return pathlib.Path(config_bi...
#!/usr/bin/python from restkit.resource import Resource import urllib2 import time from StringIO import StringIO import json import logging import sys from urllib import urlencode from optparse import OptionParser from urlparse import urljoin logging.basicConfig(level=logging.INFO) log = logging.getLogger("main") d...
""" Atribuindo dados em um DataFrame """ import pandas as pd base = pd.read_csv("./index_select_assign/assigning_data_3/census2.csv") print(base.loc[base.occupation == " ?"]) # OBS: nรฃo alterei o arquivo original, modifiquei a base base.loc[base.occupation == " ?", "occupation"] = "Nรฃo informado" print(base.loc[bas...
from lm_eval import tasks from itertools import islice ct = 3 for tname, Task in tasks.TASK_REGISTRY.items():#[('record', tasks.superglue.ReCoRD)]:# task = Task() print('#', tname) docs = islice(task.validation_docs() if task.has_validation_docs() else task.test_docs(), ct) print() for i in range...
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.5.2 # kernelspec: # display_name: 'Python 3.8.5 64-bit (''hsfm'': conda)' # name: python3 # --- # Trying to follow... # https://ceholden.github...
import requests from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import validate_email class GlobeePayment: """ Globee Payment """ def __init__(self, payment_data: dict = None, payment_id: str = None): """ Init Globee pay...
# -*- coding: utf-8 -*- import sys sys.path.append('../') import sklearn import sklearn.preprocessing import numpy as np from datetime import datetime import math from utilx.constant import CONST, RedisKeyConstant import traceback from utilx.utils import Utils import logging from utilx.redix import Re...
from react_select.ReactSelect import ReactSelect from selenium import webdriver driver = webdriver.Chrome() driver.get('https://jedwatson.github.io/react-select/') react_select = ReactSelect(driver.find_element_by_class_name('Select'), 1) react_select.open_menu() react_select._close_menu() react_select.select_by_visib...
from __future__ import annotations from typing import TYPE_CHECKING, Optional from .playlist import Playlist from .constants import * if TYPE_CHECKING: from ..spotify import SpotifyClient from ..youtube import YoutubeClient async def get_playlist( spotify: SpotifyClient, youtube: YoutubeClient, url: st...
import json import logging from pprint import pprint from urllib.parse import urlparse import requests import wikipedia from PIL import Image from opennem.api.photo.controllers import img_to_buffer, write_photo_to_s3 from opennem.core.loader import load_data from opennem.core.normalizers import station_name_cleaner f...
import tempfile import unittest import numpy as np from server.common.compute import diffexp_generic from server.common.fbs.matrix import encode_matrix_fbs, decode_matrix_fbs from server.compute import diffexp_cxg from server.compute.diffexp_cxg import diffexp_ttest from server.dataset.matrix_loader import MatrixData...
import csv #as always, something in my system changes the current dir to F:/Git # with open("data.csv", "w") as file: # writer = csv.writer(file, lineterminator='\n') #lineterminator='\n' removes blank rows, but makes this code not *nix-compatible # writer.writerow(["transaction_id", "product_id", "price"]) ...
from . import provider from . import system from . import cview
#!/usr/bin/env python # encoding: utf-8 from unittest import TestCase import mock import time from ycyc.ycollections.namedict import namedict, RequireFieldsMissError class TestNamedDict(TestCase): def test_usage(self): cur_time = time.time() Params = namedict( "InvokeParams", ...
import os import shutil import unittest import logging import pymel.core as pm from Luna import Config from Luna import Logger from Luna import TestVars from Luna.static import directories class TestCase(unittest.TestCase): """ Base class for unit test cases run in Maya. Tests do not have to inherit from...
#!/usr/bin/env python3 # Copyright (c) 2017-2021 The Particl Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. import random from test_framework.test_particl import GhostTestFramework from test_framework.util import ...
from random import randint from time import sleep computador = randint(0,10) print('='*60) print('\33[32mVou pensar em um nรบmero entre 0 e 10. Tente adivinhar!\33[m') print('='*60) jogador = int(input('Qual nรบmero eu pensei? ')) print('\33[32mPROCESSANDO...\33[m') sleep(2) vez = 1 while jogador != computador: print...
from django import forms from django.conf import settings from django.contrib.auth.models import User from .constants import * from .models import ObjectChange def add_blank_choice(choices): """ Add a blank choice to the beginning of a choices list. """ return ((None, "---------"),) + tuple(choices) ...
import os from scipy.io import wavfile import json import ast import numpy as np jsonDirPath = '/Users/Chen/็™พๅบฆไบ‘ๅŒๆญฅ็›˜/Startup/Clevo/่”ๅŠจๆ•ฐๆฎ/emotionJson/' wavDirPath = '/Users/Chen/็™พๅบฆไบ‘ๅŒๆญฅ็›˜/Startup/Clevo/่”ๅŠจๆ•ฐๆฎ/wav/' wavSavePath = '/Users/Chen/็™พๅบฆไบ‘ๅŒๆญฅ็›˜/Startup/Clevo/่”ๅŠจๆ•ฐๆฎ/wavSegs/' if (os.path.isdir(jsonDirPath) != True): rais...
"""Debug helper The purpose of this file is to help during development. The idea is to silence internal exceptions raised by Friendly itself for most users by redirecting them here, and have them printed only when debugging mode is activated. """ import os import sys from typing import Any, Optional from .ft_gettext...
from django.urls import path from .views import checkout,HomeView,ItemDetailView app_name='core' urlpatterns=[ path('product/<slug>',ItemDetailView.as_view(),name='product'), path('',HomeView.as_view(),name='home'), path('checkout/',checkout,name='checkout'), ]
from models.senet import senet50 import utils from torch.autograd import Variable import torch import cv2 import torchvision.transforms import numpy as np from PIL import Image class VGGFace: def __init__(self, trained_model="/media/haoxue/WD/VGGFace2-pytorch/senet50_ft_weight.pkl", transform=True): sel...
import requests import time import datetime import json import cexapi from twilio.rest import Client from config import * from sys import argv # colors for terminal output class bcolors: MAGENTA = '\033[95m' BLUE = '\033[94m' GREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\0...
import sys from typing import Any, List app_list: List = ["flask", "starlette", "sanic", "tornado"] def auto_load_app_class() -> Any: """A project using only a web framework, to use `auto_load_app_class`""" real_app: Any = None for app in app_list: if app not in sys.modules: continue ...
from ebml.base import EBMLInteger, EBMLString, EBMLMasterElement, EBMLProperty #from ebml.util import TypeValidator, EBMLProperty __all__ = ["EBMLVersion", "EBMLReadVersion", "EBMLMaxIDLength", "EBMLMaxSizeLength", "DocType", "DocTypeVersion", "DocTypeReadVersion", "EBMLHead"] class EBMLVersion(EBMLInteger...
import logging logger = logging.getLogger(__name__) import simplejson as json from datetime import datetime from blinker import signal from cassandra.cqlengine import columns from cassandra.cqlengine.models import Model from ...common.mixins.json import JsonMixin class AbstractBaseModel(Model, JsonMixin): """ ...
import torch import torch.nn.init import torch.nn as nn eps = 1e-10 class L2Norm(nn.Module): def __init__(self): super(L2Norm,self).__init__() self.eps = 1e-10 def forward(self, x): norm = torch.sqrt(torch.sum(x * x, dim = 1) + self.eps) x= x / norm.unsqueeze(-1).expand_as(x)...
# Generated by Django 2.1.3 on 2020-06-30 07:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('result', '0101_auto_20200626_1450'), ] operations = [ migrations.AddField( model_name='btutor', name='first_term', ...
import hashlib import zlib from util.repo_handling.repo_file import repo_file def object_write(obj, actually_write=True): data = obj.serialize() # Add header result = obj.fmt + b' ' + str(len(data)).encode() + b'\x00' + data # Compute hash sha = hashlib.sha1(result).hexdigest() if actually_w...
import argparse import sys import os import getpass from fetchai.ledger.api import LedgerApi from fetchai.ledger.crypto import Entity, Address from fetchai.ledger.crypto.entity import _strong_password as is_strong_password from fetchai.ledger.serialisation.transaction import encode_transaction from .address_book impo...
# -*- coding: utf-8 -*- # โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— # โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘โ•šโ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ–ˆโ–ˆโ•”โ•โ•โ•โ•โ•โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•”โ•โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— # โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ•šโ–ˆโ–ˆโ–ˆโ•”โ• โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•”โ• # โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘โ•šโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•”โ•โ•โ• โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•”โ–ˆโ–ˆโ•— โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•”โ•โ•โ–ˆโ–ˆโ•— # โ–ˆโ–ˆโ•‘โ–ˆโ–ˆโ•‘ โ•šโ–ˆโ–ˆโ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ•‘ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ•—โ–ˆโ–ˆโ•‘โ–ˆ...
# /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright ยฉ 2021-12-08 20:14 bucktoothsir <rsliu.xd@gmail.com> # # Distributed under terms of the MIT license. """ """ from unittest import mock from domxss import DomXSSDetector from domxss import DomAlertInfo from .test_config import * import p...
# stdlib imports import datetime # django imports from django.conf import settings from django.core.cache import cache from django.db import models from django.db import transaction from django.db.models import Count from django.db.models import F from django.db.models import OuterRef from django.db.models import Subqu...
import esphome.codegen as cg import esphome.config_validation as cv from esphome import pins from esphome.components import sensor from esphome.const import CONF_COUNT_MODE, CONF_FALLING_EDGE, CONF_ID, CONF_INTERNAL_FILTER, \ CONF_PIN, CONF_RISING_EDGE, CONF_NUMBER, \ ICON_PULSE, UNIT_PULSES_PER_MINUTE from esp...
"""attendence indexes Revision ID: 3559c36f279d Revises: 3daa1030c816 Create Date: 2015-07-21 09:34:59.716931 """ # revision identifiers, used by Alembic. revision = '3559c36f279d' down_revision = '3daa1030c816' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa def upgrade(): ...
# -*- coding: utf-8 -*- """The item methods and class """ from __future__ import unicode_literals class Item(object): """ Define a basic item of the db. """ def __init__(self, title, link, feed, username, content): """ Initialize an item object. This define what a...
""" File: pitch_range_interpreter.py Purpose: A PitchRangeInterpreter is an interface for mapping numeric values to pitches. """ from abc import ABC, abstractmethod class PitchRangeInterpreter(ABC): """ A PitchRangeInterpreter is an interface for a function whose utility to to map numeric values to pitches...
import sys from src.functionality import data_io from src.functionality import user import requests import json import os import datetime sys.modules['user'] = user class App: def __init__(self): self.user_expense_data = {} self.user_budget_data = {} self.budget_performance_data = {} ...
# Copyright (C) 2019 Intel Corporation # # 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 wri...
mensagem = 'oi, python' numero = 10 pi = 3.14 type(mensagem) type(numero) type(pi) meu_nome = 'Rondinele' print("Hello, World!") numero = input('Digite um nรบmero:\n') print(numero)
iris_file = open('iris_train.csv') iris_file = iris_file.readlines() def sort_by_0(n): return n[0] def sort_by_1(n): return n[1] def sort_by_2(n): return n[2] def sort_by_3(n): return n[3] setosa_range = [] versicolor_range = [] virginica_range = [] for i in range(len(iris_file)): iris_file[i] =...
__author__ = 'Sushant' from sklearn.base import BaseEstimator, ClassifierMixin from scipy.optimize import minimize from sklearn.metrics import log_loss import numpy from sklearn.cross_validation import StratifiedShuffleSplit """ Usage: estimators = [] estimators.append(RandomForestClassifier(n_estimators = 100)) esti...
#17/02/21 #What does this code do? # This code is designed to take a single line input of the class, which according to Grok will be given in Title case (Only first letter capitalised.) with a single space between each name. # We use the .sort() function in this code, as well as the .split() function. Put basically,...
from pytorch_lightning.loggers.base import LightningLoggerBase, rank_zero_only import csv import os import numpy as np from os.path import join from argparse import Namespace from typing import Optional, Dict, Union, Any from warnings import warn import torch from pkg_resources import parse_version from torch.utils.te...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 5 18:55:22 2018 @author: kyungdoehan """ import pandas as pd import os import numpy as np #%% Importing lake coordinates and levels class lake_data_read: def __init__(self, Ma, nz, ny, nx, grid, rch, dx, dy, lakeK, top, bot, lakeb): sel...
from plugins.module_utils.foreman_helper import _foreman_spec_helper def test_empty_entity(): spec = {} foreman_spec, argument_spec = _foreman_spec_helper(spec) assert spec == {} assert foreman_spec == {} assert argument_spec == {} def test_full_entity(): spec = { 'name': {}, ...
#!/usr/bin/env python from distutils.core import setup from setuptools import setup,find_packages setup(name='glasgowcs_labtest', version='1.0.6', description='Testing framework for Glasgow CS classes', url='https://github.com/jakelever/glasgowcs_labtest', author='Jake Lever', author_email='jake.lever@glasgow.a...
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import plotly.express as px import pandas as pd import numpy as np from plotly.subplots import make_subplots import plotly.graph_objects as go from sqlalchemy.orm import Session from sqlalchemy...
str = input("Enter the equation as follows (5 + 2) > ") equation = str.split(" ") num1 = int(equation[0]) operator = equation[1] num2 = int(equation[2]) answer = 0 match operator: case "+": answer = num1 + num2 case "-": answer = num1 - num2 case "*": answer = num1 * num2 case "/...
from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from pyuploadcare.dj.forms import ImageField from .models import Profile, Neighbourhood, Updates, Business, EmergencyContact, Post class SignupForm(UserCreationForm): class Meta: mo...
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-01-19 17:16 from __future__ import absolute_import from __future__ import unicode_literals from django.core.management import call_command from django.db import migrations def update_es_mapping(*args, **kwargs): def _update_es_mapping(): retu...
from spada.methods import method from spada.network import ensembl_transcript_network import os import pytest scriptPath = os.path.realpath(__file__) dataPath = os.path.dirname(scriptPath) + "/../../data/" txs = ensembl_transcript_network.ENSEMBLTranscriptNetwork('aName') txs.skip_filter = False def test_init(): ...
def initialize(): """Initialize the dashboard, data storage, and account balances.""" return def build_dashboard(): """Build the dashboard.""" return def fetch_data(): """Fetches the latest prices.""" return def generate_signals(): """Generates trading signals for a given dataset.""" ...
#!/usr/bin/python # # James Sandford, copyright BBC 2020 # # 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 l...
""" author: Paul Bruillard, harsh """ import jax.numpy as jnp from jax import jit from cjax.utils.math_trees import * from typing import Any from functools import partial def get_rotation_pytree(src: Any, dst: Any) -> Any: """ Takes two n-dimensional vectors/Pytree and returns an nxn rotation matrix mappi...
############################################################################### # main.py # # simple script to read the value of a Force Sensitive Resistor (FSR) every # 500ms and print its value to the REPL. The pin connected to Pin Y12 on the # pyboard, should have a pull-down resistor of 10K connected to it ...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="senda", version="0.7.7", author="Lars Kjeldgaard", author_email="lars.kjeldgaard@eb.dk", description="Framework for Fine-tuning Transformers for Sentiment Analysis", long_description=...
import json import math import numpy as np import pandas as pd import xarray as xr from pyplan_engine.classes.evaluators.BaseEvaluator import BaseEvaluator from pyplan_engine.classes.evaluators.PandasEvaluator import PandasEvaluator from pyplan_engine.classes.XHelpers import XHelpers, XIndex from pyplan_engine.common...
from django.contrib import admin from .models import Employee, Position # Register your models here. # Register your models here. admin.site.register(Employee) admin.site.register(Position)
import os import pandas as pd import numpy as np from sklearn import linear_model from sklearn.model_selection import train_test_split def getData(): # Get home data from CSV file dataFile = None if os.path.exists('home_data.csv'): print("-- home_data.csv found locally") dataFile = pd.read_...
from typing import Any, Optional from pandas_profiling.config import ImageType from pandas_profiling.report.presentation.core.item_renderer import ItemRenderer class Image(ItemRenderer): def __init__( self, image: str, image_format: ImageType, alt: str, caption: Optional[s...
# STACK IMPLEMENTED AS A LIST #To check stack is empty or not def isEmpty(stack): if stack==[]: return True else: return False #Insertion of Element def Push(stack, item): stack.append(item) top=len(stack)-1 #Deletion of Element def Pop(stack): if isEmpty(stack): ...
import random from kelte.maths import Position from kelte.tiles import get_tile, Tile from kelte.ecs import Entity mob_registry = {} def create_mob(name: str, type: str, tile: Tile = None, health: int = None, inventory: dict = None, position: Position = None): tile = get_tile(name) if tile is None else tile ...
# -*- coding: utf-8 -*- from translate.TranslatorInterface import TranslatorInterface import requests from lxml import html import json from gtts import gTTS # # https://dictionary.yandex.net/api/v1/dicservice.json/lookup?key=dict.1.1.20170611T172307Z.4abaf98a6a837032.37092569e629450212c2a109f3e90091d784d1e3&lang=ru-...
# :coding: utf-8 # :copyright: Copyright (c) 2014 ftrack import os import re from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand from pkg_resources import get_distribution, DistributionNotFound ROOT_PATH = os.path.dirname(os.path.realpath(__file__)) RESOURCE_PATH = o...
""" The module containing the PyReshaper configuration specification class This is a configuration specification class, through which the input to the PyReshaper code is specified. Currently all types of supported operations for the PyReshaper are specified with derived dypes of the Specification class. Copyright 20...
"""Bayesian polynomial mixture model.""" # pylint: disable=invalid-name import numpy as np import tensorflow as tf import tensorflow_probability as tfp tfd = tfp.distributions tfb = tfp.bijectors class BayesianPolynomialMixture: # pylint: disable=too-few-public-methods """Handles creation of a polynomial mixtu...
import numpy as np from numba import njit @njit(cache=True) def calculate_goodness_of_fit(table): n = table.shape[0] m = table.sum() row_sum = table.sum(axis=0).astype(np.float64) col_sum = table.sum(axis=1).astype(np.float64) e = np.dot(col_sum.reshape(n, 1), row_sum.reshape(1, 2)) / m s = np...
from radioapi.radios.Radio import Radio import json jsonData = {} jsonData['QDM'] = False jsonData['Launch'] = False jsonData['Abort'] = False radio = Radio(True) radio.send(json.dumps(jsonData), True)
## ## Get commandline arguments ## from sys import stderr as error from sys import stdout as out from sys import exit from re import compile def print_usage(output, bin_name): print("%s: Usage:\n" % bin_name, file=output) print("\t-h/--help\tPrint usage", file=output) print("\t-u\t\tUser name", file=outpu...
__pyarmor__(__name__, __file__, b'\x50\x59\x41\x52\x4d\x4f\x52\x00\x00\x03\x08\x00\x55\x0d\x0d\x0a\x04\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x40\x00\x00\x00\xdc\x0f\x00\x00\x00\x00\x00\x10\xac\xe4\x91\x3d\xb6\x93\x02\x2d\xa7\xfa\x52\xf5\x3f\xd6\x9c\x72\x00\x00\x00\x00\x00\x00\x00\x00\xe5\x4a\x3b\x2f\xe6\x1f\x89\x...
# # Copyright 2021 Ocean Protocol Foundation # SPDX-License-Identifier: Apache-2.0 # # %% import json import logging from pathlib import Path import jsonschema as jschema import pkg_resources # %% # Here is the Schema file, loaded as the default to validate against LOCAL_SCHEMA_FILE = Path( pkg_resources.resourc...
import logging import re from bs4 import BeautifulSoup LOGGER = logging.getLogger(__name__) class BaseHtmlSplitter: """ Permit to split an HTML file or string """ INTERNAL_BODY_FINDER = re.compile(r"<body[\w\-=\"\ ]*>([\s\S]+?)<\/body>") HEADER_REGEX = re.compile(r'^h[1-7][\w\-="\ ]*') @s...