content
stringlengths
5
1.05M
#!/usr/bin/env python # # 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.0OA # # Authors: # - Wen Guan, <wen.guan@cern.ch>, 2019 import json from trac...
# uncomment to setup WiFi connection """ import network def do_connect(): sta_if = network.WLAN(network.STA_IF) if not sta_if.isconnected(): print('Connecting to network...') sta_if.active(True) sta_if.connect('SSID', 'password') while not sta_if.isconnected(): pas...
import numpy as np from src.io import npy_events_tools from src.io import psee_loader import tqdm import os from numpy.lib import recfunctions as rfn import pandas as pd import torch import time import math import argparse def taf_cuda(x, y, t, p, shape, volume_bins, past_volume): tick = time.time() H, W = sha...
import math from data import gazetteer class FeatureVector(object): def __init__(self, fdict): # mapping for features self.fdict = fdict def times_plus_equal(self, scalar, v2): """ self += scalar * v2 :param scalar: Double :param v2: FeatureVector :ret...
"""Support for Twente Milieu sensors.""" from __future__ import annotations from twentemilieu import ( WASTE_TYPE_NON_RECYCLABLE, WASTE_TYPE_ORGANIC, WASTE_TYPE_PAPER, WASTE_TYPE_PLASTIC, TwenteMilieu, TwenteMilieuConnectionError, ) from homeassistant.components.sensor import SensorEntity, Sen...
import importlib import logging import os import sys from collections import Counter from pathlib import Path from typing import List, Type from . import __version__, settings from .checkers.aws.ec2 import get_instance_type from .checkers.aws.spot import SpotInstanceValueObserver from .defaults import DEFAULT_MODEL_VE...
from django.db import models from django.contrib import admin from django.contrib.auth.models import User from .server import Server from .serverUser import ServerUser from .entity import Entity from .key import Key class EntityOnServer(models.Model): """ This represents the relationship between entity and se...
#!/usr/bin/python from bluepy import btle from bluepy.btle import BTLEException from badge import Badge, BadgeDelegate import struct import logging import logging.handlers import os import re import subprocess import shlex import sys import time import csv from badge_discoverer import BadgeDiscoverer log_file_name = '...
""" 34.64% """ # Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ inte...
import os, random, pygame, sys class Music(object): """ Plays selected audio files or picks a random file named music*.mp3.""" def __init__(self): self.music = {}; if os.path.exists(os.path.expanduser('~/.config/pialarmclock/audio')) == True: for fileMp3 in os.listdir(os.path.expan...
import torch from torch import nn import torch.utils.data as Data import torch.optim as optim from tqdm import tqdm from dataLoader import stl10_loader,mbllen_loader from network import DenoiseAutoEncoder from lolPSNR import lolPSNR from loss import SSIM,LXJ_LOSS from torchvision import models, transforms from torch.a...
#!/usr/bin/env python from math import sqrt f = open('p102_triangles.txt') triangles = f.read().strip().split() f.close() triangles = map(lambda x: map(int, tuple(x.split(','))), triangles) # use Heron's formula: http://mathworld.wolfram.com/HeronsFormula.html # area = sqrt(p*(p-a)*(p-b)*(p-c)) = sqrt(4a^2b^2-(a^2+...
# Problem Statement: https://www.hackerrank.com/challenges/detect-html-tags-attributes-and-attribute-values/problem import sys from html.parser import HTMLParser class MyHTMLParser(HTMLParser): def handle_starttag(self, tag, attrs): print(tag) for attr in attrs: print('->', ' > '.join(attr)) N = input() par...
from __future__ import annotations from typing import Iterator, Type from ._cdata import CData from ._ffi import ffi, lib from ._profile import Profile __all__ = ["Input"] class Input: def __init__(self, nmm_input: CData): self._nmm_input = nmm_input if self._nmm_input == ffi.NULL: ...
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 """ The file contains necessary transformations to convert models created with a TensorFlow Object Detection framework from the https://github.com/tensorflow/models/blob/master/research/object_detection/ repository. There is a dedicated ...
from algorithm.sorts.quick_sort import quick_sort from tests.sort.base_sort import BaseSortTestCase class QuickBaseSortTestCase(BaseSortTestCase): def test_quick_sort(self): self.loop(quick_sort, self.data) def test_quick_sort_random(self): self.loop(quick_sort, self.data, is_random=True) ...
# -*- coding: utf-8 -*- import os.path from guietta import B, L, _, Gui, Quit gui = Gui( [ 'Enter expression:', '__expr__' , B('right.png', 'newname') ], [ L('left.png', 'result') , 'result' , _ ], [ _ , _ , Quit ], images_dir = os.path.dirname...
from flask import Flask, redirect, url_for, request app = Flask(__name__) @app.route('/success/<name>') def success(name): return "welcome %s" % name @app.route('/') def hi(): return "<h1>The Guide for Flask Professional</h1>" @app.route('/login', methods=['POST','GET']) def login(): if request.method ==...
#!/usr/bin/env python from __future__ import division, absolute_import, print_function """ Defines general functions, derivatives, etc. Definition ---------- Current functions are: curvature Curvature of function f: f''/(1+f'^2)^3/2 logistic logistic function L/(1+exp...
import functools import shutil from pathlib import Path from typing import Any, Iterable, List, Optional, Tuple import numpy as np import pandas as pd from .parallel import execute_parallel from .typing import FilePath __all__ = [ "categorize_folders", "split_labels", "build_srcs_dsts", "convert_byte...
"""Plugin declaration for thola nautobot.""" __version__ = '0.2.0' from nautobot.extras.plugins import PluginConfig class Thola(PluginConfig): """Plugin configuration for the thola_nautobot plugin.""" name = 'thola_nautobot' verbose_name = 'Thola Nautobot' description = 'Thola plugin for Nautobot' ...
#!/usr/bin/env python # coding: utf-8 import os import sys import cmiles from openeye import oechem def read_split_mols(filename): ifs = oechem.oemolistream() # open input file that contains many molecules ifs.open(filename) # get all molecules from sdf file mol_list = [] for mol in ifs.GetOEMo...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. # -*- coding: utf-8 -*- import json import os from pprint import pprint import requests ''' This sample makes a call to the Bing Video Search API with a topic query and returns relevant video with data. Documentation: https...
#!/usr/bin/env python import os, sys def getSource(className, nameSpace): headerSrc = \ '''#ifndef _<NAMESPACE>_<CLASSNAME>_H_ #define _<NAMESPACE>_<CLASSNAME>_H_ namespace <NameSpace> { class <ClassName> { public: <ClassName>(); private: }; } // namespace <NameSpace> #endif // _<NAMESPACE>_<CLASSNAME>_H...
from plenum.common.request import Request from plenum.common.types import f def generate_action_result(request: Request): return {**request.operation, **{ f.IDENTIFIER.nm: request.identifier, f.REQ_ID.nm: request.reqId}}
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.sna_ex import sna_ex def test_sna_ex(): """Test module sna_ex.py by downloading sna_ex.csv and testing shape of extracted data has 0 rows ...
# This is an python GUI program which is used to display the time. # importing the modules from tkinter import * from time import strftime # creating a display window variable window = Tk() # setting up the title for the display window window.title("Digital Clock") # setting up the background for the di...
import os import subprocess import sys import shutil import socket import time import logging import platform import csv from datetime import datetime import multiprocessing as mp fave_path = r'FAAValign.py' fave_dir = r'D:\Dev\GitHub\FAVE\FAVE-align' dictionary_path = r'D:\Data\aligner_comp\dictionaries\fave.diction...
# -*- coding: utf-8 -*- r""" The matrix monoid `\Sigma_0(N)`. This stands for a monoid of matrices over `\ZZ`, `\QQ`, `\ZZ_p`, or `\QQ_p`, depending on an integer `N \ge 1`. This class exists in order to act on p-adic distribution spaces. Over `\QQ` or `\ZZ`, it is the monoid of matrices `2\times2` matrices `\begin{p...
from collections import namedtuple Range = namedtuple('Range', ('begin', 'end'))
import getopt import sys import time global phoneNumber try: opts,args = getopt.getopt(sys.argv[1:],"n:",["phoneNumber"]) except getopt.GetoptError as err: print(str(err)) for o,a in opts: if o in ('-n'): phoneNumber =a i=0 print("Start to attacking...\n") time.sleep( 10 ) print("Finished!\n")...
from .longpool import listen __version__ = '1.0' __author__ = 'lixa4-m'
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: kikimr/public/api/protos/ydb_common.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _re...
""" inference ========= EP inference drivers (in the future, other inference methods could be implemented here as well). """ import numpy as np import scipy.linalg as sla import scipy.sparse as ssp import scipy.io # DEBUG: Load Matlab files import numbers import time # For profiling import apbsint.helpers as help...
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def LasMain(req): print(req.GET['name']) return render(req,'index.html',{'NAME':req.GET['name']})
from math import floor import numpy as np import pandas as pd class MortalityTable(): def __init__( self, qx_rates, start_age=0, select_rates=None, age_basis='anb', force='u', *args, **kwargs): if force.lower() not in ['u', 'c']: ...
import tensorflow as tf import cv2 import time import argparse import math import posenet parser = argparse.ArgumentParser() parser.add_argument('--model', type=int, default=101) parser.add_argument('--cam_id', type=int, default=0) parser.add_argument('--cam_width', type=int, default=1280) parser.add_argument('--cam_...
#!/usr/bin/env python3 from socketserver import TCPServer from http.server import BaseHTTPRequestHandler from http import HTTPStatus import http.client import json import os from collections import OrderedDict # Credits: # https://gist.github.com/bradmontgomery/2219997 # https://stackoverflow.com/questions/3474045/pr...
import re size = [] with open("allSize.txt") as inFile: for line in inFile: z = re.match(r'(.*)T ', line) if z: # print((z.groups())) # print z.group()[:-2] size.append(float(z.group()[:-2])) print sum(size)
# main interface to blink(1) from blink1.blink1 import blink1 import atexit from random import random class BlinkInterface(object): def __init__(self, ipython): self.ipython = ipython # send patterns to blink1, and store indices into pattern memory self.executing_pattern = (1, 2) ...
import glob import os import setuptools import shutil import subprocess import sys from distutils.command.clean import clean as _clean from distutils.spawn import find_executable from os.path import basename from os.path import splitext if sys.version_info[0] == 3: from distutils.command.build_py import build_py_...
from logging import getLogger from time import sleep from time import time import numpy as np import os from keras.callbacks import TensorBoard from keras.optimizers import Adam import chess from chess_zero.config import Config from chess_zero.lib import tf_util from chess_zero.lib.data_helper import get_game_data_fi...
import requests __author__ = "Griffith Asare Awuah (@gwuah)" class ogma(): """Language Detection Library For Pythonistas""" def __init__(self, accessKey): self.payload = {'access_key': str(accessKey)} def detect(self, phrase) : self.payload['query'] = str(phrase) try : r = requests.get('http://apilaye...
import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.datasets as datasets import torchvision.transforms as transforms from torch.utils.data import DataLoader import numpy as np import matplotlib.pyplot as plt import os import time from data import TinyIN, cifar10tra...
from ..models.nodes import Node from ._NodePermission import NodePermission class NodeIsSelf(NodePermission): """ Permission that that applies to actions on nodes that requires that the node is accessing itself """ def has_node_permission(self, node, request, view, obj) -> bool: # If the o...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Deleting field 'Building.organization' db.delete_column('buildings_buil...
from plotly.missing_ipywidgets import FigureWidget from vuabl.data.size_plot_data import SizePlotData import plotly.graph_objects as go import vuabl.utils.theming as theming def plot_categories_sizes_pie(data: SizePlotData) -> FigureWidget: figure: FigureWidget = go.Figure(go.Pie( labels=data.frame["cate...
from scrapyd_api.exceptions import ScrapydError def test_scrapyd_error(): err = ScrapydError() assert repr(err) == 'ScrapydError("Scrapyd Error")' err_with_detail = ScrapydError(detail='Something went wrong') assert repr(err_with_detail) == 'ScrapydError("Something went wrong")'
# -*- coding: UTF-8 -*- import os import sys import vcr DIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(DIR, '../../limbo/plugins')) from wiki import on_message def test_basic(): with vcr.use_cassette('test/fixtures/wiki_basic.yaml'): ret = on_message({"text": u"!wiki d...
import argparse #from pytlv.TLV import * from TLV import * from smartcard.System import readers from smartcard.util import toHexString,toASCIIString from smartcard.Exceptions import NoCardException import Crypto from Crypto.PublicKey import RSA import json import rocatest import sys r=readers() GET_RESPONSE = [0X00...
cadena = input() abecedario = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] for i in cadena: if i in abecedario: if i == 'z': print('a', end = '') else: letra =...
import os from peewee import PostgresqlDatabase, CharField, IntegerField, Model db = PostgresqlDatabase( os.environ["DB_NAME"], user=os.environ["DB_USER"], password=os.environ["DB_PASS"], host=os.environ["DB_HOST"], port=os.environ["DB_PORT"], ) class Reward(Model): id = CharField(null=False)...
import os import pickle import argparse import argcomplete import numpy as np import pandas as pd import nmslib from bertcode import bertvectors def create_nmslib_search_index(numpy_vectors): search_index = nmslib.init(method='hnsw', space='cosinesimil') search_index.addDataPointBatch(numpy_vectors) sear...
# -------------- import pandas as pd from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import sklearn_crfsuite from sklearn_crfsuite import metrics import eli5 # Start of code # Read the file with the given encoding and do not throw any error, ignore it. df = pd.read_csv(p...
x = 2 print(x == 2) print(x == 3) print(x < 3)
#!/usr/bin/env python3 # coding:utf-8 """ 手动倒入cad解析 """ import os import json import datetime from libs.utils import get_json, save_json from project.project import Project from project.cad import Cad from project.room import Room from project.connection_item import ConnectionItem cad_name = "Jinshan Layout.dxf" proje...
"""Middleware used by django-watson.""" from __future__ import unicode_literals from django.core.exceptions import ImproperlyConfigured try: from django.utils.deprecation import MiddlewareMixin cls = MiddlewareMixin except: cls = object from watson.search import search_context_manager WATSON_MIDDLEWARE...
#!/usr/bin/env python3 import sys import cdsapi import yaml with open('/home/users/smartmet/.camsapirc', 'r') as f: credentials = yaml.safe_load(f) c = cdsapi.Client(url=credentials['url'], key=credentials['key']) year= sys.argv[1] mon= sys.argv[2] day= sys.argv[3] date='%s-%s-%s'%(year,mon,day) c.retrieve( ...
# -*- coding: utf-8 -*- # @Time : 19-9-17 上午11:43 # @Author : Redtree # @File : s_game_gowin.py # @Desc : 角色获胜处理 from data import player_runtime from logic import loader import random from data import color_rgb from utils import timer import pygame ''' 1 我方一角色攻击力永久+2 2 阵营所有英雄血量+2 3 立即对场上一个指定角色造成...
class LRUCache(object): def __init__(self, capacity): """ :type capacity: int """ self.capacity = capacity self.ht = {} self.q = [] def get(self, key): """ :rtype: int """ if key in self.ht: self.q.remove(key) ...
"""Test sample data.""" def test_data(make_napari_viewer): samples = [ "sample_data_random", "sample_data_cell_culture", "sample_data_timelapse_brightfield", "sample_data_timelapse_nanog", "sample_data_timelapse_pu1", "sample_data_wsi_brain", ] viewer = mak...
from .modelcatalog import ModelCatalog class ModelBuilder(object): def __init__(self, cfg): self.cfg = cfg def build(self): model = ModelCatalog.get(self.cfg.MODEL.name, self.cfg) return model
# Copyright 2021 Hang-Chi Shen. 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...
# Copyright (c) Lawrence Livermore National Security, LLC and other VisIt # Project developers. See the top-level LICENSE file for dates and other # details. No copyright assignment is required to contribute to VisIt. """ File: visit_exprs_parser.py Authors: Cyrus Harrison <cyrush@llnl.gov> Maysam Moussa...
# Python stubs generated by omniidl from ..\..\..\..\..\idl\COS\CosTypedNotifyComm.idl # DO NOT EDIT THIS FILE! import omniORB, _omnipy from omniORB import CORBA, PortableServer _0_CORBA = CORBA _omnipy.checkVersion(4,2, __file__, 1) try: property except NameError: def property(*args): ...
import FWCore.ParameterSet.Config as cms import copy from TrackingTools.KalmanUpdators.Chi2MeasurementEstimator_cfi import * # Chi2MeasurementEstimatorESProducer RelaxedChi2Simple = copy.deepcopy(Chi2MeasurementEstimator) RelaxedChi2Simple.ComponentName = 'RelaxedChi2Simple' RelaxedChi2Simple.MaxChi2 = 100. #replace R...
import pygame class Wall(pygame.sprite.Sprite): def __init__(self, color, dimensions, coordinates): super().__init__() self.image = pygame.Surface(dimensions) self.image.fill(color) self.rect = self.image.get_rect(center=coordinates)
# mode: run # tag: control-flow, uninitialized def conditional(cond): """ >>> conditional(True) [] >>> conditional(False) Traceback (most recent call last): ... UnboundLocalError: local variable 'a' referenced before assignment """ if cond: a = [] return a def inside_lo...
############################################################################ # # # Copyright (c) 2017 eBay Inc. # # Modifications copyright (c) 2018-2020 Carl Drougge # # ...
import numpy as np class CountLine(): ''' Counts everytime a bat crosses a line defined in space (y = constant) ''' def __init__(self, line_value, line_dim=1, total_frames=None): ''' line_value: the value that defines the position of the line the bats are crossing. ...
from decimal import Decimal from uuid import uuid4 import time import math from pprint import pprint from pyjuque.Engine.Models import TABotModel as Bot, PairModel as Pair, OrderModel as Order from pyjuque.Engine.OrderManager import placeNewOrder, simulateOrderInfo, cancelOrder from pyjuque.Exchanges.Base.Exceptions im...
from data import * from stdVars import ureg import numpy as np # Initialize a new data object and add column descriptions data = Data() data.define_row('row1', displayname=r'N', error= lambda x: np.sqrt(x)) # The error of the data is automatically calculated using the given formula data.define_row('row2', displayname=...
"""Unit tests for the Timer class.""" import logging import time import pytest from pynetdicom.timer import Timer LOGGER = logging.getLogger('pynetdicom') LOGGER.setLevel(logging.CRITICAL) class TestTimer(object): """Test the Timer class.""" def test_init(self): """Test Timer initialisation""" ...
from django.test import TestCase from django.shortcuts import reverse, redirect class TestViews(TestCase): def test_login_page(self): page = self.client.get("/accounts/login/") self.assertEqual(page.status_code, 200) self.assertTemplateUsed(page, "login.html") def test_registration_p...
#!/usr/bin/env python import re, glob, json # ['cholesky-p16-simsmall', 'MESI', 'OoO', 'TSO', '4', '192', '42', 'NoCoal', 'OnExecute', 'OoO', '16', '256', '16', '16', '1.stats.lines.8.energy'] with open('writersblock_energy.csv', "w") as f: f.write('app,coherence_protocol,core_type,memory_ordering,dispatch_width,r...
""" This project is part of the PyFunceble project. The objective of this project is to provide the PyFunceble project behind a Web REST API. :: ██████╗ ██╗ ██╗███████╗██╗ ██╗███╗ ██╗ ██████╗███████╗██████╗ ██╗ ███████╗ ██╔══██╗╚██╗ ██╔╝██╔════╝██║ ██║████╗ ██║██╔════╝██╔════╝██╔══██╗██║ ██╔...
import rubrik_cdm rubrik = rubrik_cdm.Connect() config = {} config['loginBanner'] = "Login Banner for the Python SDK Cluster" set_login_banner = rubrik.put('internal', '/cluster/me/login_banner', config)
from .base import * from .grains.logging import LOGGING from .grains.aws import * from .grains.sentry import * from .grains.cache import * # Google Analytics settings GOOGLE_TAG_MANAGER = False DEBUG = False STATICFILES_DIRS = () MIDDLEWARE_CLASSES = ( 'django.middleware.common.BrokenLinkEmailsMiddleware', ...
from __future__ import print_function import os import sys import tensorflow as tf import data_helpers import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from sklearn.model_selection import train_test_split from keras.layers import Dense, Input, Fla...
#!/usr/bin/env python # -*- coding:utf-8 -*- # @Time : 2020/5/30 11:20 # @Author : dorom # @File : db.py # @Software: PyCharm # coding:utf-8 import pymysql from utils.readYaml import ReadYaml from utils.filePath import FilePath from utils.logger import MyLogger class DbOption(object): def __init__(self): ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from django.core.management.base import BaseCommand, CommandError from django.core.management import call_command from ...conf import settings from ... import utils class Command(BaseCommand): help = ( 'Creates or updates .po fil...
#!/usr/bin/env python # # Copyright 2013 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. import distutils.spawn import fnmatch import optparse import os import shutil import re import subprocess import sys import textwrap ...
# -*- coding: utf-8 -*- """ tmdbsimple.account ~~~~~~~~~~~~~~~~~~ This module implements the Account, Authentication, and Lists functionality of tmdbsimple. Created by Celia Oakley on 2013-10-31. :copyright: (c) 2013-2014 by Celia Oakley :license: GPLv3, see LICENSE for more details """ from .base im...
import ctypes import time class ThreadNode(object): """A ThreadNode used in building the thread tree""" __slots__ = ['ident', 'name', 'thread', 'health', 'exception', 'status', 'daemon', 'children', 'last_updated'] def __init__(self, thread): self.ident = thread.ident self.name = thread.n...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright (C) 2020 The Project U-Ray Authors. # # Use of this source code is governed by a ISC-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/ISC # # SPDX-License-Identifier: ISC from utils.spec import rclk_int_3 from ut...
import csv import matplotlib.pyplot as plot import os.path from numpy import polyfit, arange CSV_FILE_NAME = "data.csv" current_directory = os.path.dirname(os.path.realpath(__file__)) def main(): """The main function that is called when the program is run""" trials = parse_data_from_csv() for trial i...
from django.db import models from shared.models import BaseModel levels = (('0','National'),('2','International'),('3','State'),) class ClubInfo(BaseModel): class Meta: db_table = '"system_config_clubinfo"' # firm_id = models.IntegerField(null=True) # dept_id = models.IntegerField(null=True) ...
""" Implementation of Command Pattern to check health of system Copyright (C) 2017-2022 Intel Corporation SPDX-License-Identifier: Apache-2.0 """ import logging from abc import ABC import netifaces import psutil import os from typing import Dict, Union, Any from .filesystem_utilities import get_free_spa...
from django.urls import path from .views import ( DashboardView, AddPreferenceView, RemovePreferenceView ) urlpatterns = [ path('', DashboardView.as_view(), name='user-dashboard'), path('<slug:category>/add/', AddPreferenceView.as_view(), name='user-add-preference'), path('<slug:category>/remove...
# Generated by Django 3.2 on 2021-04-18 02:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('specs', '0003_alter_educationdirection_education_form'), ('organizations', '0002_educationorg_regi...
#!/usr/bin/python #----------------------------------------------------- # Create a DataFrame from a CSV file With Header # Input: CSV File With Header #------------------------------------------------------ # Input Parameters: # a CSV file With Header #------------------------------------------------------- # @auth...
from collections import namedtuple from FPNode import FPNode class FPTree(object): """ An FP tree. This object may only store transaction items that are hashable (i.e., all items must be valid as dictionary keys or set members). """ Route = namedtuple('Route', 'head tail') ...
# import module from wsgifref from wsgiref.simple_server import make_server # import our application from hello import application # create a server,IP NULL, port 8000 httpd = make_server('', 8000, application) print "Serving HTTP on port 8000..." # start listening HTTP request httpd.serve_forever()
from __future__ import absolute_import, division import collections import math from functools import reduce from itertools import chain, count, islice, takewhile from multiprocessing import Pool, cpu_count import dill as serializer import six if six.PY2: PROTOCOL = 2 else: PROTOCOL = serializer.HIGHEST_PRO...
#!/usr/bin/env python import matplotlib matplotlib.use('Agg') from datetime import datetime from matplotlib.dates import date2num import matplotlib.pyplot as plt import numpy as np class Stock(): def __init__(self, filename): self.time = [] self.adjclose = [] self.mvavg = [] self....
import httplib from httplib import HTTPException, ImproperConnectionState import logging import socket from urllib import urlencode from lxml import etree from datetime import datetime from lxml.etree import XMLSyntaxError from squirrel_api.exceptions import SquirrelException, SquirrelApiException, SquirrelConnection...
import zipfile from cStringIO import StringIO import re CSLINE = 129 ZIP4FILE = re.compile("zip4/[0-9]{3}.zip") ZIP4LINE = 182 def extract_zip4(cur): cur.execute(""" DROP TABLE IF EXISTS usps_cs_scheme; """) cur.execute(""" DROP TABLE IF EXISTS usps_cs_alias; """) cur.execute(""" DROP TABLE IF EXISTS ...
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.condenser_equipment_and_heat_exchangers import FluidCoolerTwoSpeed log = logging.getLogger(__name__) class TestFluidCoolerTwoSpeed(unittest.TestCase): def setUp(self): ...
# Python - 3.6.0 test.expect(even_or_odd(2) == 'Even') test.expect(even_or_odd(0) == 'Even') test.expect(even_or_odd(7) == 'Odd') test.expect(even_or_odd(1) == 'Odd') test.expect(even_or_odd(-1) == 'Odd')
import json import logging REMOVED_FIELDS = [ "cluster.image_info_ssh_public_key", "cluster.ssh_public_key", "cluster.image_info.ssh_public_key" "cluster.connectivity_majority_groups", "cluster.controller_logs_collected_at", "cluster.hosts.connectivity", "cluster.hosts.images_status", ...