content
stringlengths
5
1.05M
#!/usr/bin/python from load import LoadState, LoadHandler from sys import argv, stdout from base64 import b64encode def arr_join(arr): return ", ".join(map(lambda x: "\"{}\"".format(x), arr)) class Handler(LoadHandler): def load_file(self, state, file, packs, type): super(Handler, self).load_file(sta...
class OpplastException(Exception): """General exception class for opplast""" class VideoIDError(OpplastException): """Error for when Video ID is not found""" class ExceedsCharactersAllowed(OpplastException): """Exception for when given string is too long"""
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RRappdirs(RPackage): """An easy way to determine which directories on the users computer ...
#!/usr/bin/env python from __future__ import unicode_literals import argparse import io import json import xml.etree.ElementTree SubElement = xml.etree.ElementTree.SubElement XFACTOR = 20 YFACTOR = 20 XMARGIN = 5 YMARGIN = 5 FONT_SIZE = 15 BITMARKER_HEIGHT = 10 def layout(fields, width): """ Adds virtual...
#!/usr/bin/env python import time import os import re import sys import nltk from nltk.tokenize import sent_tokenize import string from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords import re from math import log10 file_input = None path = 'test_books' word_counts = {} number_of_terms_in_docum...
from lin.exception import Success from lin.redprint import Redprint from app.libs.jwt_api import member_login_required, get_current_member from app.models.comment import Comment from app.validators.v1.comment_forms import CommentContent comment_api = Redprint('comment') @comment_api.route('/product/<int:pid>', meth...
from tkinter import * import tkinter import first_face_dataset, registeruser, second_face_training, gallery import mysql.connector import tkinter.scrolledtext as scrolledtext from fpdf import FPDF from PIL import Image,ImageTk from tkinter import filedialog from tkinter import ttk from datetime import datetime #connec...
import argparse def init_argparser(step): parser = argparse.ArgumentParser( description=f'CLI for the {step} starbucks') parser.add_argument( 'load_path', type=str, help=f'Loading files for {step}') parser.add_argument( 'save_path', type=str, help=f'Saving files from {st...
#!/usr/bin/env python # # test_colourbutton.py - # # Author: Paul McCarthy <pauldmccarthy@gmail.com> # import wx import mock import pytest from . import run_with_wx, simclick import fsleyes_widgets.colourbutton as cb def test_Create(): run_with_wx(_test_Create) def _test_Create(): frame = wx.GetApp().Get...
from tests import TEST_ROLE, client def test_role_base(): response = client.get(f'/role/{TEST_ROLE}') assert response.status_code == 200 assert response.text.startswith("<html>\n <head>\n") assert response.text.count(TEST_ROLE) == 17
# Copyright 2017 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 applicable law or ag...
# Cryomagnetics_CS4, Cryomagnetics CS4 magnet power supply driver # Reinier Heeres <reinier@heeres.eu>, 2008 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or...
#Language Coverage languageDict = { 'Afrikaans':['Egrave','egrave','Eacute','eacute','Ecircumflex','ecircumflex','Edieresis','edieresis','Icircumflex','icircumflex','Idieresis','idieresis','napostrophe','Ocircumflex','ocircumflex','Ucircumflex','ucircumflex'], 'Albanian':['Ccedilla','ccedilla','Edieresis','edieresis']...
from django_object_actions import BaseDjangoObjectActions as ObjectActions from django.contrib import admin from django.contrib.admin import ModelAdmin, RelatedOnlyFieldListFilter from core.admin.utils import ( get_change_view_link, get_changelist_view_link, get_html_preview, get_image_preview ) from ...
"""Create the Flask app""" from flask import Flask, Request, abort, jsonify, make_response from denseedia.config import CONFIG from denseedia.routes import register_routes app = Flask(__name__) @app.errorhandler(404) def on_route_not_found(error): """Override the HTML 404 default.""" content = {"msg": "Pag...
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-12-22 13:16 from hanlp_common.constant import HANLP_URL OPEN_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_SMALL_ZH = HANLP_URL + 'mtl/open_tok_pos_ner_srl_dep_sdp_con_electra_small_20201223_035557.zip' "Electra (:cite:`clark2020electra`) small version of joint tok, pos, ner,...
"""Common code for the omics ingest.""" import base64 from contextlib import contextmanager import datetime import os import os.path import pathlib import subprocess # nosec import tempfile import typing import dateutil.parser from irods_capability_automated_ingest.sync_irods import irods_session from irods.meta imp...
from src.feature_extractor.interface import IBoWFeatureExtractor, IW2VFeatureExtractor from src.feature_extractor.impl import ( TFIDFFeatureExtractor, CountFeatureExtractor, FastTextFeatureExtractor, BERTFeatureExtractor, RobertaFeatureExtractor, )
from flask import Flask, request, jsonify from flask_restful import Resource, Api app = Flask(__name__) api = Api(app) def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): ...
# -*- coding: utf-8 -*- from numpy import pi def comp_torque(self, out_dict, N0): """Compute the electrical average torque Parameters ---------- self : Electrical an Electrical object out_dict : dict Dict containing all magnetic quantities that have been calculated in comp_parame...
# __author__ = "Mio" # __email__: "liurusi.101@gmail.com" # created: 5/20/21 4:55 PM from pathlib import Path from docx import Document Path('docx').mkdir(exist_ok=True) for file in Path('output_docx').glob('*.docx'): doc = Document(file) for i in doc.paragraphs: # print(i.text) cn_index = i.te...
import builtins from unittest import TestCase import mock from engine.game import InputHandler from engine.game.BattleEngine import BattleEngine from engine.pkmn.types.ClassicTypesRuleSet import ClassicTypesRuleSet from models.game.battle.BattleGameState import BattleGameState from models.game.trainer.PokemonTrainer i...
from faker.generator import Generator class MGenerator(Generator): def add_provider(self, provider, *args, **kwargs): """ 使add_provider支持传参给provider对象 """ if isinstance(provider, type): provider = provider(self, *args, **kwargs) self.providers.insert(0, provid...
import logging import copy import yfinance as yf import pandas as pd import numpy as np import pandas as pd from pypfopt import black_litterman from pypfopt.expected_returns import mean_historical_return from pypfopt.black_litterman import BlackLittermanModel from pypfopt.risk_models import CovarianceShrinkage from s...
import os import importlib import numpy as np from .helpers import util from .helpers.data import WSGenerator, WSRandGenerator from sim.helpers.util import get_path as get_network_path from sim.helpers.data import DataInfo def compute(args): network = args.NETWORK epoch = args.epoch anon = not args.inclu...
# -*- encoding: utf-8 -*- """ @File Name : verification.py @Create Time : 2021/7/14 21:00 @Description : @Version : @License : @Author : diklios @Contact Email : diklios5768@gmail.com @Github : https://github.com/diklios5768 @Blog : @Motto ...
import requests import datetime import fnmatch import re import logging import subprocess import os import sys from github import Github, Label REPO_NAME = 'AOSC-Dev/aosc-os-abbs' TARGET_LABEL = 'security' AFTER_DATE = datetime.datetime(2019, 11, 6, 0, 0, 0) TOKEN = os.getenv('TOKEN') CVE_PATTERN = r'(?:\*\*)?CVE IDs:...
# ***************************************************************************** # Copyright 2017 Karl Einar Nelson # # 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...
from __future__ import print_function import sys from AppKit import NSObject from PyObjCTools import AppHelper import vanilla class SimpleAppAppDelegate(NSObject): def applicationDidFinishLaunching_(self, notification): SimpleAppWindow() class SimpleAppWindow(object): def __init__(self): s...
import cv2 import numpy as np import os, re import face_recognition.api as face_recognition recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read('trainer/trainer_lbp.yml') cascadePath = "cascade_data/lbpcascade_frontalface.xml" faceCascade = cv2.CascadeClassifier(cascadePath) unidentified_image_dir = "../...
import soundset # create random score for C3~C5note == 130.8~523.3hz #-> score object s1 = soundset.score.random(length=32,tempo=120,beat=16,chord=3,pitch=3,register=25,random_state=None) # create score piano roll #-> 2-dim binaly numpy array, size of (length, 128) roll = s1.to_roll(ignore_out_of_range=False) assert...
## -*- coding: UTF8 -*- ## view.py ## Copyright (c) 2020 libcommon ## ## 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 us...
"""Add binvox_rw to PYTHONPATH Usage: import _init_binvox import binvox """ import os.path as osp import sys def add_path(path): if path not in sys.path: sys.path.insert(0, path) this_dir = osp.dirname(osp.realpath(__file__)) binvox_dir = osp.abspath(osp.join(this_dir, '..', 'libs', 'binvox-rw-...
# Recuerda que el radio es la mitad del diámetro. # Por otro lado, si nosotros quisieramos saber cuanto es 51 entre 17 lo podemos guardar en una variable # Resultado_Sorprendente = 51 / 17 # Y luego esa podemos usarla para otros calculos como: # Resultado_Sorprendete_2 = (Resultado_Sorprendente ** 2) * 11
from django.urls import path from . import views urlpatterns = [ path('', views.danmakuwall, name='danmakuwall'), ]
# -*- coding: utf-8 -*- import codecs import os, sys import copy import random import json import math import decimal import datetime import threading import exceptions import time import base64 import md5 from gevent import socket import urllib, urllib2, urlparse from socket import error import errno import subproces...
"""Main urls.py file for project.""" from django.conf.urls import patterns, include, url from django.contrib import admin import accounts.urls import core.urls import logs.urls import djangonumerics.urls admin.autodiscover() urlpatterns = patterns( '', url(r'', include(core.urls)), url(r'^logs/', include...
from spynnaker.pyNN.models.neuron.synapse_types.synapse_type_exponential \ import get_exponential_decay_and_init from spynnaker.pyNN.models.neural_properties.neural_parameter \ import NeuronParameter from spynnaker.pyNN.models.neuron.synapse_types.abstract_synapse_type \ import AbstractSynapseType from spy...
import elasticsearch, elasticsearch.helpers import iconclass from django.conf import settings import redis import time import json def go(): es = elasticsearch.Elasticsearch() esi = elasticsearch.client.IndicesClient(es) esi.delete(index=settings.ES_INDEX_NAME + '_en') init_index('en') def init_index...
from floodsystem.stationdata import build_station_list, update_water_levels from floodsystem.station import MonitoringStation from floodsystem.utils import sorted_by_key stations = build_station_list() update_water_levels(stations) names = [ 'Bourton Dickler', 'Surfleet Sluice', 'Gaw Bridge', 'Hemingfor...
''' This code is part of QuTIpy. (c) Copyright Sumeet Khatri, 2021 This code is licensed under the Apache License, Version 2.0. You may obtain a copy of this license in the LICENSE.txt file in the root directory of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. Any modifications or derivative wor...
from os import path import re from setuptools import setup def get_version(): text = open(path.join(path.dirname(__file__), "sphinx_affiliates", "__init__.py")).read() match = re.compile(r"^__version__\s*\=\s*[\"\']([^\s\'\"]+)", re.M).search(text) return match.group(1) with open("README.md") as readme:...
import json import math import os from math import * # noqa import bmesh import bpy import mathutils from bpy.props import StringProperty from bpy.types import Operator from shutil import copyfile, SameFileError # ExportHelper is a helper class, defines filename and # invoke() function which calls the file selector...
# -*- coding: utf-8 -*- """ Created on Fri Sep 30 15:49:39 2016 @author: TUD205099 """ #%% load modules import triple_dot import numpy as np import qtt from qtt.scans import makeDataset_sweep, makeDataset_sweep_2D import qcodes from qcodes import load_data #from qcodes.plots.pyqtgraph import QtPlot from qcodes.plots.q...
import requests import json import numpy as np import pandas as pd urla = "https://data.smartdublin.ie/cgi-bin/rtpi/realtimebusinformation" urlb = str(235) urlc = "&format=json" url = urla+urlb+urlc response = requests.get(urla) data = response.json() print(data) #create with json codedump from Dublin Bus API filen...
# Copyright 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import torch, glob, os from .sparseConvNetTensor import SparseConvNetTensor from .metadata import Metadata def toLongTenso...
import numpy as np import copy import multiprocessing as mpc import pandas as pd import functools as fct import os from .inference_utils import init_search_directory, dset_list_logl from .inference_utils import save_search_initial_setup from .inference_utils import generate_variated_par from .inference_utils import mc...
# -*- coding: utf-8 -*- # @Time : 2022 # @Author : Yong Zheng r""" NeuCMFw0 ################################################ References ----- Yong Zheng, Gonzalo Florez Arias. "A Family of Neural Contextual Matrix Factorization Models for Context-Aware Recommendations", ACM UMAP, 2022 Notes ----- 1). NeuCMFw0 has...
import json from datetime import datetime from datetime import timedelta #import fileinput import os import re import io class DataManipulation: def manipulate_timestamp(self, file_path, sourcetype, source): #print('Updating timestamps in attack_data before replaying') if sourcetype == 'aws:clo...
import collections class StreamHelper: """ Staticly available class with a bunch of useful variables. streamer: The name of the streamer in full lowercase streamer_id: The Twitch user ID of the streamer (a string) stream_id: The ID of the current stream. False if the stream is not live """ st...
import datetime as DT import numpy as NP import matplotlib.pyplot as PLT import matplotlib.colors as PLTC import scipy.constants as FCNST from astropy.io import fits from astropy.io import ascii from astropy.table import Table import progressbar as PGB import antenna_array as AA import data_interface as DI import geome...
""" Get the polyinterface objects we need. Currently Polyglot Cloud uses a different Python module which doesn't have the new LOG_HANDLER functionality """ from udi_interface import Custom,Node,LOG_HANDLER,LOGGER import logging # My Template Node from nodes import TemplateNode # IF you want a different log format ...
# Modified by Yulun Nie 11/25/2021 for version 0.1 #makes straight line import numpy as np import cv2 def get_points(img): # Set up points to return data = {} data['img'] = img.copy() data['lines'] = [] # Set the callback function for any mouse event # print(img) cv2.imshow("Image", img) ...
from os import environ, path environ['PYART_QUIET'] = '' conf_path = path.join(path.dirname(path.realpath(__file__)), 'pyart_config.py') environ['PYART_CONFIG'] = conf_path #conf = config.load_config(conf_path)
import argparse as argp SAVE_LIST_FILENAME = 'Lottery649_History.bin' SAVE_LIST_FILENAME_2 = 'SuperLotto638_History.bin' LOTTERY_NUM = 7 LOTTERY_HEIGHT = 64 EMBEDDED_CH = 64 LOTTERY_1_MAX_NUM = 49 LOTTERY_2_MAX_NUM = 38 # 0 ~ 6 TRAIN_NUM_INDEX = 0 CHECKPOINT_FILENAME = 'checkpoint{0}.ckpt'.format(TRAIN_NUM_...
def resolve(): ''' code here ''' N, K = [int(item) for item in input().split()] xs = [int(item) for item in input().split()] min_lr = 10**9 min_rl = 10**9 if N != K: for i in range(N-K+1): min_lr = min(min_lr, abs(xs[i]) + abs(xs[i+K-1] - xs[i])) min...
from app.models import yandex_translate, converter, opensubtitles, registration, learning_mode def register(email, username, hashed_password): return registration.register_user(email, username, hashed_password) class Controller(object): def __init__(self, yandex_translate_api_key): self._opensubtitl...
import json import os import boto3 from slack import WebClient from slack.errors import SlackApiError from data_access.dataRepos import MafiaSerializer, GameStateRepo from stateManagers.gameStateManager import Actions from models.player import Roles from models.gameState import States as GameStates from util.env import...
class Flow: def __init__(self, flow): self.flow = flow def isNextInFlow(self, next, currentName): current = self._getCurrent(currentName) if (current is None): return False return next in current['next'] def getRestOfFlow(self, currentName): current = se...
#-*- encoding:utf-8 -*- import sys import hashlib from hashlib import sha1 import hmac import base64 from socket import * import json, time, threading from websocket import create_connection import websocket from urllib import quote import logging reload(sys) sys.setdefaultencoding("utf8") logging.bas...
import unittest import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtTest import QTest from PyQt5 import Qt from PyQt5.QtCore import QSize from unittest import TestCase import main app = QApplication(sys.argv) class MemoryTest(unittest.TestCase): """Tests the memory scanner""" def setUp(self): ...
from project.user import User class Library: def __init__(self): self.user_records: 'user objects' = [] self.books_available: '{authors: [books]}' = {} self.rented_books: '{usernames: {book names: days left}}' = {} self.days_to_return_book: '{book_name: [days]}' = {} ...
from ..api import narrow_buttons, wide_buttons from django import template register = template.Library() @register.simple_tag def wide_social_buttons(request, title, url): return wide_buttons(request, title, url) @register.simple_tag def narrow_social_buttons(request, title, url): return narrow_buttons(reque...
cat_to_num_cluster = {"ladies palazzo": {"1 per set": 4, "1 / unit": 15, "1 per packet": 2}, "hmi touch panel": {"1 unit": 11}, "steam iron": {"1 / unit": 4, ...
# Generated by Django 2.1.3 on 2018-11-21 08:16 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), ] ope...
# Generated by Django 3.0.6 on 2020-05-20 16:45 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('entities', '0001_initial'), ] operations = [ migrations.AddField( model_name='questionset', name='was_send', ...
import os import sys sys.path.append( './' ) os.environ["TOKENIZERS_PARALLELISM"] = "false" import numpy as np import argparse import torch import torch.nn as nn from models.Transformers import PairSupConBert from training import PairSupConTrainer from dataloader.dataloader import pair_loader from utils.utils import...
"""Unit test for parsing.""" import unittest from fractions import Fraction from decimal import Decimal from integral.expr import Var, Const, Op, Fun, trig_identity from integral.parser import parse_expr class ParserTest(unittest.TestCase): def testParseTerm(self): test_data = [ "x", "1", "1...
""" """ import hashlib import hmac from html.parser import HTMLParser import logging import os from typing import Any, cast, Dict import urllib import urllib.parse from fastapi import Request from sqlalchemy.orm import Session from . import admin from .data import BroodUser from .models import ( SlackOAuthEvent, ...
#coding=utf-8 """ Description: 多文档格式转换工具 Author:伏草惟存 Prompt: code in Python3 env """ import os,fnmatch from win32com import client as wc from win32com.client import Dispatch,gencache ''' 功能描述:抽取文件文本信息 参数描述:1 filePath:文件路径 2 savePath: 指定保存路径 ''' def Files2Txt(filePath,savePath=''): try: # 1 切分文件上级目录和文件名...
# Copyright 2021 Rafał Safin (rafsaf). 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 applicabl...
import numpy as np import sys as sys try: from pycuda import cumath, driver, gpuarray, tools from pycuda.elementwise import ElementwiseKernel from scikits.cuda import cublas import pycuda.autoinit except Exception as e: sys.stderr.write("WARNING: Pycuda or cublas was not found on python path\n")
from rental.models import Car, Language, User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'lang', 'password', ) write_only_fields = ('password', ) def create(self, validated_dat...
from django import template register = template.Library() @register.filter def get_answer(offer, user): """Returns an user answer for the given offer""" if not user.is_authenticated: return None return offer.answers.filter(user=user).first()
from datetime import datetime from .Base import Base from . import db class Rental(Base): _ignored_fields = Base._ignored_fields + ['user_id', 'movie_id'] user_id = db.Column(db.ForeignKey('users.id')) movie_id = db.Column(db.ForeignKey('movies.id')) date_rented = db.Column(db.DateTime, default=date...
"""Support function for parsing JPL ephemeris text files. This is for parsing a NASA ephemeris text header file, like: ftp://ssd.jpl.nasa.gov/pub/eph/planets/ascii/de421/header.421 You can use this routine like this:: from jplephem.ascii import parse_header d = parse_header(open('header.421')) from ppr...
import torch import torch.nn as nn from bootstrap.lib.logger import Logger class ReduceLROnPlateau(): def __init__(self, optimizer, engine=None, mode='min', factor=0.1, patience=10, verbose=False, threshold=0.0001, thr...
from . import config as c from .basetypes import Vector2 import math def clamp(x, a, b): """Clamps value x between a and b""" return max(a, min(b, x)) def accelerate(obj, accel_x, accel_y, limit_x = None): """Accelerate until limit is reached""" obj.vel += Vector2(accel_x, accel_y) * c.delta_time ...
import socket def get_host_ip(): """Return the local IP address""" try: ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ss.connect(('8.8.8.8', 8070)) ip = ss.getsockname()[0] finally: ss.close() return ip
#!/usr/bin/env python from __future__ import print_function import logging import os, re import SimpleITK as sitk import radiomics from radiomics import featureextractor import json import csv import random from . import utils def tqdmProgressbar(): """ This function will setup the progress bar exposed by...
#!/usr/bin/python3 import os import sys from pymongo import MongoClient, errors class Mongo: def __init__(self, connectionString, databaseName, collectionName): self.connectionString = connectionString self.databaseName = databaseName self.collectionName = collectionName #Function ensu...
import os import vlc surahFiles = os.listdir("./") surahFiles.sort() j=0 while j<len(surahFiles): print "len: " + str(len(surahFiles)) + " j " + str(j) surahFile = surahFiles[j] print surahFile if not surahFile.endswith('.mp3'): j = j + 1 continue; #surahFile = "037-as-saffat.mp3" ...
# -*- coding: utf-8 -*- import pytest from todolist import create_app from todolist.services import todo as todo_service @pytest.fixture def app(): app = create_app() return app @pytest.fixture(scope='function', autouse=True) def reset_todo_list(): """Reset `todo_service._TODOS` state.""" todo_serv...
import platform import click from awsflock.parsing import Duration DEFAULT_DYNAMO_TABLE = "awsflock" def lease_duration_opt(func): return click.option( "--lease-duration", type=Duration(), default="2 hours", show_default=True, help=( "The duration of the leas...
import os import numpy as np import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') import matplotlib.pyplot as plt from networkx.drawing.nx_pylab import draw_spring from meta_graph import convert_to_original_graph from events import detect_events_given_path from util import load...
import math def circleArea(r): return math.pi*r*r print(circleArea(55)) print(math.pi)
import torch from torch import Tensor import math from .benchmarks import BenchmarkBase from botorch.utils.sampling import draw_sobol_samples class SineBenchmark(BenchmarkBase): """ One-dimensional sine function with two global optimizers with different noise level. Noise in the measurements is zero-mean ...
# Time: O(|V| + |E|) # Space: O(|E|) # There are a total of n courses you have to take, labeled from 0 to n - 1. # # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, # which is expressed as a pair: [0,1] # # Given the total number of courses and a list of prerequisite...
import os import re import sys import subprocess from termcolor import colored def __find_file_in_dir(directory, filename): if re.search(r'^~', directory): directory = os.path.expanduser(directory) matches = [] if os.path.isdir(directory): for root, dirs, files in os.walk(directory): ...
# Copyright 2019 Graphcore Ltd. import numpy as np import popart import time from functools import partial class PerfIntervalTimer: # Define a simple timer object: def __init__(self): self.time = None def not_set(self): return self.time is None def last(self): return self.tim...
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.3 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="view-in-github" colab_type="text" # <a href="https://colab...
import abc class BaseRepository: @abc.abstractmethod def init(self): pass @abc.abstractmethod def check(self): pass @abc.abstractmethod def eraise(self): pass @abc.abstractmethod def commit(self): pass @abc.abstractmethod def write_tags(self...
from django import forms # Form takes in input URLs from the user for the website whose articles they want to see. class URLForm(forms.Form): url1 = forms.URLField(initial="https://bbc.co.uk") url2 = forms.URLField(initial="https://apnews.com") url3 = forms.URLField(initial="https://reuters.com")
# Print the following pattern lastNumber = 6 for row in range(1, lastNumber): for column in range(1, row+1): # end=" " is for space, only comma will new line print(column, end=" ") print(" ") # print with black string means newline
import re from functools import partial from django.contrib.auth.models import BaseUserManager generate_random = partial(BaseUserManager.make_random_password.im_func, None) def string_to_css_class(string): 'Convert a string to a format useful for use as a css class.' if not string: return '' r...
from django.template.loader import render_to_string from django.utils.html import format_html from cms.app_base import CMSAppConfig, CMSAppExtension from djangocms_alias.models import AliasContent from djangocms_versioning.constants import DRAFT from djangocms_version_locking.helpers import version_is_locked def a...
# -*- coding: utf-8 -*- """ /*************************************************************************** LithicEdgeWear A QGIS plugin This plugin quantifies lithic edge wear ------------------- begin : 2017-10-30 git sha ...
from .paddings import ZeroPadding, Pkcs7Padding from .rijndael import Rijndael, RijndaelCbc __version__ = '0.3.3'
from net_models.fields import GENERIC_OBJECT_NAME, PRIVILEGE_LEVEL, AAA_METHOD_NAME from net_models.models.BaseModels import BaseNetModel, VendorIndependentBaseModel from pydantic import root_validator from pydantic.types import PositiveInt from pydantic.typing import Optional, List, Literal, Union def enable_action_...
import datetime import numpy as np import pandas as pd import tkinter as tk from selenium import webdriver from typing import List, Dict, Any from .classWidget import Widget from .classLogger import Logger from .classSettings import Settings logger = Logger(__name__, Settings.LOGGER) class WidgetBins(Widget): de...