content
stringlengths
0
894k
type
stringclasses
2 values
from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status, viewsets from profiles_api import serializer, models class HelloApiView(APIView): """Test API View""" serializer_class = serializer.HelloSerializer ...
python
""" [caption] def=Cutting URL parameters ja=URLパラメータの切り取り """ import sys import io import tkinter import tkinter.ttk import tkinter.simpledialog import ctypes import ctypes.wintypes from urllib.parse import urlparse, parse_qsl, urlencode, urlunparse sys.stdin = io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8') sys...
python
# coding: utf-8 from __future__ import unicode_literals from django.test import TestCase class ComputeIntersectionsTestCase(TestCase): def test_command(self): pass # @todo
python
#!/usr/bin/env python # ---------------------------------------------------------------------------- # Copyright 2015-2016 Nervana Systems Inc. # 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 #...
python
"""Define resize, blur, and related constants.""" from . import io from collections import namedtuple from numba import guvectorize import math import numpy as np RowOps = namedtuple('RowOps', 'tindices sindices fweights'.split()) GAUSSIAN_SCALE = 1.0 / np.sqrt(0.5 * np.pi) def hermite(x): x = np.clip(x, 0, 1) ...
python
# Generic imports import os import random import shutil from datetime import datetime # Imports with probable installation required try: import progress.bar except ImportError: print('*** Missing required packages, I will install them for you ***') os.system('pip3 install progress') import progress.b...
python
# -*- coding: utf-8 -*- """ Created on Tue Nov 2 10:54:54 2021 @author: po-po """ import numpy as np import matplotlib.pyplot as plt import pandas as pd import os #filename = r'C:\Users\po-po\Desktop\DOC\Fibras\Programas\data\dr2todr4e01121121.csv' filename = r'C:\Users\po-po\Desktop\DOC\Fibras\Program...
python
# Copyright (c) 2022 Aiven, Helsinki, Finland. https://aiven.io/ import sys from unittest import mock import pytest from pghoard import postgres_command def test_restore_command_error(): with mock.patch("pghoard.postgres_command.http_request", return_value=500): with pytest.raises(postgres_command.PGCE...
python
# This file is part of the Reference Data Repository (refdata). # # Copyright (C) 2021 New York University. # # refdata is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Loader implementation for datasets that are given in Json format...
python
from django.test import TestCase from whats_fresh.whats_fresh_api.models import Video from django.contrib.gis.db import models class VideoTestCase(TestCase): def setUp(self): self.expected_fields = { 'video': models.URLField, 'caption': models.TextField, 'name': models...
python
import os import json import torch import numpy as np from PIL import Image import copy import os import logging from detectron2.data import detection_utils as utils from ..registry import DATASOURCES from .load_coco import load_coco_json @DATASOURCES.register_module class COCO_BOXES(object): def __init__(self,...
python
from __future__ import absolute_import, division, print_function import os from pdfx import cli # import pytest curdir = os.path.dirname(os.path.realpath(__file__)) def test_cli(): parser = cli.create_parser() parsed = parser.parse_args(['-j', 'pdfs/valid.pdf']) assert parsed.json assert parsed.pdf ...
python
#!/usr/bin/env python # # This script is experimental. # # Liang Wang @ Dept. Computer Science, University of Helsinki # 2011.09.21 # import os, sys import socket import pickle import random import Queue import time import threading import resource from khash import * from bencode import bencode, bdecode from common...
python
import itertools import json import logging import os import subprocess import sys import warnings from collections import OrderedDict from pathlib import Path import click import pip_api import requests from cachecontrol import CacheControl # from pipdownload.settings import SETTINGS_FILE from pipdownload import logg...
python
# -*- coding: utf-8 -*- # Copyright (C) 2013-2017 Oliver Ainsworth # Modifications (remove py2) by (C) Stefan Tapper 2021 import enum import itertools import rf2settings.valve from rf2settings.valve import messages, util REGION_US_EAST_COAST = 0x00 REGION_US_WEST_COAST = 0x01 REGION_SOUTH_AMERICA = 0x02 REGION_EUROP...
python
#!/usr/bin/env python # -*- coding: UTF-8 -*- import os import platform import re from setuptools import setup, Extension python_version = platform.python_version() system_name = platform.system() print("build for python{} on {}".format(python_version, system_name)) # Arguments actrie_dir = "" alib_dir = "" def ge...
python
# @author kingofthenorth # @filename problemsearch.py # @description Assignment 2 # @class CS 550 # @instructor Roch # @notes N/A from collections import deque from basicsearch_lib02.queues import PriorityQueue from basicsearch_lib02.searchrep import (Node, Problem) from explored import Exp...
python
# @name: Katana-DorkScanner # @repo: https://github.com/adnane-X-tebbaa/Katana # @author: Adnane-X-tebbaa (AXT) # Scada-file V2.2 # I used dorks for the most used PLCs """ MIT License Copyright (c) 2020 adnane tebbaa Permission is hereby granted, free of charge, to any person obtaining a copy of t...
python
import sqlite3 from functools import partial import multiprocessing as mp def create(args): p,name,sql = args db = sqlite3.connect(name) db.execute(sql) class mydb: def __init__(self, w): self.pool = mp.Pool(w) def create(self, tab, name_tmpl, parts=[0]): sql = 'create table if not exists {}'.format(tab) ...
python
#!/usr/bin/env python """ Hacky script for comparing output set to gold set. Usage: just run python compare_solution.py -h """ import argparse import fileinput import sys import re def compare_sets(s1, s2): """Compare the sets.""" if len(s1) != 0: # return s1 == s2 return s1 - s2 return ...
python
import logging from airflow.decorators import dag, task from datetime import datetime, timedelta from airflow.utils.dates import days_ago from airflow.providers.amazon.aws.operators.dms_create_task import DmsCreateTaskOperator from airflow.providers.amazon.aws.operators.dms_start_task import DmsStartTaskOperator from ...
python
import numpy as np s = '''73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511 12540698747158523863050715693290963295227443043557 66896648950445244523161731856403098711121722383113 ...
python
# step: build the vectorizer for year_month + general, f > 2, ngram = 3 # import os from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import SGDClassifier import numpy as np import pickle from sklearn.metrics import classification_report, f1_score from scipy.sparse import lil_matrix...
python
# --------------------------------------------------------------------------- # import os import filecmp from arroyo import utils import pytest # --------------------------------------------------------------------------- # # Asymmetric Key Tests from arroyo.crypto import KeyAlgorithmType, EncodingType from arr...
python
""" Copyright 2020 The OneFlow 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 applicable law or agr...
python
def solution(arrows): answer = 0 coorL = [[0,0]] for each in arrows: if each == 0: a = [int(coorL[-1][0]), int(coorL[-1][1])+1] elif each == 1: a = [int(coorL[-1][0])+1, int(coorL[-1][1])+1] elif each == 2: a = [int(coorL[-1][0])+1, int(coorL[-1...
python
from django.urls import reverse from rest_framework import status from cornershop.apps.weather.tests import WeatherAPTestCase class WeatherPostTestCase(WeatherAPTestCase): def test_with_existing_record(self): url = reverse('weather-list') response = self.client.get(url, format='json') ...
python
"""Utilities for algebraic number theory. """ from sympy.core.sympify import sympify from sympy.ntheory.factor_ import factorint from sympy.polys.domains.rationalfield import QQ from sympy.polys.domains.integerring import ZZ from sympy.polys.matrices.exceptions import DMRankError from sympy.polys.numberfields.minpoly ...
python
import enum import os from argparse import ArgumentParser import tensorflow as tf import create_mask_image tf.logging.set_verbosity(tf.logging.INFO) logger = tf.logging home = os.path.expanduser("~") class TrainingPaths(enum.Enum): MASK = 0, ORIGINAL_IMAGE = 1, MASKED_IMAGE = 2 PATHS = { TrainingPaths....
python
from __future__ import absolute_import, unicode_literals from .extras.clients import WebApplicationPushClient from .extras.grant_types import AuthorizationCodePushGrant from .extras.endpoints import Server from .extras.errors import MalformedResponsePushCodeError
python
from functools import wraps import logging import math import time from typing import Callable logger = logging.getLogger() def format_seconds(seconds: int): seconds = int(seconds or 0) hours = math.floor(seconds / 3600) seconds -= hours * 3600 minutes = math.floor(seconds / 60) seconds -= minu...
python
#!/usr/bin/env python import RPi.GPIO as GPIO import subprocess import time SENSOR_PIN = 14 TIME_ON = 20 def main(): GPIO.setmode(GPIO.BCM) GPIO.setup(SENSOR_PIN, GPIO.IN) subprocess.run(['xset', 'dpms', 'force', 'off']) def callback(_): subprocess.run(['xset', 'dpms', 'force', 'on']) ...
python
"""Testing v0x04 FlowRemoved message.""" from pyof.v0x04.asynchronous.flow_removed import FlowRemoved from pyof.v0x04.common.flow_match import Match from tests.test_struct import TestStruct class TestFlowRemovedMsg(TestStruct): """FlowRemoved message tests (also those in :class:`.TestDump`).""" @classmethod ...
python
import enum from ..time import Resolution, UTC class Curve: """ The curve identifies any type of time series data and OHLC data. The ``curve.name`` is used in the API when loading data for a curve. """ def __init__(self, name, curve_type=None, instance_issued_timezone=None, are...
python
#! python3 import sys, PyQt5 from PyQt5.QtWidgets import QWidget, QLabel, QLineEdit, QApplication class Example(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.label = QLabel(self) qle = QLineEdit(self) qle.m...
python
# coding=utf-8 # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. # FIpurE: This is odd... import sys import os from grpc._cython.cygrpc import StatusCode from pur.core.purnode import purNode from pur.generated.purbase_pb2 import G...
python
# -*- coding: utf-8 -*- import sys import time timer = time.clock if sys.platform[:3] == 'win' else time.time def total(reps, func, *args, **kwargs): """Total time to run func() reps times. Returns (total time, last result) """ repslist = list(range(reps)) start = timer() for i in repslist:...
python
"""Platform to present any Tuya DP as a binary sensor.""" import logging from functools import partial import voluptuous as vol from homeassistant.components.binary_sensor import ( DEVICE_CLASSES_SCHEMA, DOMAIN, BinarySensorEntity, ) from homeassistant.const import CONF_DEVICE_CLASS from .common import Lo...
python
#!/usr/bin/env python3 from utils import mathfont import fontforge # Create a WOFF font with glyphs for all the operator strings. font = mathfont.create("stretchy", "Copyright (c) 2021 Igalia S.L.") # Set parameters for stretchy tests. font.math.MinConnectorOverlap = mathfont.em // 2 # Make sure that underover para...
python
# Copyright (C) 2018 The python-bitcoin-utils developers # # This file is part of python-bitcoin-utils # # It is subject to the license terms in the LICENSE file found in the top-level # directory of this distribution. # # No part of python-bitcoin-utils, including this file, may be copied, # modified, propagated, or d...
python
legal_labels = ["west-germany", "usa", "france", "canada", "uk", "japan"] label_name = "places" MAX_NUM_WORDS = 10000 MAX_SEQ_LENGTH = 100 EMBEDDING_DIM = 50
python
from django.conf.urls import url from . import views from django.contrib.auth.views import LoginView, LogoutView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView app_name = 'account' urlpatterns = [ url(r'^$', LoginView.as_view(template_name='account/welcome.html'), name='welcome_page'), ur...
python
import numpy as np from astropy.io import fits import matplotlib.pyplot as plt source = 'NGC3351' line = np.array(('CO10','CO21','13CO21','13CO32','C18O21','C18O32')) num = line.shape[0] for i in range(num): fits_map = fits.open('data_image/'+source+'_'+line[i]+'_mom0_broad_nyq.fits')[0].data fits_err = fits....
python
import pytest import grblas as gb import dask_grblas as dgb from grblas import dtypes from pytest import raises from .utils import compare def test_new(): s = gb.Scalar.new(int) ds = dgb.Scalar.new(int) compare(lambda x: x, s, ds) s = gb.Scalar.new(float) ds = dgb.Scalar.new(float) compare(lam...
python
# -*- coding: utf-8 -*- """This file contains the wifi.log (Mac OS X) parser.""" import logging import re import pyparsing from plaso.events import time_events from plaso.lib import errors from plaso.lib import eventdata from plaso.lib import timelib from plaso.parsers import manager from plaso.parsers import text_p...
python
# chebyfit/__init__.py from .chebyfit import __doc__, __all__, __version__ from .chebyfit import *
python
from typing import Generator, Mapping, Union from flask_babel import lazy_gettext from app.questionnaire.location import Location from .context import Context from .section_summary_context import SectionSummaryContext class SubmitQuestionnaireContext(Context): def __call__( self, answers_are_editable: ...
python
def get_answer(): """something""" return True
python
# Copyright (c) 2015, Michael Boyle # See LICENSE file for details: <https://github.com/moble/scri/blob/master/LICENSE> from __future__ import print_function, division, absolute_import import pytest import numpy as np from numpy import * import quaternion import spherical_functions as sf import scri from conftest im...
python
from apiaudio.api_request import APIRequest class Connector(APIRequest): OBJECT_NAME = "connector" resource_path = "/connector/" connection_path = "/connection/" @classmethod def retrieve(cls, name): if not name: raise Exception("Name must be set") return cls._get_requ...
python
import unittest from rime.util import struct class TestStruct(unittest.TestCase): def test_dict_attr(self): self.assertEqual(struct.Struct.items, dict.items) def test_constructor(self): s = struct.Struct(test_attr='test_obj') self.assertEqual(s.test_attr, 'test_obj') self.ass...
python
import pandas as pd from calendar import isleap def get_date_range_hours_from_year(year): """ creates date range in hours for the year excluding leap day :param year: year of date range :type year: int :return: pd.date_range with 8760 values :rtype: pandas.data_range """ date_rang...
python
from collections import defaultdict import nltk import random import string import torch from nltk.corpus import stopwords from pytorch_pretrained_bert import BertTokenizer, BertForMaskedLM from tqdm import tqdm device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print('Initialize BERT vocabulary......
python
from .FeatureSet import FeatureSet class Version(FeatureSet): def __init__(self, api, internalIdentifier, identifier, versionString, apiString): super(Version, self).__init__(api, internalIdentifier) self.nativeIdentifier = identifier self.apiString = apiString self.majorVersion, s...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
python
#!/usr/bin/python import dnaseq import bm_preproc import kmer_index human_chromosome = dnaseq.read_genome("chr1.GRCh38.excerpt.fasta") def approximate_matches(p, t, index): n = 2 matches = set() total_hits = 0 for i in range(0, 24, 8): pi = p[i:i+8] hits = index.query(pi); total_hits += len(hits) for hi...
python
from .baselines import * from .cocostuff import * from .potsdam import * from .duckietown import *
python
import os import sys import tempfile from unittest import mock from hashlib import sha1 from random import random from io import StringIO import argparse from .base import BaseTest from .. import cloudssh class Test(BaseTest): fake_reservations = [ { 'Groups': [], 'Instances': ...
python
#!/usr/bin/env python from glob import glob import re from collections import Counter import subprocess32 as sp import string from itertools import product from sys import stderr from time import time def split_regions_file(boot_contigs_dict, fnames, size): """ takes Counter dictionary of bootstrapped contigs...
python
import tempfile from django.urls import reverse from PIL import Image from rest_framework import status from rest_framework.test import APITestCase from brouwers.users.tests.factories import UserFactory from ..factories import AlbumFactory, PhotoFactory class PhotoViewsetTests(APITestCase): def setUp(self): ...
python
""" MIT License Copyright (c) 2020 Shahibur Rahaman """ import Operations import time def main(): print( """ Calculator version 2.9.10.20 Copyright (c) Shahibur Rahaman Licensed under the MIT License. |> Press (Ctrl + C) to exit the program. |> Choose your operation: 1. Addition 2. Subtraction 3. Mul...
python
import sys import json from data_grab.run_scraper import Scraper if(len(sys.argv)<2): print('Please Give topic name. e.g. "Clock"') sys.exit() topic = sys.argv[1] data_obj = False j_data = json.loads(open('data_grab/resources/topic_examvida.json').read()) for c in j_data: if topic == c["topic_name"]: ...
python
from views.main_view import prompt prompt()
python
#!/usr/bin/env python # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ A clone of 'pmap' utility on Linux, 'vmmap' on OSX and 'procstat -v' on BSD. Report memory map of a process. $ python scripts/p...
python
# coding=utf-8 # Copyright 2021-present, the Recognai S.L. team. # # 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 ...
python
# Copyright (c) 2018, Manfred Moitzi # License: MIT License import pytest import os import ezdxf BASEDIR = 'integration_tests' if os.path.exists('integration_tests') else '.' DATADIR = 'data' COLDFIRE = r"D:\Source\dxftest\CADKitSamples\kit-dev-coldfire-xilinx_5213.dxf" @pytest.mark.skipif(not os.path.exists(COLDFIR...
python
def run(): my_range = range(0, 7, 2) print(my_range) other_range = range(0, 8, 2) print(other_range) print(id(my_range)) print(id(other_range)) print(my_range == other_range) # Validate (value equality) print(my_range is other_range) # Validate (object equality) # Par for...
python
from fastapi import APIRouter, Depends from typing import List from src.utils.crud_router import include_generic_collection_document_router from src.dependencies import current_active_user from src.services.courses import CourseService, CourseSectionService dependencies: List[Depends] = [Depends(current_active_user)]...
python
from typing import Dict, Text, Any, List import tensorflow_transform as tft def preprocessing_fn(inputs: Dict[Text, Any], custom_config) -> Dict[Text, Any]: """tf.transform's callback function for preprocessing inputs. Args: inputs: map from feature keys to raw not-yet-transformed features. custo...
python
import numpy as np import tensorflow as tf from datasets import audio from infolog import log from wavenet_vocoder import util from wavenet_vocoder.util import * from .gaussian import sample_from_gaussian from .mixture import sample_from_discretized_mix_logistic from .modules import (Conv1D1x1, ConvTranspose2D, ConvTr...
python
"""Testing for vault_backend module.""" import hvac import pytest import requests import config import vault_backend def test___get_vault_client(monkeypatch): # valid test client = vault_backend.__get_vault_client('salesforce') assert isinstance(client, hvac.Client) # test w/ no VAULT_CERT def m...
python
#==================================================================================== # TOPIC: PYTHON - Modules Usage #==================================================================================== # # FILE-NAME : 013_module_usage.py # DEPENDANT-FILES : These are the files and libraries needed to run this p...
python
from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from colorful.fields import RGBColorField from mayan.apps.acls.models import AccessControlList from mayan.apps.databases.model_mixins import ExtraDataModelMixin from mayan.apps.events.classes import Ev...
python
"""Common run function which does the heavy lifting of formatting output""" import csv import enum import itertools import logging import typing from notions.flatten import flatten_item from notions.models.database import Database from notions.models.page import Page, PageTitleProperty from . import yaml from .confi...
python
import numpy as np import pickle from natasha import ( Doc, Segmenter, NewsEmbedding, NewsMorphTagger, MorphVocab ) from navec import Navec from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler from telegram import Bot as Bot_ from metrics import metric PAT...
python
from django.apps import AppConfig class CityeventConfig(AppConfig): name = 'cityEvent'
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import arrow from app import celery, create_app from app.models.email_event import EmailEvent from app.email import send_email @celery.task def schedule_send_emails(): now = arrow.utcnow().replace(second=0, microsecond=0) app = create_app(os.getenv('JU...
python
# Command Line Interface import argparse as ap import datetime as dt import inflationtools.main as main from argparse import RawTextHelpFormatter # Allows to use newline in help text import locale import gettext # Unable to get pot for this file... find the reason. pt = gettext.translation('CLI', localedir='locales', ...
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-28 15:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('book', '0008_book_type'), ] operations = [ migrations.AddField( ...
python
#!/usr/bin/python3 def islower(c): chrcode = ord(c) if chrcode >= 97 and chrcode <= 122: return True else: return False
python
import json import os import time import pandas as pd from bing import bing_web_search def crawl_snippets(title, retry=3): _, raw_resp = bing_web_search(title) response = json.loads(raw_resp) for _ in range(retry): try: pages = response['webPages']['value'] return '\n'.joi...
python
import base64 from unittest.mock import ANY import pytest from rhub.auth.keycloak import KeycloakClient from rhub.api import DEFAULT_PAGE_LIMIT API_BASE = '/v0' def test_token_create(client, keycloak_mock): keycloak_mock.login.return_value = {'access_token': 'foobar'} rv = client.post( f'{API_BAS...
python
from corehq.apps.commtrack.const import COMMTRACK_USERNAME from corehq.apps.users.util import DEMO_USER_ID, SYSTEM_USER_ID from corehq.pillows.utils import ( COMMCARE_SUPPLY_USER_TYPE, DEMO_USER_TYPE, MOBILE_USER_TYPE, SYSTEM_USER_TYPE, WEB_USER_TYPE, ) from corehq.warehouse.loaders import ( App...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 15 11:52:31 2019 @author: tgadfort """ import sys import re from datetime import timedelta from playTypes import playtype # create logger import logging module_logger = logging.getLogger('log.{0}'.format(__name__)) ##############################...
python
""" Abstractions for lazy compositions/manipulations of And Inverter Graphs. """ from __future__ import annotations from typing import (Union, FrozenSet, Callable, Tuple, Mapping, Sequence, Optional) import attr import funcy as fn from bidict import bidict from pyrsistent import pmap from pyrsist...
python
import numpy as np import xobjects as xo import xpart as xp # Create a Particles on your selected context (default is CPU) context = xo.ContextCupy() part = xp.Particles(_context=context, x=[1,2,3]) ############## # PANDAS/HDF # ############## # Save particles to hdf file via pandas import pandas as pd df = part.to...
python
# proxy module from pyface.i_file_dialog import *
python
import unicodedata from django.utils.timezone import make_aware from eagle.models import EDINETCompany, EDINETDocument class EDINETDocumentRegister(): @classmethod def register_document(cls, document, xbrl_path, pdf_path): def normalize(text): if text is not None: return ...
python
import asyncio import aiohttp import json async def pollForex(symbols, authkey): i = 0 while True: symbol = symbols[i % len(symbols)] try: async with aiohttp.ClientSession() as session: async with session.get( url="https://api-fxpractice.oanda...
python
import os import sys import glob import random import math import datetime import itertools import json import re import logging # from collections import OrderedDict import numpy as np from scipy.stats import multivariate_normal # import scipy.misc import tensorflow as tf # import keras import keras.backend as KB imp...
python
from django.contrib import admin from forums.models import Category from guardian.admin import GuardedModelAdmin class CategoryAdmin(GuardedModelAdmin): list_display = ('title', 'parent', 'ordering') list_display_links = ('title',) admin.site.register(Category, CategoryAdmin)
python
# transaction_model.py # # ATM MVC program # # Team alroda # # Aldrich Huang A01026502 2B # Robert Janzen A01029341 2B # David Xiao A00725026 2B import datetime import os class TransactionModel: _TRANSACTION_COLUMNS = 'date,uid,account_type,account_number,transaction_type,amount' def __init__(self): ...
python
#!/usr/bin/python3.5 """ Command line utility to extract basic statistics from a gpx file """ import pdb import sys as mod_sys import logging as mod_logging import math as mod_math import gpxpy as mod_gpxpy #hack for heart rate import xml.etree.ElementTree as ET #heart rate statistics import numpy as np import o...
python
import matplotlib.pyplot as plt, sys sys.path.insert(0, '..') from Louis.misc import * from Louis.ARC_data.objects import * from Louis.grids import * from Louis.unifying import * def show_pb(name, n=17): l, i = reversed(pickle_read(name)), 0 for pb, p, c_type in l: i += 1 if i % n == 0: ...
python
import re import csv from io import BytesIO from zipfile import ZipFile import requests from ._version import __version__ URLHAUS_API_URL = 'https://urlhaus.abuse.ch/downloads/' REGEX_CSV_HEADER = re.compile(r'^#\s((?:[a-z_]+,)+(?:[a-z_]+))\r', re.MULTILINE) REGEX_HOSTFILE_DOMAIN = re.compile(r'^127\.0\.0\.1\t(.+)...
python
from enum import Enum from typing import List, NewType TeamID = NewType("TeamID", int) class RoleType(Enum): PLANNER = 0 OPERATOR = 1 LINKER = 2 KEYFARMING = 3 CLEANER = 4 FIELD_AGENT = 5 ITEM_SPONSOR = 6 KEY_TRANSPORT = 7 RECHARGING = 8 SOFTWARE_SUPPORT = 9 ANOMALY_TL = 1...
python
#!/usr/bin/env python # Copyright 2015 Ufora Inc. # # 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 applic...
python
import os import shutil import datetime import functools import subprocess import xml.etree.ElementTree as ET import numpy as np import torch import logging from util.misc import all_gather from collections import OrderedDict, defaultdict class OWEvaluator: def __init__(self, voc_gt, iou_types, args=None, use_07_...
python
# a method for obtaining a rough estimate of species richness on islands with transient dynamics # check it gives reasonable estimates import numpy as np import matplotlib.pyplot as plt import pandas as pd # check a range of parameter values # --- # where to save results dir_results = '../../../results/verify/test...
python
#!/usr/bin/env python3 import rospy from nav_msgs.msg import Path, Odometry from geometry_msgs.msg import PoseStamped, Point, Quaternion, Twist from controller_copy import Controller class Test(): def __init__(self): self.odom_topic = "/odom" self.target_path = Path() self.target_path.pos...
python