content
stringlengths
5
1.05M
"""Some example calculations for a CHARA beam combiner, to be fabricated in Chalcogenide by Harry.""" from __future__ import division, print_function import numpy as np import matplotlib.pyplot as plt import opticstools as ot plt.ion() L=1585 D=1500 BendRad=180 L=890 D=800 BendRad=200 #-----------...
# coding=utf-8 # Copyright 2021 DeepMind Technologies Limited. # # 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...
import numpy as np from astropy import log from astropy import units as u from scipy import ( conjugate, polyfit, ) from skimage.transform import resize from scipy.fftpack import fft, ifft class Image(object): '''Low level class which handles the image transformations and cross correlation with anothe...
import numpy as np import matplotlib.pyplot as plt log = np.append(np.full((45), np.nan),np.full((10),0)) green1 = np.append(np.full((20), np.nan),np.full((60),0.1)) green2 =np.append(np.full((24), np.nan),np.full((52),0.12)) bg_color = '0.5' fig = plt.figure(facecolor=bg_color) axes = fig.add_subplot(111) axes.pat...
# -*- coding: utf-8 -*- from selenium import webdriver import unittest from contact import Contact class UntitledTestCase(unittest.TestCase): def setUp(self): self.wd = webdriver.Firefox() self.wd.implicitly_wait(30) def test_add_contact(self): wd = self.wd self.login(username=...
from analyze_text import az_get_keywords from analyze_key import az_get_links_for_key from collections import Counter if __name__ == "__main__": realTxt = 'DRINGEND!!!! Sag bitte allen Leuten in deiner WhatsUp-Liste, dass sie den Kontakt "Tobias Mathis" nicht annehmen sollen! Das ist ein Virus (über WhatsUp) der di...
# SPDX-License-Identifier: BSD-3-Clause # # flake8: noqa=F401 """ This module provides the :py:class:`~depthcharge.hunter.Hunter` base class and its associated implementations. In Depthcharge parlance, a *"Hunter"* is class that searches data for items of interest and either provides information about located instanc...
import os import xmltodict from setuptools import setup, find_packages def clean(): """Cleans the source directory of all non-source files. """ os.system('rm -rf .coverage') os.system('find . -name "__pycache__" -print0|xargs -0 rm -rf') os.system('find . -name "*.egg-info" -print0|xargs -0 rm -r...
# Stub for Ordinary Differential Equations
from typing import Dict, Optional from jsonschema import validate from openapi.spec import SchemaParser def validate_config( config: Dict, schema: Dict, defaults: bool = False ) -> Optional[Dict]: if schema: additional = schema.get("additionalProperties") schema["additionalProperties"] = True...
import setuptools setuptools.setup( name="pyhwjser", version="0.0.4", author="KyuzoM", author_email="kyuzom@googlegroups.com", description="json-serializable HWSerial", long_description="json-serializable HWSerial", url="https://github.com/kyuzom/taskedin", license="MIT", packages=[...
import webbrowser import requests from npyscreen import BoxTitle, Event from . import INSTALLED class PkgBox(BoxTitle): def create(self): self.display() self.values = INSTALLED self.update() def when_value_edited(self): self.parent.parentApp.queue_event( Event("e...
def load_df_json_cols(csv_path, json_cols=[], data_type = {}, nrows=None): ''' Function to load a DF with data in json format. Original idea in https://www.kaggle.com/scirpus/to-overcome-the-terrible-data ''' from pandas.io.json import json_normalize import json import os d...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from collections import Counter def get_probs(occurrences): """ Computes conditional probabilities based on frequency of co-occurrences Parameters ---------- occurrences: occurences[x][y] number of times with (X=x and Y=y) ...
import cv2 import numpy as np from scipy import ndimage cap = cv2.VideoCapture('B1.mp4') #Video1 cap2 = cv2.VideoCapture('A6.mp4') #Video2 cap3 = cv2.VideoCapture('A7.mp4') #Video3 cap4 = cv2.VideoCapture('B11.mp4') #Video4 cap5 = cv2.VideoCapture('B6.mp4') #Video5 cap6 = cv2.VideoCapture('A1.mp4') #Video6 c...
# import torch # # x = torch.ones(2, 2, requires_grad = True) # print(x.data) # print(x.grad) # print(x.grad_fn) # print('*' * 10) # y = x + 2 # print(y) # print(y.grad) # print(y.grad_fn) # print('*' * 10) # # z = y * y * 3 # out = z.mean() # print(z) # print(out) # print('*' * 10) # # # out.backward() # print(x.grad)...
from tkinter import * window = Tk() canvas = Canvas(window, height=1000, width=1000, bg='white') canvas.pack() cx=1000//2 cy=1000//2 r = 400 canvas.create_oval(cx-r, cy-r, cx+r, cy+r, width=2, outline="red") window.mainloop()
#! /usr/bin/env python """ Test BANE.py """ from __future__ import print_function from AegeanTools import BANE from astropy.io import fits import numpy as np import os __author__ = 'Paul Hancock' __date__ = '23/08/2017' import logging logging.basicConfig(format="%(module)s:%(levelname)s %(message)s") log = logging.g...
import getopt import io import sys import k8v def usage(output: io.IOBase) -> None: """Display the command line usage help screen.""" with open("etc/usage.md") as f: for line in f.readlines(): output.write(line) f.close() def main(argv: list) -> None: """Main execution to s...
import dataclasses import json import dataclasses_json def get_encode_config(): return dataclasses.field( metadata=dataclasses_json.config( encoder=lambda lst: sorted(lst, key=json.dumps, reverse=False) ) )
import numpy as np from itertools import product from scipy.io import loadmat def target_distribution_gen_all(name, param_range, which_param, other_param): """ Generate a set of target distributions by varying one parameter. which_param sets whether distr. param or noise param.""" if which_param == 1: ...
import numpy as np from openpnm.topotools import generate_base_points, dimensionality, isoutside def trim(network, vert_ids=None, edge_ids=None): r""" Remove given pores or throats from a network Parameters ---------- network : dictionary A dictionary containing 'vert.coords' and 'edge.co...
"""add user table Revision ID: 3326eb4a8333 Revises: cb38ff4e8b0a Create Date: 2020-02-05 16:44:09.758691 """ from alembic import op import sqlalchemy as sa import sqlalchemy_utils # revision identifiers, used by Alembic. revision = '3326eb4a8333' down_revision = 'cb38ff4e8b0a' branch_labels = None depends_on = Non...
# # Copyright (c) 2015-2018 Canonical, Ltd. # # This file is part of Talisker # (see http://github.com/canonical-ols/talisker). # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regardin...
if __name__=='__main__': pass
rios = { 'nilo': 'egito', 'amazonas': 'brasil', 'mississippi': 'estados unidos', } for rio, pais in rios.items(): print(f'O {rio.title()} corre pelo {pais.title()}.') print('\nRios:') for rio in rios.keys(): print(f'\t{rio.title()}') print('\nPaíses:') for pais in rios.values(): print(f'\t{pa...
# end_other('Hiabc', 'abc') → True # end_other('AbC', 'HiaBc') → True # end_other('abc', 'abXabc') → True def end_other(a, b): len_a = len(a) len_b = len(b) if len_a >= len_b: return(b.lower() == a[-len_b:].lower()) return(a.lower() == b[-len_a:].lower()) print(end_othe...
import pyperclip, re strongPassword = re.compile(r'^(?=.*\d)(?=.*[A-Z])\w{8,15}$') password = str(pyperclip.paste()) matches = [] for groups in strongPassword.findall(password): if len(matches) < 8: print('Password need to be at least 8 characters') else: print('Well done')
import wee from wee import application @wee.route('/') def index(request): body = """ <h1>Sample Wee application</h1> <ul> <li> <code>/<a href="/hello">hello</a>?name={your_name}</code> — prints welcome message </li> <li> <code>/<a href="/request">request</a></code> — prints request obje...
import unittest import lxml import webstruct.annotation_verifier html_1 = '<span style="abc" class="span">aa</span>' html_2 = '<span style="abd" class="span">aa</span>' html_3 = '<span style="abd" class="span">aa<p>s</p></span>' html_3 = '<span style="abd" class="span">aa<p>s</p><p>ss</p></span>' class SomethingTe...
from importlib import import_module from typing import Dict, List import xarray from .core import BlueskyRun __all__ = ['Projector', 'project_xarray'] class ProjectionError(Exception): pass def get_run_projection(run: BlueskyRun, projection_name: str = None): """Finds a projection in the run. If pro...
# -*- coding: utf-8 -*- """ #Buy / Sell stocks directly from zerodha """ from kiteconnect import KiteConnect import logging import os cwd = os.chdir("D:\Developers Institute\DevelopersInstitute\Week7\Hackathon") #generate trading session access_token = open("access_token.txt",'r').read() key_secret = open("api_key.tx...
from pymodbus.client.sync import ModbusTcpClient #import logging import time import random #FORMAT = ('%(asctime)-15s %(threadName)-15s ' # '%(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s') #logging.basicConfig(format=FORMAT) #log = logging.getLogger() #log.setLevel(logging.DEBUG) UNIT = 0x1 while T...
#!/usr/bin/env python from __future__ import division from pysstv.sstv import byte_to_freq, FREQ_BLACK, FREQ_WHITE, FREQ_VIS_START from pysstv.grayscale import GrayscaleSSTV from itertools import chain from enum import Enum class Color(Enum): red = 0 green = 1 blue = 2 class ColorSSTV(GrayscaleSSTV): ...
#!/usr/bin/python3 import xml.etree.ElementTree as ET from urllib import request, parse import hashlib # configuration FRITZBOX_PASSWORD = '' FRITZBOX_USER = '' FRITZBOX_BASE_URL = '' # method to retrieve SID def get_sid(): fb = request.urlopen(FRITZBOX_BASE_URL + 'login_sid.lua') dom = ET.parse(fb) sid = dom.fin...
import media import fresh_tomatoes interstellar = media.Movie( "Interstellar", "Interstellar is a 2014 science fiction film directed, co-written, " "and co-produced by Christopher Nolan. It stars Matthew McConaughey, " "Anne Hathaway, Jessica Chastain, Bill Irwin, Ellen Burstyn, and Michael " "Cai...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Filename: Entry.py Description: Script retireves CSV export from game, analyzes the players in every possible position, and exports data in an excel file. Author: Paul Brockmann How to Use: 1) Download most recent team roster as a csv (use Fi...
import unittest import os from tests import TestTools from DockerBuildSystem import VersionTools class TestVersionTools(unittest.TestCase): def test_GetVersionFromChangelog(self): version = VersionTools.GetVersionFromChangelog(os.path.join(TestTools.TEST_SAMPLE_FOLDER, 'CHANGELOG.md')) se...
#!/usr/bin/env python3 import numpy as np import os, sys import argparse from ..api import ZgyReader, SampleDataType from ..test.utils import SDCredentials _brief_info = """ File name = '{name}' File size (bytes) = {r._fd.xx_eof:,d} File format and version = {r.datatype.name} ...
import main x = 10
# -*- coding: utf-8 -*- # # © 2009 Digg, Inc. All rights reserved. # Author: Ian Eure <ian@digg.com> # """Lazyboy: Key.""" import uuid from cassandra.ttypes import ColumnPath, ColumnParent from lazyboy.base import CassandraBase from lazyboy.exceptions import ErrorIncompleteKey class Key(ColumnParent, CassandraBase...
from django.conf import settings from django.contrib.syndication.feeds import Feed, FeedDoesNotExist from django.contrib.sites.models import Site from django.contrib.contenttypes.models import ContentType from models import Project, CodeRepository, CodeCommit # Get the current site. site = Site.objects.get_current()...
# Copyright (c) 2020 PaddlePaddle 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 appli...
# This code scans any I2C devices connected to I2C0 & I2C1 at frequency 100kHz # and print the address(es) on serial. # --- # Connection: I2C0, SCL0 = GP1, SDA0 = GP0 # I2C1, SCL1 = GP3, SDA1 = GP2 # --- # Hardware: Any RP2040 boards. # --- import machine i2c0 = machine.I2C(0, scl=machine.Pin(1),...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ 采集规则 """ from __future__ import absolute_import from __future__ import print_function import sys import os PROJECT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) package = PROJECT_PATH + '/package' sys.path.insert(0, package) from y...
# Generated by Django 3.1.6 on 2021-02-18 12:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0004_users2'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', mod...
""" MESA select """ def getJunctions(filename1,filename2): with open(filename1) as file1: with open(filename2) as file2: header1 = file1.readline().rstrip().split("\t") header2 = file2.readline().rstrip().split("\t") junctions1 = set() for line in file1: ...
# Generated by Django 2.1.7 on 2019-03-24 19:26 import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Shop', fields=[ ...
###################################################################################################################### # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
import os from .entity_extraction_factory import EntityExtractionFactory def test_flair(): config = {'model': 'ner'} entity_factory = EntityExtractionFactory() model = entity_factory.get_entity_extraction_model('flair', config) text = 'Apple is looking to buy USA startup for $1 billion.' print('F...
from __future__ import absolute_import from django.utils import timezone from sentry.models import Activity from sentry.testutils import AcceptanceTestCase class OrganizationActivityTest(AcceptanceTestCase): def setUp(self): super(OrganizationActivityTest, self).setUp() self.org = self.create_or...
def extract_size_and_uom(value): extract_response = {} stripped_value = value.strip() if count_digit_groups(stripped_value) > 1: extract_response['successful'] = False return extract_response size = '' for char in list(stripped_value): if char.isdigit(): ...
__author__ = 'Aaron Yang' __email__ = 'byang971@usc.edu' __date__ = '11/26/2020 3:44 PM' def use_logging(func): def wrapper(): print("%s is invoking" % func.__name__) return func() return wrapper @use_logging def foo(): print("func foo") foo()
from collections import namedtuple import json import itertools class PushResponseError(Exception): """Base class for all push reponse errors""" def __init__(self, push_response): if push_response.message: self.message = push_response.message else: self.message = 'Unkno...
import os p = os.path.dirname(__file__) p = os.path.realpath(os.path.join(os.path.abspath(p), '..')) from sys import path if p not in path: path.append(p)
# Retrieve and store attachments from Jira server # # AVOU 06.11.2019 v1 # AVOU 25.06.2020 v2 # AVOU 28.12.2020 v3 # # This script connects to a jira_server (given the jira_user/jira_password) and retrieves the attachments # of all the tickets of the defined projects. Attachments are stored in a directory named with th...
import base64 import copy import inspect import json import logging import os import re import warnings from collections import OrderedDict from typing import Optional from urllib.parse import urlparse try: from azure.identity import DefaultAzureCredential from azure.keyvault.secrets import SecretClient except...
#!/usr/bin/env python # # Copyright (c) 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # # # This script is used to run OfflinePageSavePageLaterEvaluationTests. # The test will try to call SavePageLater on the list pr...
import decimal import requests import urllib.request, urllib.parse, urllib.error import json import hashlib import hmac import time import calendar import datetime import logging logger = logging.getLogger(__name__) hdlr = logging.FileHandler('logs/logger.log') formatter = logging.Formatter('%(asctime)s %(levelname...
A, B, D = map(int, input().split()) def eratosthenes(m, n, k): MAX, count = 4000000, 0 check = [0] * (MAX+1) check[0] = check[1] = True for i in range(2, MAX+1): if not check[i]: j = 2*i while j < MAX: check[j] = True j += i k = str(k...
from __future__ import (absolute_import, division, print_function, unicode_literals) import scipy.signal as sig import numpy as np from raspy.progressTrackers import ProgressPrinter def estimateArgs(data, fs, callback=ProgressPrinter()): if not data.ndim == 1: raise ValueError('fi...
import time import torch from torch.utils.checkpoint import checkpoint import config as cfg from ctm.one_site_c4v.env_c4v import * from ctm.one_site_c4v.ctm_components_c4v import * try: import scipy.sparse.linalg from scipy.sparse.linalg import LinearOperator except: print("Warning: Missing scipy. ARNOLDISV...
#!/usr/bin/env python import logging import os import importlib import sys import pickle import numpy as np import pandas as pd import utils import process_features import attention_model import torch from torch.utils import data import torch_visual from torch import save from time import time import random import my_...
import mysql.connector import dbconfig as config db = mysql.connector.connect( host=config.mysql['host'], user=config.mysql['username'], password=config.mysql['password'], database=config.mysql['database'] ) cursor = db.cursor() sql="select * from student" cursor.execute(sql) result = cursor.fetchall() for ...
class MergedOptimizers: """ Can be used to Merge 2 optimizers into one. This is useful when you want to apply different optimizers to different parameters while the algorithm implementation only supports one optimizer. """ def __init__(self, opt_list): self.opt_list = opt_lis...
import chalicelib.utils as utils import json import sys from gremlin_python.driver.protocol import GremlinServerError from gremlin_python.process.graph_traversal import __ from gremlin_python.process.traversal import T from gremlin_python.driver.client import Client from gremlin_python.structure.graph import Vertex, E...
from rest_framework import serializers from .fields import ( JSONStringField, CartItemElementRelatedField, ContentTypeSerializerField ) from ..models import Cart, CartItem, CartGroup from ..settings import settings __all__ = ( 'CartItemElementSerializer', 'CartChangeSerializer', 'CartItemRetri...
import pandas as pd def write_parquet_file(): df = pd.read_csv('recipeData-utf8.csv') df.to_parquet('data/recipeData.parquet') write_parquet_file()
from django.conf.urls import url from .views import index, assignments, webhook urlpatterns = [ url("^$", index, name="score"), url("^assignments/$", assignments, name="assignments"), url("^webhook/?$", webhook) ]
#! /usr/bin/env python # -*- coding: UTF-8 -*- __author__ = 'xcma' class Counter: def __init__(self, func): self.func = func self.count = 0 def __call__(self, *args, **kwargs): self.count += 1 return self.func(*args, **kwargs) def todo(func): import functools @functool...
import tensorflow as tf import math import numpy as np def warmup_cosine_annealing_lr(lr, steps_per_epoch, warmup_epochs, max_epoch, T_max, eta_min=0): base_lr = lr warmup_init_lr = 0 total_steps = int(max_epoch * steps_per_epoch) warmup_steps = int(warmup_epochs * steps_per_epoch) lr_each_step = ...
__author__ = 'vasiliki' from django.conf.urls import patterns, url from myapp import views urlpatterns = patterns('', url(r'^home/', views.home, name='home'), url(r'^$', views.home, name='home'), url(r'^main/', views.main, name='main'), url(r'^buildings/', views.buildings, name='buildings'), url(...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2017, 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...
# # Turbo Decoder # import numpy as np from .siso_decoder import SISODecoder class TurboDecoder: @staticmethod def demultiplex(a, b, extrinsic): return list(zip(a, b, extrinsic)) @staticmethod def early_exit(LLR, LLR_ext): LLR = [int(s > 0) for s in LLR] LLR_ext = [int(s > 0...
#!/usr/bin/env python # coding=utf-8 from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys sys.path.append('.') from tqdm import tqdm from sfd import WiderDetection dt = WiderDetection(splits='val') H, W = 0, 0 with tqdm(total=len(dt)) as pbar: fo...
from collections import Counter, defaultdict import math FILE = "days/14/input.txt" def solve(template, rules, iterations): # Initial set of pairs c = Counter([f"{template[i-1]}{template[i]}" for i in range(1, len(template))]) for _ in range(iterations): # This dict contains all the updates (plus...
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import enum import typing import pytest from cryptography import utils class TestCachedProperty(object): def test_simple(self): ...
#!/usr/bin/env python # Siconos is a program dedicated to modeling, simulation and control # of non smooth dynamical systems. # # Copyright 2018 INRIA. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the L...
# Author: Karl Stratos (me@karlstratos.com) import argparse import copy import inspect import math import numpy as np import pickle import random import torch import torch.nn as nn import torch.nn.functional as F import util from collections import OrderedDict def control_weights(args, models): def init_weights...
import warnings from .configuration import Configuration from .datasets import AttckDatasets class Attck(object): ''' This class creates an interface to all MITRE ATT&CK frameworks. Currently, this class enables access to the Enterprise & PRE-ATT&CK frameworks with others coming soon. To accces...
#!/usr/bin/env python # -*- coding:utf-8 -*- import logging import os from logging.handlers import RotatingFileHandler from datetime import datetime class DumbFormatter(logging.Formatter): converter = datetime.fromtimestamp def formatTime(self, record, datefmt=None): ct = self.converter(record.creat...
__version__ = '1.8' def setup(app): from .doxylink import setup_doxylink_roles app.add_config_value('doxylink', {}, 'env') app.connect('builder-inited', setup_doxylink_roles)
import os import paypalrestsdk import yaml from django.conf import settings from lessons.payments import plans BASE_DIR = os.path.join( "..", # proj "..", # land os.path.dirname(__file__) # commands ) ORDER_A_CONF_PATH = os.path.join("paypal", "order-annual.yml") ORDER_M_CONF_PATH = os.path.join("payp...
""" Asyncio client module """ import socket import asyncio import asyncio.streams from smserver.smutils import smconn class AsyncSocketClient(smconn.StepmaniaConn): ENCODING = "binary" def __init__(self, serv, ip, port, reader, writer, loop): smconn.StepmaniaConn.__init__(self, serv, ip, port) ...
from skimage import color from skimage import io from skimage.transform import rescale from config import MAX_SIZE def downscale_an_image(image): """ Если одна из сторон больше MAX_SIZE то уменьшаем в (MAX_SIZE / max_shape) раз :param image: :return: """ max_shape = max(image.shape) if...
# This file is part of wallriori # (c) Timofey Mukha # The code is released under the MIT Licence. # See LICENCE.txt and the Legal section in the README for more information from __future__ import absolute_import from __future__ import division from __future__ import print_function from wallriori.wallmodels import LOT...
import numpy as np from scipy.optimize import minimize from .debug_utils import debug_show from .keypoints import make_keypoint_index, project_keypoints from .normalisation import norm2pix from .simple_utils import fltp from datetime import datetime as dt from cv2 import circle, line, LINE_AA __all__ = ["optimise_para...
 import TreeModel from PyQt5.Qt import Qt from PyQt5.QtCore import QVariant class CategoryTreeItem(TreeModel.TreeItem): def __init__(self, category, parent=None): super().__init__(parent) self.category = category def columnCount(self, parent): return 1 def data(self, index, rol...
import os import glob import numpy as np import tensorflow as tf import utils import metrics from core.experiments import Experiment class ExtractFeaturesFlipped(Experiment): name = "extract-features-flipped" requires_model = True @classmethod def specific_default_hparams(cls): hps = utils...
# -------------------------------------------------------- # Faster R-CNN # Copyright (c) 2015 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by Ross Girshick and Sean Bell # -------------------------------------------------------- # ------------------------------------------------------...
from django.urls import path, include from client import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('clients', views.ClientsViewSet, basename='Clients') app_name = 'client' urlpatterns = [ path('', include(router.urls)), ]
# :coding: utf-8 # :copyright: Copyright (c) 2013 Martin Pengelly-Phillips # :license: See LICENSE.txt. from ..error import SchemaConflictError class Collection(object): '''Store registered schemas.''' def __init__(self, schemas=None): '''Initialise collection with *schemas*.''' self._schema...
import os from concurrent.futures import ProcessPoolExecutor from functools import partial from typing import Collection, Optional, Union import numpy as np import pandas as pd from .exceptions import EndogInputError, InvalidModelError from .summary import SummaryList from .typings import Endog, Exog, RngGen from .ua...
# from src.utils import conf, log # # init configration # conf.init() # # init log module # log.init()
import serial with serial.Serial('/dev/serial0', 9600, timeout=2) as ser: line1 = ser.readline() print(line1) line2 = ser.readline() print(line2) line3 = ser.readline() print(line3) line4 = ser.readline() print(line4) for i in range(100): command = 'command%d\n' % i ...
from unittest import TestCase from .main import merge_similar class MergeTest(TestCase): def test_negative_example(self): test_communities = { 'abc': set([1,2,3,4]), 'def': set([5,6,7,8]) } merged = merge_similar(test_communities, 0.75) print(merged) ...
#!/usr/bin/python ############################### TOOLS MAKED BY ANONYMINHACK5 import os import urllib2 import json import time import smtplib from termcolor import colored, cprint from base64 import * ############################### RECODE AUTO JAHANNAM os.system("reset") print ("\033[93m __ __ ...
from necrobot.util import server from necrobot.config import Config from necrobot.botbase.commandtype import CommandType class AddRacerRole(CommandType): def __init__(self, bot_channel): CommandType.__init__(self, bot_channel, 'addrole') self.help_text = f'Add yourself to the {Config.RACER_ROLE} r...
import pandas as pd QUERY_SAMPLE = 'nmdc:mga04781' QUERY_AWS_PATH = 's3://psss-metagenomics-codeathon-data/marine/nmdc:mga04781/assembly/nmdc_mga04781_contigs.fna' metadata = pd.read_csv('data.tsv', sep='\t') metadata = metadata.query("MGA_ID != @QUERY_SAMPLE") metadata = metadata.set_index('MGA_ID') open('query_pat...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-09-13 08:27 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('location', '0003_auto_20160819_0207'), ] operations = [ migrations.AddField( ...