content
stringlengths
5
1.05M
ListVar = [ "iLoad1", "iLoad2", "iMod1", "iMod2", "iMod3", "iMod4", "vLoad", "vDCMod1", "vDCMod2", "vDCMod3", "vDCMod4", "vOutMod1", "vOutMod2", "vOutMod3", "vOutMod4", "temp1", "temp2", "temp3", "temp4", "ps_OnOff", "ps_OpMode", "p...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import nu...
AUTH_ROUTES = [ '/edit-profile/', '/', '/about/', '/contact/', '/faq/', '/privacy/', '/tos/', '/change-password/', '/users/', '/calendar/', "/robots.txt", "/external/" ] AUTH_REDIR_ROUTES = [ '/login/', '/signup/', "/reset-password/", "/reset-limbo/", "/signup-limbo/", '/o/test/', ...
from fractions import Fraction from typing import List, Sequence, Union ExactNumber = Union[int, Fraction] NonInteger = Union[float, Fraction] Number = Union[int, float, Fraction] NumberList = List[Number] Numeric = Union[Number, str] NumericSequence = Union[None, Numeric, Sequence[Numeric]]
"""Test file for output File""" import csv import json import os from rawsec_cli.output import csv_output from rawsec_cli.output import json_output from rawsec_cli.output import list_output from rawsec_cli.output import print_output from rawsec_cli.output import table_output def test_json_output(capsys): """test...
import sys sys.path.insert(0, "../../") import matplotlib.pyplot as plt import algorithms as alg fig = plt.figure(figsize=(6,4)) plt.xlabel("Episodes") plt.ylabel("Value") eps = 0.5 N = 1000 eps_non = [alg.utils.decay_none(eps, i, N) for i in range(N)] eps_lin = [alg.utils.decay_linear(eps, i, N) for i in range(N)] e...
""" Diffie-Hellman mechanisms. """ from _ctypes import pointer, sizeof from ctypes import cast, c_void_p from ..attributes import to_byte_array from ..cryptoki import CK_ECDH1_DERIVE_PARAMS, CK_BYTE_PTR, CK_ULONG from .helpers import Mechanism class ECDH1DeriveMechanism(Mechanism): """ ECDH1-specific mechan...
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) pub_year = models.IntegerField('year published')
#!/usr/bin/env python """ Values based on Kofke Antoine law + Johnson MWBR EOS, corrected for TS potential (Schlaich & Coasne, JCP 2019) - should be correct within 1-2% (based on rigorous finite size scaling, to be published) """ import mwbr # parameters for Argon temp = 95.84 # temperature in Kelin epsilon = 119.8...
# Austin Liu # tknac.py import tkinter as tk import random board = [[" "," "," "],[" "," "," "],[" "," "," "]] pos = [[[50, 50],[150, 50],[250, 50]],[[50, 150],[150, 150],[250, 150]],[[50, 250],[150, 250],[250, 250]]] root = tk.Tk() root.title("Tic Tac Toe") canvas = tk.Canvas(root, width=300, height = 30...
""" Uplift estimation and selection functions. Written by Daniel Steinberg and Lachlan McCalman, Gradient Institute Ltd. (info@gradientinstitute.org). Copyright © 2020 Monetary Authority of Singapore Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with t...
import uuid from datetime import datetime, timedelta import time import simplejson as json import urllib from google.appengine.api import modules from google.appengine.api import taskqueue from cassandra.cqlengine import columns, ValidationError from cassandra.cqlengine.models import Model from transitions import Machi...
from datetime import datetime from zeit.cms.i18n import MessageFactory as _ from zeit.cms.interfaces import CONFIG_CACHE from zeit.cms.workflow.interfaces import CAN_PUBLISH_ERROR from zeit.cms.workflow.interfaces import CAN_PUBLISH_SUCCESS from zeit.cms.workflow.interfaces import CAN_PUBLISH_WARNING from zeit.workflow...
""" time_series_generator.py ======================== Holds TimeSeriesGenerator class to generate time series values based on a set of inputs. """ from datetime import datetime, timedelta from calendar import monthrange class SimpleDate(object): """ Simple container class for a date. ""...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import libvirt from ovm.utils.logger import logger class LibvirtConnect: _conn = None _connection_string = 'qemu:///system' @classmethod def get_connection(cls): if cls._conn is None: cls._conn = libvirt.open(cls._connection_string...
#coding: utf-8 from __future__ import unicode_literals import unittest import io from tempfile import NamedTemporaryFile from lxml import etree, isoschematron from packtools import domain, style_errors, exceptions # valid: <a><b></b></a> # invalid: anything else sample_xsd = io.BytesIO(b'''\ <xsd:schema xmlns:xsd="...
class ActivationStep: def __init__(self): self.output = [] def forward(self, inputs): # outdated most of the time because it makes regression harder res = [] for value in inputs: if value > 0: res.append(1) else: res.append(0) ...
from abc import ABC, abstractmethod class RenderInterface2D(ABC): def __init__(self): self._rendering_enabled = False self._rendering_type = "2d" self._state_history_for_rendering = [] self._refresh_interval = 50 # in milliseconds self....
#! /usr/bin/python import json import numpy as np from flask import jsonify from flask_restful import Resource, reqparse from algorithm.streamAnomalyDetect import stream_anomaly_detect class post_stream_data(Resource): """ post stream data for anomaly detection with one field. """ def __init__(self,...
# Generated by Django 2.2.4 on 2019-10-14 13:55 import logging from django.db import migrations logger = logging.getLogger(__name__) class Migration(migrations.Migration): initial = True dependencies = [ ('library', '0004_auto_20191022_1521'), ] operations = [ ]
import tensorflow as tf import numpy as np import sys sys.path.append('../') from scipy.io import savemat import os import scipy.misc #from spectrum import fftshift #from tensorflow.python.ops.signal.helper import fftshift #from tensorflow.python.ops.signal.helper import ifftshift #from tensorflow.python imp...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
class Solution: """ @param x: An integer @return: The sqrt of x """ def sqrt(self, x): if x < 1: return 0 l, r = 1, x//2 + 1 while r > l: mid = (l + r) // 2 square = mid * mid if square > x: ...
def getBonuses(performance): bonus = [1] for i in range(1, len(performance)-1): plus = 1 if performance[i] > performance[i-1]: plus += 1 if performance[i] > performance[i+1]: plus += 1 bonus.append(plus) bonus.append(performance[len(performance)-1]) ...
from multiprocessing import Process, Value counter = Value('i', 0) num = 1000 def fx1(): for _ in range(num): with counter.get_lock(): counter.value += 1 def fx2(): for _ in range(num): with counter.get_lock(): counter.value += 1 if __name__ == '__main__': p1 =...
import torch import torch.nn as nn import torch.nn.functional as F from pointnet2_lib.pointnet2.pointnet2_modules import PointnetFPModule, PointnetSAModuleMSG from lib.config import cfg from torch.nn.functional import grid_sample BatchNorm2d = nn.BatchNorm2d def conv3x3(in_planes, out_planes, stride=1): """3x3 c...
import numpy as np import random as rd class Kmeans: def __init__(self, data, kind=2, rowsam=True): ''' :__init__: Kmeans类初始化 :param data: 样本矩阵,样本矩阵中的每个样本向量(每行或者每列)将被依次编号为0,1,2,... :type data: np.array :param kind: 聚类的类别数量,默认值为2,即聚类为2类,这些类别将被依次编号为0,1,2,... ...
from __future__ import unicode_literals import logging import re import urllib from bs4 import BeautifulSoup from mopidy import backend from mopidy.models import Album, Artist, Ref, Track logger = logging.getLogger(__name__) class BassdriveLibraryProvider(backend.LibraryProvider): _genre = 'Drum and Bass' ...
import flask import mkstowe import mariadb import sys import os from gensim.models import Word2Vec def get_db(): if 'mariadb_db' not in flask.g: with open(mkstowe.app.config["SECRETS_FILE"], "r") as f: lines = f.readlines() username = lines[0].strip() password = lines[1...
# -*- coding: utf-8 -*- from django.conf.urls import url from . import views app_name = 'financeiro' urlpatterns = [ # Lancamentos # Gerar lancamento url(r'gerarlancamento/$', views.GerarLancamentoView.as_view(), name='gerarlancamento'), # Lista todos lancamentos url(r'lancamentos/$', view...
''' Export/Dataframes/comparative _____________________________ Dataframe producer for the comparative report, or a report with a 2D table of the crosslinks identified with a horizontal axis for files/crosslinkers and a vertical axis for linkages identified. :copyright: (c) 2015 The Regents of...
from tfcgp.config import Config from tfcgp.chromosome import Chromosome from tfcgp.problem import Problem import numpy as np import tensorflow as tf from sklearn import datasets c = Config() c.update("cfg/base.yaml") data = datasets.load_iris() def test_creation(): p = Problem(data.data, data.target) print(p....
import os from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db import connections from django.db.utils import ConnectionDoesNotExist class Command(BaseCommand): help = 'Recreates the database' def add_arguments(self, parser): p...
#!/usr/bin/env python3 from .io import read from .io import write from .io import register_read_function from .io import register_write_function from .io import register_file_system from .io import unregister_file_system from .read_parallel import read_parallel from .file import File from .path import Path from .pa...
try: from gpiozero import LED except: print('Could not import gpiozero library. This could happen if your computer does not have GPIO pins.') from donkeypart_PCA9685_actuators import PWMSteering, PWMThrottle, PCA9685 import time class Sombrero: """ Part for custom donkey hat. """ def __in...
import torch import torch.nn as nn import dlutil as dl class MultiHeadAttention(nn.Module): def __init__(self, q_in_features, k_in_features, v_in_features, num_heads, d_model): super(MultiHeadAttention, self).__init__() self.num_heads = num_heads self.d_model = d_model assert d_mod...
import random _mrpt_num_trials = 5 # number of bases to test def is_prime(n): assert n >= 2 if n == 2: return True if n % 2 == 0: return False s = 0 d = n-1 while True: quotient, remainder = divmod(d, 2) if remainde...
from toolz.utils import raises from toolz.dicttoolz import merge, valmap, keymap, update_in, assoc inc = lambda x: x + 1 def test_merge(): assert merge({1: 1, 2: 2}, {3: 4}) == {1: 1, 2: 2, 3: 4} def test_valmap(): assert valmap(inc, {1: 1, 2: 2}) == {1: 2, 2: 3} def test_keymap(): assert keymap(inc...
from tortoise import Tortoise from .controllers import router def init(app): app.include_router(router, prefix="/items", tags=["Items"]) Tortoise.init_models(["app.items.models"], "items")
#!/usr/bin/env python __author__ = "bt3" """ Given an integer x and an unsorted array of integers, describe an algorithm to determine whether two of the numbers add up to x. 1. Using hash tables. 2. Sorting the array and keeping two pointers in the array, one in the beginning and one in the end. Whenever the sum of ...
import numpy import torch import torch.nn as nn import torch.nn.functional as F from . import BaseModel, register_model """ u_embedding: Embedding for center word. v_embedding: Embedding for neighbor words. """ @register_model('HERec') @register_model('Metapath2vec') class SkipGram(BaseModel): @classmeth...
from ..abstract_transformation import * from ..tasks import * import random import numpy as np class HomoglyphSwap(AbstractTransformation): """ Transforms an input by replacing its words with visually similar words using homoglyph swaps. """ def __init__(self, change=0.25, return_metadata=False): ...
# Generated by Django 2.2.2 on 2019-08-05 08:04 import sys from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # This file presents an interface for interacting with the Playstation 4 Controller # in Python. Simply plug your PS4 controller into your computer using USB and run this # script! # # NOTE: I assume in this script that the only joystick plugged in is the PS4 controller....
import smtplib import socket socket.setdefaulttimeout(30) def send(msg): try: sender="flames123@gmail.com" recevier="your mail-ID" pswrd="lbemgukarpljllys" server=smtplib.SMTP('smtp.gmail.com',587) server.ehlo() server.starttls() server.ehlo() server.l...
import os import pytest from cfiddle import * import cfiddle from fixtures import setup from util import skip_if_go_not_available def test_hello_world_build(setup): skip_if_go_not_available() src = code(r""" //export DoubleIt func DoubleIt(x int) int { return x * 2 } """, language="go") r ...
from utils import enc, dec from biliob import BiliobSpider from time import sleep from datetime import datetime import asyncio # url = 'https://space.bilibili.com/ajax/member/getSubmitVideos?mid={}&pagesize=10&page=1&order=pubdate' url = 'http://api.bilibili.com/x/space/arc/search?mid={}&ps=20&tid=0&pn=1&keyword=&orde...
#!/usr/bin/python # author: Jan Hybs import cihpc.artifacts.base as artifact_base import re class CollectModule(artifact_base.AbstractCollectModule): """ This module excepts a dictionary as a first and only argument to the method process It simply merges system wide information and given object tog...
# -*- coding: utf-8 -*- from ..logger import logger logger.debug("Started 'reading process/measure.py'") import os import numpy as np import pyqtgraph as pg from qtpy import QtWidgets, QtCore, QtGui from .. import global_vars as g from ..utils.BaseProcess import BaseProcess from ..utils.misc import save_file_gui from ...
datasheet = """0 High SDA0 SA5 PCLK - - - 1 High SCL0 SA4 DE - - - 2 High SDA1 SA3 LCD_VSYNC - - - 3 High SCL1 SA2 LCD_HSYNC - - - 4 High GPCLK0 SA1 DPI_D0 - - ARM_TDI 5 High GPCLK1 SA0 DPI_D1 - - ARM_TDO 6 High GPCLK2 SOE_N DPI_D2 - - ARM_RTCK 7 High SPI0_CE1_N SWE_N DPI_D3 - - - 8 High SPI0_CE0_N SD0 DPI_D4 - - - 9 L...
# Generated by Django 2.2.2 on 2019-06-13 17:57 import blog.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0001_initial'), ] operations = [ migrations.AlterField( model_name='blog', name='image', ...
# -*- coding: utf-8 -*- #!/bin/python import time import pandas as pd import boto3 import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Output, Event import plotly import plotly.graph_objs as go from fun import dynamo_scan, generate_graph # get the service re...
from worker import app from worker.utils import Mailer @app.task def hello_world(): mailer = Mailer(app.conf) mailer.send(recipient='petar.efnushev@keitaro.com', subject='Celery Periodic Task', body='Hello, World!')
from setuptools import setup, find_packages VERSION='0.1.0' long_description=''' An opinionated command line utility that provisions kubernetes clusters atop libvirt. ''' packages=[ 'installer', ] install_requires=[ 'click', 'libvirt-python', 'toml', 'jinja2', 'tabulate', ] def main(): ...
sum = 0 num = 0 for c in range(1,501): if c % 2 != 0: if c % 3 == 0: sum += c # este é um acumulador num += 1 # este é um contador print(sum,'é a soma') print(num,'repetições')
from datetime import datetime from typing import List class Row(): description: str = "" value: float = 0.00 def __init__(self, _desc:str, _value: float): self.value = _value self.description = _desc pass pass class Period(): date: datetime.date = None rows: List[R...
from abc import ABC, abstractmethod class ToolBase(ABC): @abstractmethod def write(self, name, text): pass class PenTool(ToolBase): def write(self, name, text): print(f'{name} (ручкой) {text}') class BrushTool(ToolBase): def write(self, name, text): print(f'{name} (кистью) ...
#!/usr/bin/env python # encoding: utf-8 from pyo import * import sys ############################################################## READY = True # Set to True when ready for the radio TITLE = "The Absurd Hat" # The title of the music ARTIST = "JT Hutton (hipnofoo)" # Your artist name DURATION = 240 ...
def BubbleSort(Iterator): """ 冒泡排序 """ a = list(Iterator) for i in range(len(a)): for j in range(len(a)-1-i): if a[j] > a[j+1]: a[j], a[j+1] = a[j+1], a[j] return a def InsertSort(Iterator): """ 插入排序 """ a = list(Iterator) for i in range(1, len(a)): ...
from bokeh.plotting import figure, show # prepare some data x = [1, 2, 3, 4, 5] y = [4, 5, 5, 7, 2] # create a plot p = figure( title="Customized grid lines example", sizing_mode="stretch_width", max_width=500, plot_height=250, ) # add a renderer p.line(x, y, line_color="green", line_width=2) # chan...
#!/usr/bin/env python from vtk import * reader1 = vtkXMLTreeReader() reader1.SetFileName("treetest.xml") reader1.Update() view = vtkIcicleView() view.SetRepresentationFromInput(reader1.GetOutput()) view.SetAreaSizeArrayName("size") view.SetAreaColorArrayName("level") view.SetAreaLabelArrayName("name") vie...
import os import sys import tempfile import yaml import zlib import numpy as np import simplejson as js import subprocess as sb from time import time,sleep from os import path from scipy.stats.mstats import mquantiles import scipy.stats.distributions as di try: from sklearn.lda import LDA from sklearn.svm impo...
from rest_framework import status from rest_framework.permissions import AllowAny from rest_framework.request import Request from rest_framework.response import Response from rest_framework.views import APIView class HealthCheckAPI(APIView): permission_classes = (AllowAny, ) def get(self, request: Request) -...
from plex import Plex from plex.lib import six from tests.core.helpers import read import responses # Set client configuration defaults Plex.configuration.defaults.server(host='mock') @responses.activate def test_recently_added(): responses.add( responses.GET, 'http://mock:32400/library/recentlyAdded', ...
import requests from json import loads def data_return(): data = loads(requests.get("https://simplecovidapi.herokuapp.com").text) return data['cases'], data['deaths'], data['recoveries']
#%% class InvalidDirectory(Exception): pass class APIError(Exception): pass # %%
# Reference from https://learnxinyminutes.com/docs/python/ # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 6. Classes # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # We use the "class" statement to ...
import requests from django.urls import reverse_lazy from directory_api_client import api_client def retrieve_regional_offices(postcode): response = api_client.exporting.lookup_regional_offices_by_postcode(postcode) response.raise_for_status() return response.json() def retrieve_regional_office(postcod...
# -*- coding: UTF-8 -*- DATE_FORMAT = "d. N Y" TIME_FORMAT = "H:i" DATETIME_FORMAT = DATE_FORMAT + " " + TIME_FORMAT + ":s" YEAR_MONTH_FORMAT = "m.Y" MONTH_DAY_FORMAT = "d.m." SHORT_DATE_FORMAT = "d.m.Y" SHORT_DATETIME_FORMAT = SHORT_DATE_FORMAT + " " + TIME_FORMAT FIRST_DAY_OF_WEEK = 1 DECIMAL_SEPARATOR = "," THOUSAN...
import urllib.request, urllib.parse, urllib.error from bs4 import BeautifulSoup import ssl #install bs4: pip install bs4 # https://pypi.python.org/pypi/beautifulsoup4 # http://www.py4e.com/code3/bs4.zip # and unzip it in the same directory as this file # ignore ssl cert error ctx = ssl.create_default_context() ctx.ch...
# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory # 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/LICEN...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Stripe import for Nottingham Hackspace Requires stripe, piecash Author: Matt Lloyd Copyright (c) 2019 Matt Lloyd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (th...
# -*- coding: utf-8 -*- import traceback from functools import wraps from queue import Queue from .utils import HelpOptions class SelfbotHook: def __init__(self, client, settings={}, commands={}, queue: Queue = None): self.client = client self.settings = settings self.commands...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # ----------------------------------------------------------------------------- # Copyright (c) 2016 The Regents of the University of California # # This file is part of kevlar (http://github.com/dib-lab/kevlar) and is # licensed under the MIT license: see LICENSE. # ----...
from django.core.management.base import BaseCommand from currency.tasks import _privat_4_years class Command(BaseCommand): help = 'Get currency rate for 4 years from privatbank' def handle(self, *args, **options): _privat_4_years.delay()
""" Viewer for an image stack. This viewer will run in an separate thread. Therefore it does not function in all versions of jupyter. Call the viewer with >>> from crackdect.visualization import show_images >>> show_images(stack) and navigate the viewer with the arrow keys <- and -> or the mouse wheel. Additional ...
import json import time from datetime import datetime from typing import List, Optional, Tuple from sqlalchemy import and_, desc, not_ from sqlalchemy.orm import Session from app.config import settings from app.constants.state import FinalStates, TaskState, TaskType from app.crud.base import CRUDBase from app.models....
# # Copyright (c) 2021 Czech Technical University in Prague. # # This file is part of Roadmaptools # (see https://github.com/aicenter/roadmap-processing). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free So...
# @Title: 不同路径 II (Unique Paths II) # @Author: KivenC # @Date: 2018-07-31 20:55:21 # @Runtime: 48 ms # @Memory: N/A class Solution: def uniquePathsWithObstacles(self, obstacleGrid): """ :type obstacleGrid: List[List[int]] :rtype: int """ R = len(obstacleGrid) if R <...
from django.db import models from django.conf import settings class Movie(models.Model): """Stores a single movie entry.""" title = models.CharField(max_length=200, blank=False) year = models.CharField(max_length=4) rated = models.CharField(max_length=255) released = models.CharField(max_length=2...
default_app_config = 'hivs_clients.apps.HivsClientsConfig'
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2017 Jon Levell <levell@uk.ibm.com> # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Distribution License v1.0 # which accompanies this distribution. # # The Eclipse Distribution License is...
"""Evaluation script for measuring model accuracy.""" import json import logging import pathlib import pickle import tarfile import numpy as np import pandas as pd import xgboost from sklearn.metrics import ( accuracy_score, precision_score, recall_score, confusion_matrix, roc_curve, ) logger = lo...
from tkinter import * from tkinter.ttk import * #import all from time import strftime import os import sys A = str(input(" press enter to continue ==> ")) root = Tk() root.title('Clock') #window # define time in the window def time(): string = strftime('%H:%M:%S %p') lbl.config(text = string) lbl.after(...
"""Setup the pylonsapp application""" import logging from pylonsapp.config.environment import load_environment log = logging.getLogger(__name__) def setup_app(command, conf, vars): """Place any commands to setup pylonsapp here""" load_environment(conf.global_conf, conf.local_conf) # Load the models ...
import matplotlib.pyplot as plt import numpy as np import cv2 from os import path import os cwd = os.getcwd() dirname = path.join(cwd, path.dirname(__file__)) class DIP: def hist_normalize(self, img, w_range=(0, 255)): '''直方图归一化''' min_, max_ = np.min(img), np.max(img) w_min, w_max = w_r...
# -*- coding: utf-8 -*- """ Created on Tue Apr 21 16:09:02 2020 @author: sandip """ # ============================================================================= # Program that checks data processed # ============================================================================= import psutil import time...
class Solution: def convertToBase7(self, num): """ :type num: int :rtype: str """ n, r = abs(num), '' while n: r = str(n % 7) + r n //= 7 r = r.lstrip('0') or '0' if num < 0: r = '-' + r return r if __name_...
# Copyright (c) 2021 Emanuele Bellocchia # # 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,...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
import base64 from io import BytesIO import joblib from PIL import Image from flask import Flask, jsonify, request, Response from flask_cors import cross_origin from feature_extraction import create_features_from_image app = Flask(__name__, static_url_path='') @app.get('/') @cross_origin() def index(): return ...
"""ExampleVal class. The purpose is to simplify conditional logic when evaluating schema DSLs.""" __all__ = ['Nullable'] class Nullable: def __init__(self, val): """ Args: val (val): Nullable bool, True or False """ self.val = val
# FIRST PROBLEM CHALLENGE GUI # SANTIAGO GARCIA ARANGO import tkinter as tk from tkinter import ttk import cv2 as cv import sol_1_A import sol_1_B import sol_2_A import sol_2_B import sol_3 import sol_4 import sol_5 import sol_6_A import sol_6_B TITLE = "SOLUTIONS" FONT_1 = ("Times New Roman",18,"bold") FONT_2 = ("T...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os, re, sys, argparse linesA = [] linesB = [] NumAtoms = 0 pattern0 = r"^\s*([0-9]*)" parser = argparse.ArgumentParser(description='Substracts or adds the grid data of two cube files.') parser.add_argument('CubeFileA', metavar='file1.cube', help='The first .cube...
import math from tester import assertRaises def almost_equal(actual, expected): return abs(actual - expected) < 0.00001 assert math.acos(0.57) == 0.9642904715818097 assert math.acos(1) == 0.0 assert math.acos(-1) == 3.141592653589793 assert math.acos(0) == 1.5707963267948966 assert math.acosh(45) == 4.499686190...
from django.contrib.auth.views import LoginView, LogoutView from django.shortcuts import render, reverse, redirect, get_object_or_404 from django.views.generic import TemplateView, CreateView from django.urls import reverse_lazy from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from acco...
from rdc.dic.test import TestCase from rdc.dic.loader.xml import SIMPLE_TYPES class SimpleTypesTestCase(TestCase): def test_bool(self): t = SIMPLE_TYPES['bool'] for v in 't', '1', 'True', 'on', 'yes': self.assertTrue(t(v)) self.assertTrue(t(v.upper())) self.assertTr...
from apscheduler.schedulers.background import BackgroundScheduler from pytz import utc import requests import rpyc from rpyc.utils.server import ThreadedServer from decouple import config import modbus_client as Modbus import logging import sys # Logger config # Outputs to stdout and supervisor takes care of logfil...
# -*- coding: utf-8 -*- """An implementation to get conditional independencies of an ADMG.""" import copy from functools import partial from itertools import chain, combinations, groupby from typing import Callable, Iterable, List, Optional, Sequence, Set, Tuple import networkx as nx from ananke.graphs import ADMG, ...
# Title : TODO # Objective : TODO # Created by: Wenzurk # Created on: 2018/2/2 name = "wenzurk ma" name = name.upper() print(name) name = name.lower() print(name) name = name.title() print(name)