content
stringlengths
5
1.05M
from sqlalchemy import Column, Integer, String, Float from app.models.database import Base class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(64), unique=False) picture = Column(String(64), unique=False) company = Column(String...
from PySide2 import QtCore, QtGui, QtWidgets from qtwidgets import PasswordEdit class Window(QtWidgets.QMainWindow): def __init__(self): super().__init__() password = PasswordEdit() self.setCentralWidget(password) app = QtWidgets.QApplication([]) w = Window() w.show() app.exec_()
from .load_dicom import load_scan_from_dicom, get_pixels_hu __all__ = [load_scan_from_dicom, get_pixels_hu]
import curses import platform import terraindata as td import fielddata as field import variables as var import uidata as UI import colors import functions as func import dialogue as dial import cardfunc as cf def display(): var.window.border('|', '|', '-', '-', '#', '#', '#', '#') var.window.addstr(UI.Main....
# Copyright (c) 2013, masonarmani38@gmail.com and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe def execute(filters=None): columns = [ "Posting Date:Date:100", "Employee:Link/Employee:100", "Employee Name:Data:150", ...
import os import pickle import numpy as np from tqdm import tqdm import phns DATA_PATH = os.path.dirname(os.path.realpath(__file__)) + "/../data/" print(f"Loading data from {DATA_PATH}") with open(DATA_PATH + "timit_bench.pkl", "rb") as f: data = pickle.load(f) # missing words: # exceptions = [ # "m...
from http import HTTPStatus from unittest.mock import patch from pytest_cases import parametrize_with_cases from infobip_channels.core.models import ResponseBase from infobip_channels.email.channel import EmailChannel from tests.conftest import get_response_object def set_up_mock_server_and_send_request( httpse...
''' Test for generate_indexes module. ''' from dmrg_helpers.extract.generate_indexes import SiteFilter def test_constant(): f = SiteFilter('1') assert f.a == '1' assert f.i == None assert f.pm == None assert f.b == None assert f.is_constant() == True assert f.build_index(5) == 1 def test_o...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, BooleanField, SubmitField from wtforms.validators import DataRequired, Email, EqualTo, ValidationError from flask_babel import _, lazy_gettext as _l from blog_app.models import User class LoginForm(FlaskForm): username = StringField(_...
import time from datetime import datetime import subprocess32 as subprocess import select from .logging_ext import logger class RunResult(object): def __init__(self, text, status): self.text = text self.status = status def run_with_io_timeout(cmd, timeout_sec=120): command = ' '.join(cmd) ...
from btmonitor.pubsub import Hub from btmonitor.pubsub import Subscription import pytest @pytest.mark.asyncio async def test_pubsub_single(): hub: Hub[int] = Hub() hub.publish(1) with Subscription(hub) as queue: assert queue.empty() hub.publish(2) result = await queue.get() ...
# This code is part of Qiskit. # # (C) Copyright IBM 2020. # # 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 wo...
import re import os import gzip import argparse import numpy as np import scipy.stats as stats import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from Bio import SeqIO def plot_lengths(lengths, name): mean_len, std_len, median_len = np.mean(lengths), np.std(lengths), np.median(lengths) m...
default_app_config = 'marketing.apps.MarketingConfig'
#020 - Sorteando uma ordem na lista from random import shuffle n1 = str(input('primeiro aluno: ')) n2 = str(input('segundo aluno: ')) n3 = str(input('terceiro aluno: ')) n4 = str(input('quarto aluno: ')) lista = [n1, n2, n3, n4] shuffle(lista) print('a ordem de apresentacao sera ') print(lista)
import cv2 import numpy as np #---------------------------------------------------# # 对输入图像进行resize #---------------------------------------------------# def letterbox_image(image, size): ih, iw, _ = np.shape(image) w, h = size scale = min(w/iw, h/ih) nw = int(iw*s...
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from django.core.cache.backends.memcached import BaseMemcachedCache class PymemcacheCache(BaseMemcachedCache): """ Implementation of a pymemcache binding for Django 2.x. """ def __init__(self, server, params): ...
## # Main Module: display.py ## import configparser import tm1637 from time import sleep config = configparser.ConfigParser() config.read('config/appconfig.ini') CLK = int(config['GPIO']['clk']) DIO = int(config['GPIO']['dio']) tm = tm1637.TM1637(clk=CLK, dio=DIO) tm.brightness(7) while True: tm.scroll('HELLO...
""" PyENT: Python version of FourmiLab's ENT: Benchmarking suite for pseudorandom number sequence. (c) 2020 by Minh-Hai Nguyen """ import sys import numpy as np from scipy.stats import chi2 as spChi2 def Chi2(data,bins,min_value=None,max_value=None): """ Compute chi-square bins: int or sequence of ...
import os from model.generic_loss_functions import PFNL_generic_loss_functions from model.generic_loss_functions import NAME as PROPOSED_LOSS from model.control import PFNL_control from model.control import NAME as CONTROL from model.alternative import PFNL_alternative from model.alternative import NAME as ALTERN...
# # 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 # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
import torch import random from torch.distributions.multivariate_normal import MultivariateNormal from utils import cov class EstimationMaximisation(object): '''Gaussian Estimation Maximisation Algorithm The following models the Gaussian Estimation Maximisation algorithm. Given a set of points, we do a cl...
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint, DispatchFunction from starlette.requests import Request from starlette.responses import Response from starlette.types import ASGIApp class BrowserCachingMiddleware(BaseHTTPMiddleware): """ Enabling the caching of assets by the ...
from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r"invoices", views.InvoicesViewSet) urlpatterns = [ path("", include(router.urls)), path( "api-auth/", include("rest_framework.urls", namespace="rest_framew...
"""Add dependency matcher pipe to the pipeline.""" from array import array from collections import defaultdict, namedtuple from typing import Union import spacy from spacy.language import Language from spacy.matcher import DependencyMatcher from spacy.tokens import Span, Token from traiter.util import as_list, sign ...
from .core import contents, where __all__ = ["contents", "where"] __version__ = "2022.05.18.1"
import json if __name__ == '__main__': students_list = [] while True: command = input("Add, list, exit, load <>, save <>: ").lower() if command == 'exit': break elif command == 'add': last_name = input('Your last name^ ') class_name = ...
def main(): info('Waiting for minibone access') wait('FelixMiniboneFlag', 0) info('Minibone free') acquire('JanMiniboneFlag', clear=True) info('Minibone acquired') wait('MinibonePumpTimeFlag', 0)
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Setup for filament_watch''' import ez_setup ez_setup.use_setuptools() from setuptools import setup with open('README.md') as readme_file: README = readme_file.read() setup( name="filament_watch", version="1.0", author="Richard L. Lynch", author_...
#!/usr/bin/env python ''' Created on Feb 21, 2020 @author: gsnyder Retrieve BOM computed notifications Note: The user account you run this under will determine the scope (i.e. projects, versions) of the notifications that can be received. ''' # TODO: Use startDate filter on /api/notifications to limit the notifi...
#!/usr/bin/env python """Exercise answer 8.2 for chapter 8.""" def ui(): """The program of UI.""" while True: tip = """ Input three numbers, using ',' to seperate it. These are from,to,and increment. We'll generate a sequence for you. Using 'q' to quit this: """ inp = raw_input(tip).strip() ...
#!/usr/bin/env python import rospy import time import cv2 import sys import numpy as np import message_filters from sensor_msgs.msg import Image, CameraInfo from std_msgs.msg import Header from cv_bridge import CvBridge, CvBridgeError from openpose_ros_msgs.msg import OpenPoseHumanList from visualization_msgs.msg impo...
import json import unittest from unittest.mock import patch import requests_mock from frontstage import app from frontstage.common.eq_payload import EqPayload from frontstage.controllers import collection_exercise_controller from frontstage.exceptions.exceptions import ApiError, InvalidEqPayLoad from tests.integratio...
import requests.exceptions import google.auth.exceptions class HttpError(Exception): """Holds the message and code from cloud errors.""" def __init__(self, error_response=None): if error_response: self.message = error_response.get("message", "") self.code = error_response.get(...
"""Implementação de Pilha em Python.""" class Nodo: """Elemento de uma pilha, guardando um valor e referenciando outro Nodo. """ def __init__(self, valor): """Constrói um nodo com o valor indicado. Por padrão, não há um próximo elemento. """ self.valor = valor ...
import topi import tvm import numpy as np import torch dim0 = 8 dim1 = 3 dim2 = 4 shape_size1 = [dim0, dim1] shape_size2 = [dim0, dim2] dtype = "float32" A = tvm.te.placeholder(shape_size1, dtype=dtype, name="A") B = tvm.te.placeholder(shape_size2, dtype=dtype, name="B") C = topi.concatenate([A, B], axis=1) dC = t...
input = """ a(1,2,0). a(1,3,0). a(2,3,0). b(X) :- a(X,_,_). c(X) :- a(_,X,_). """ output = """ a(1,2,0). a(1,3,0). a(2,3,0). b(X) :- a(X,_,_). c(X) :- a(_,X,_). """
#!/usr/bin/env python3 from json import dump, load from os.path import isfile from subprocess import run import sys class colors: BOLD = "\033[1m" HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' END = '\033[0m' BOLD = '\033[1m' UN...
def sortedSquaredArray(array): smallest = 0 largest = len(array) - 1 result = [] while smallest <= largest: if abs(array[smallest]) > abs(array[largest]): val = array[smallest] smallest += 1 else: val = array[largest] largest -= 1 ...
''' 有这样一个字典d = {"chaoqian":87, “caoxu”:90, “caohuan”:98, “wuhan”:82, “zhijia”:89} 1)将以上字典按成绩排名 ''' d = {"chaoqian":87, "caoxu":90, "caohuan":98, "wuhan":82, "zhijia":89} print(sorted(d.items(),key = lambda item : item[1]))
import datetime import pandas as pd import plotly.graph_objects as go from dateutil.relativedelta import relativedelta from plotly.subplots import make_subplots def get_date_list(start_day) -> list: """시작일부터 오늘까지를 1달 간격으로 나눈 것을 리스트로 만듦""" date_list = [] start = datetime.datetime.strptime(start_day, "%Y%m...
import csv from datetime import datetime import pytz import os from ledger.settings_base import TIME_ZONE from mooringlicensing.settings import BASE_DIR from mooringlicensing.components.approvals.models import ( Approval, WaitingListAllocation, AnnualAdmissionPermit, AuthorisedUserPermit, MooringLicenc...
# Copyright (c) 2021 - present / Neuralmagic, 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 b...
from respa.settings import * # Get whitenoise for serving static files try: place = MIDDLEWARE.index('django.middleware.security.SecurityMiddleware') except ValueError: place = 0 MIDDLEWARE.insert(place, 'whitenoise.middleware.WhiteNoiseMiddleware') import environ deploy_env = environ.Env( USE_X_FORWAR...
# -*- coding: utf-8; -*- # # @file __init__.py # @brief # @author Frédéric SCHERMA (INRA UMR1095) # @date 2016-09-01 # @copyright Copyright (c) 2016 INRA/CIRAD # @license MIT (see LICENSE file) # @details """ coll-gate application initialisation """ # Application Config for startup and more... default_app_config = ...
import arcade def draw_snowflake(x,y): #90 degree up arcade.draw_line(x, y,x, y+50, arcade.color.WHITE, 3) arcade.draw_line(x, y+30, x+10, y + 40, arcade.color.WHITE, 3) arcade.draw_line(x, y+30, x-10, y + 40, arcade.color.WHITE, 3) #0 degree - right arcade.draw_line(x, y, x+50, y, arcade.col...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np from sklearn.svm import SVC import pickle from sklearn.metrics import f1_score from sklearn.metrics import accuracy_score import collections from sklearn import tree from sklearn.neural_network import MLPClassifier import time import os def _get_int_...
#!/usr/bin/env python """ obsgen.py State Estimation and Analysis for PYthon Module to process observations: obsgen : class to convert from raw to ROMS observations using specific subclasses Written by Brian Powell on 08/15/15 Copyright (c)2010--2021 University of Hawaii under the MIT-Lice...
from pydantic import BaseModel, Field, UUID4 from typing import Optional from uuid import uuid4 from api.models import type_str, validators class AlertTypeBase(BaseModel): """Represents a type of alert.""" description: Optional[type_str] = Field(description="An optional human-readable description of the ale...
#! /usr/bin/env python ''' This module is part of the FMLC package. https://github.com/LBNL-ETA/FMLC ''' import time class triggering(object): ''' Class to handle internal triggering of models. ''' def __init__(self, ts, init_now=False): ''' Input ----- ts (dict): Time...
from django.test import TestCase from django.urls import reverse from django.contrib.auth import get_user_model from django.contrib import messages from django.utils.translation import gettext_lazy as _ from nami import Nami, MemberNotFound from nami.mock import Session as NamiMock from .views import NamiSearchView ...
"""http://projecteuler.net/problem=056 Powerful digit sum A googol (10^100) is a massive number: one followed by one-hundred zeros; 100^100 is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1. Considering natural numbers of the form, a^b,...
import os import requests from b2stage.endpoints.commons.b2access import B2accessUtilities from restapi import decorators from restapi.connectors import celery from restapi.exceptions import RestApiException from restapi.services.authentication import Role from restapi.utilities.logs import log from seadata.endpoints....
import rclpy from rclpy.node import Node from robot_interfaces.srv import SetMuxSource from sensor_msgs.msg import Joy class JoyCommands(Node): def __init__(self): super(JoyCommands, self).__init__('joy_commands') self._subscription = self.create_subscription(Joy, 'joy', self.joy_cb, 10) s...
""" This module allows doctest to find typechecked functions. Currently, doctest verifies functions to make sure that their globals() dict is the __dict__ of their module. In the case of decorated functions, the globals() dict *is* not the right one. To enable support for doctest do: import typecheck.doctest...
import os from glob import glob import torch def mkdir_ifnotexists(directory): if not os.path.exists(directory): os.mkdir(directory) def get_class(kls): parts = kls.split('.') module = ".".join(parts[:-1]) m = __import__(module) for comp in parts[1:]: m = getattr(m, co...
"""Provide Hook implementations for contingency checks.""" import logging from nested_lookup import nested_lookup from boardfarm.exceptions import ContingencyCheckError from boardfarm.lib.common import ( check_prompts, domain_ip_reach_check, retry_on_exception, ) from boardfarm.lib.DeviceManager import ...
# @Author : Peizhao Li # @Contact : peizhaoli05@gmail.com import scipy.sparse as sp import torch from torch import optim import torch.nn.functional as F from args import parse_args from utils import fix_seed, find_link from dataloader import get_dataset from model.utils import preprocess_graph, project from model.o...
from mine_generate import mine_generate import random import numpy as np class Cell: def __init__(self, coordinate): self.clues = set() self.reveal = 0 self.probability = 1.0 self.neighbor = 0 self.coordinate = coordinate self.mined = -1 class MineSweeper(object):...
# ------------------------------------------------------------------------- # # Author: RRD # # Created: 24/10/2012 # Copyright: (c) rdamiani 2012 # Licence: <your licence> # ------------------------------------------------------------------------- import numpy as np def frustum(Db, Dt, H): """Th...
from __future__ import absolute_import, print_function import unittest from metavariant.components import VariantComponents, findall_aminochanges_in_text, parse_components_from_aminochange AA_synonyms = {'Leu653Arg': ['L653R', 'Leu653Arg', '(Leu653Arg)'], 'Cys344Tyr': ['(Cys344Tyr)', 'C344Y', 'Cys344...
import logging import time from typing import Optional, Tuple import numpy as np from torch import Tensor import puc from puc import PUcKernelType from apu import config from apu.datasets.types import TensorGroup from apu.utils import ViewTo1D class PUcLearner: r""" Encapsulates learning for the PUc learner"""...
from .bymean import DistanceFromMeanClassifier from .tensorflow import * from .tflearn import *
from antlr4 import Token, DiagnosticErrorListener, FileStream, CommonTokenStream from antlr4.error.ErrorListener import ErrorListener from pygls.types import Diagnostic, Range, DiagnosticSeverity, Position, Location from .antlr_build.diagnosis.SystemVerilogLexer import SystemVerilogLexer as DiagnosisLexer from .a...
# Author of Aqsa: Yulay Musin from django.conf.urls.i18n import i18n_patterns from django.conf.urls import url, include from aqsa_apps.account.urls import before_login_urlpatterns from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = ...
# Copyright (c) 2021, Mahmood Sharif, Keane Lucas, Michael K. Reiter, Lujo Bauer, and Saurabh Shintre # This file is code used in Malware Makeover """ Randomize multiple binaries to test that randomization doesn't break functionality. """ import random import time random.seed(time.time()) import sys sys.path.append(...
""" Write a Python program to append text in a existing file """ def append_text(file_name): with open(file_name, "a") as file: file.write("Django is the Python high level web framework!\n") file.write("and flask is also a good python framework") with open(file_name, "r") as read_file: ...
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from classy_vision import meters from classy_vision.meters import VideoAccuracyMeter from test.generic.m...
# generated by datamodel-codegen: # filename: schema/api/teams/createUser.json # timestamp: 2021-10-01T19:50:55+00:00 from __future__ import annotations from typing import List, Optional from pydantic import BaseModel, Field from ...entity.teams import user from ...type import basic, profile class RequestToC...
#!/usr/bin/env python # coding: utf8 # # Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES). # # This file is part of PANDORA # # https://github.com/CNES/Pandora # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may...
__author__ = 'rcj1492' __created__ = '2017.12' __license__ = 'MIT' def walk_data(input_data): ''' a generator function for retrieving data in a nested dictionary :param input_data: dictionary or list with nested data :return: string with dot_path, object with value of endpoint ''' def _walk_dict...
from testfixtures import StringComparison as S, compare from testfixtures.compat import PY2 from unittest import TestCase class Tests(TestCase): def test_equal_yes(self): self.failUnless('on 40220'==S('on \d+')) def test_equal_no(self): self.failIf('on xxx'==S('on \d+')) def test_not_equ...
from flask import Flask, request, render_template import main.judge_ques as Jg import main.judge_image as Img import main.utils as Utils import main.mock as Mock import os,json import main.db as db from main.WXBizDataCrypt import WXBizDataCrypt app = Flask(__name__) ''' @project: 官网 @author: Laurel ''' @app.route('/...
import threading class Adc(object): """Thread-safe wrapper around an ADC object.""" def __init__(self, adc): """Create a new Adc instance Args: adc: The raw ADC which this class makes thread-safe by synchronizing its read calls. """ self._adc = adc...
from setuptools import setup setup(name='comic-scraper', version='0.9.0', description='Scraps comics,mangas and creates cbz (/pdf) files for offline reading', url='https://github.com/AbstractGeek/comic-scraper', download_url='https://github.com/AbstractGeek/comic-scraper/tarball/0.9.0', a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 21 12:06:17 2018 @author: zoli """ from export.filter_volumes import filter_volumes def get_server_name(server_id:str,instances:list) -> str: for instance in instances: if instance.id == server_id: return instance.name...
# Copyright 2021 IBM Corp. # SPDX-License-Identifier: Apache-2.0 import unittest import sys from xskipper import Registration from xskipper.testing.utils import XskipperTestCase class XskipperRegistrationTests(XskipperTestCase): def setUp(self): super(XskipperRegistrationTests, self).setUp() def te...
import example print(f"result={example.add(2, 5)}")
import FWCore.ParameterSet.Config as cms # DQM Environment dqmEnv = cms.EDAnalyzer("DQMEventInfo", # put your subsystem name here (this goes into the foldername) subSystemFolder = cms.untracked.string('YourSubsystem'), # set the window for eventrate calculation (in minutes) eventRateWindow = cms.untrac...
from unittest import TestCase from mock import Mock, MagicMock, patch from broker.service.spreadsheet_upload_service import SpreadsheetUploadService class SpreadsheetUploadServiceTest(TestCase): def setUp(self) -> None: self.ingest_api = Mock('ingest_api') self.storage_service = Mock('storage_...
from rest_framework.schemas import AutoSchema class CustomSchema(AutoSchema): def get_link(self, path, method, base_url): link = super().get_link(path, method, base_url) link._fields += self.get_core_fields() return link def get_core_fields(self): return getattr(self.view, "co...
import sys executable = sys.executable import mpi4py mpi4py.rc.threads = False # no multithreading... from mpi4py import MPI def xtomo_reconstruct(data, theta, rot_center='None', Dopts=None, order='sino'): if order != 'sino': data=np.swapaxes(data,0,1) if type(Dopts)==type(None): Dopts={ 'algo'...
import requests theEnum = {'place': '位置', 'kind': '類型', 'rentprice': '租金', 'area': '坪數'} region = {} region[0] = [ {'id': 0, 'txt': '北部'}, {'id': 1, 'txt': '台北市'}, {'id': 3, 'txt': '新北市'}, {'id': 6, 'txt': '桃園市'}, {'id': 4, 'txt': '新竹市'}, {'id': 5, 'txt': '新竹縣'}, {'id': 21, 'txt': '宜蘭縣'}, ...
import os, json, time, gc, copy, shutil, random, pickle, sys, pdb from datetime import datetime import numpy as np from allennlp.common.tee_logger import TeeLogger from allennlp.modules.text_field_embedders import TextFieldEmbedder, BasicTextFieldEmbedder from allennlp.modules.token_embedders import PretrainedTransform...
"""2d Helmholtz""" from .base_fun import fun_cst, fun_cst_der from .calc_field import far_field, incident_field, scattered_field, total_field from .prob_cst import create_problem_cst
from stt import Transcriber import glob import os BASE_DIR = '/home/sontc/PycharmProjects/VPS/wave2vec_2/self-supervised-speech-recognition' transcriber = Transcriber(lm_weight=1.51, word_score=2.57, beam_size=100) result = [] file_names, data = [], [] for i, file_path in enumerate(glob.glob('converted_wavs/*', rec...
import time import psycopg2 from Protocol import * import threading DATABASE_ADDRESS = "NONE" DATABASE_NAME = "NONE" DATABASE_SCHEME = "NONE" DATABASE_USER = "NONE" DATABASE_PASSWORD = "NONE" DATABASE_PORT = "NONE" SECRET_KEY = b'\xf8[\xd6\t<\xd8\x04a5siif\x93\xdc\xe0' IV = b'\x8e;\xf21bB\x0c\x95\x93\xce\xe9J3,\x04\x...
from django.shortcuts import render from forms import contactForm from django.core.mail import send_mail from django.conf import settings # Create your views here. def contact(request): title = 'Contact' form = contactForm(request.POST or None) confirm_message = None if form.is_valid(): name ...
#!/usr/bin/env python from multiprocessing import Event import json import time # from pygecko.multiprocessing import geckopy # from pygecko.transport.zmq_sub_pub import Pub, Sub from pygecko.transport.zmq_req_rep import Reply, Request from pygecko.multiprocessing.process import GeckoSimpleProcess from pygecko import...
from reports.models import Station def station_list(request): # pylint: disable=unused-argument stations = list() for station in Station.objects.all(): station.incidents_count = station.incidents.count() stations.append(station) return {'station_list': stations}
from __future__ import print_function, unicode_literals """ This file pretends to make it possible that all the unit tests use a particular and somehow configurable port range (e.g. 10500 - 11000), so as to avoid conflicts with other applications. At this moment, the system uses random ports which are in conflict wit...
# Copyright (c) 2022 Dai HBG """ 该脚本用于将1分钟数据中不在市的部分删除 """ import os import pandas as pd def main(): data_path = 'D:/Documents/AutoFactoryData' intra_path = 'E:/Backups/AutoFactoryData/StockIntraDayData/1m' dates = os.listdir(intra_path) for date in dates: all_securities = pd.read_csv('{}/S...
# Copyright (c) 2021, zerodha and contributors # For license information, please see license.txt import frappe from frappe.model.document import Document class RobinChapterMapping(Document): """Mapping.""" def before_insert(self): if not self.user: self.user = frappe.session.user @frap...
#Oskar Svedlund #TEINF-20 #24-08-21 #Welcome screen print("Welcome to the game.") name = input("What is your name? ") print("Glad you're back, " + name) cats = input("How many cats did you se on your way here? ") paws = int(cats) * 4 print("so you saw" , cats, "cats on your way here? Thats like", paws, "paws. cool")
# Generated by Django 2.1.7 on 2019-03-20 03:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('forum_permission', '0003_remove_forumpermission_name'), ] operations = [ migrations.RemoveField( model_name='forumpermission', ...
from abc import ABCMeta, abstractmethod from future.utils import with_metaclass, iteritems class OpticAxisRule(with_metaclass(ABCMeta, object)): # return values of neighbor_that_send_photor_to and # neighbor_that_provide_photor should be the # following: # [x] is the neighbor at position x # [x, y...
"""Add vehicle table Revision ID: 1e99b5efb76f Revises: 2bbd670f53b4 Create Date: 2020-05-24 15:29:19.928946 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "1e99b5efb76f" down_revision = "2bbd670f53b4" branch_labels = ...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.rst') as f: readme = f.read() with open('LICENSE') as f: license = f.read() setup( name='datatransfer', version='1.0', description='the data transfering module to use scp.', long_description=None, aut...
#!/usr/bin/env python #coding: utf-8 from riak_common import * import riak import redis import numbers def _set_expecting_numeric_response(nutcracker, key, value): response = nutcracker.set(key, value) if not isinstance(response, numbers.Number): raise Exception('Expected nutcracker.set to return a nu...
#!/usr/bin/env python3 import sys import yaml config = {} with open(sys.argv[1]) as raw: config = yaml.load(raw) def alias_for_cluster(cluster): if cluster == "api.ci": return "ci" # why do we still do this?? return cluster def internal_hostnames_for_cluster(cluster): if cluster == "api.ci"...