content
stringlengths
5
1.05M
from setuptools import setup setup(name='safygiphy', version='1.1.1', description='API Wrapper for the online Gif library, Giphy', url='https://code.tetraetc.com/SafyGiphy/', author="TetraEtc", author_email="administrator@tetraetc.com", install_requires=[ 'requests' ...
from mypy import api from redun.tests.utils import get_test_file def test_task_types() -> None: """ mypy should find type errors related to redun task calls. """ workflow_file = get_test_file("test_data/typing/workflow_fail.py.txt") stdout, stderr, ret_code = api.run( [ "--sh...
from collections import Counter l = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8] # print(Counter(l)) s = 'aaassssvvvveeeeedddddccccccceeelllll' # print(Counter(s)) word = 'How many times does each word show up in this sentence word word show up' words = word.s...
"""Process ACL states""" from __future__ import absolute_import import logger from utils import dict_proto from proto.acl_counting_pb2 import RuleCounts LOGGER = logger.get_logger('aclstate') class AclStateCollector: """Processing ACL states for ACL counting""" def __init__(self): self._switch_co...
from sqlalchemy.orm import joinedload from FlaskRTBCTF.utils.models import db, TimeMixin, ReprMixin from FlaskRTBCTF.utils.cache import cache # Machine Table class Machine(TimeMixin, ReprMixin, db.Model): __tablename__ = "machine" __repr_fields__ = ( "name", "os", ) id = db.Column(db....
# This file is part of Peach-Py package and is licensed under the Simplified BSD license. # See license.rst for the full text of the license. from enum import IntEnum class FileType(IntEnum): # No file type null = 0 # Relocatable file object = 1 # Executable file executable = 2 # Fixed...
from requests.exceptions import ConnectionError, HTTPError, SSLError from sentry.exceptions import PluginError from django.utils.translation import ugettext_lazy as _ from sentry_youtrack.forms import VERIFY_SSL_CERTIFICATE from sentry_youtrack.youtrack import YouTrackClient class YouTrackConfiguration(object): ...
class Solution: def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
import signal import sys import time from collections import deque import traceback from picrosolve.game.cell import CellList from .strategies.all import ALL_STRATEGIES class Solver(object): def __init__(self, board, strategies=None, debug=False): self._board = board if not strategies: ...
#!/usr/bin/python # -*- coding: utf-8 -*- import aredis import asyncio import pytest import sys from unittest.mock import Mock from distutils.version import StrictVersion _REDIS_VERSIONS = {} async def get_version(**kwargs): params = {'host': 'localhost', 'port': 6379, 'db': 0} params.update(kwargs) key...
import urllib2 from bs4 import BeautifulSoup import re response = urllib2.urlopen("http://www.baidu.com") # html_doc = response.read() html_doc = '<div id="u_sp" class="s-isindex-wrap s-sp-menu"> <a href="http://www.nuomi.com/?cid=002540" target="_blank" class="mnav">糯米</a> <a href="http://news.baidu.com" target="_bla...
from kapteyn import maputils from matplotlib import pylab as plt header = {'NAXIS': 2 ,'NAXIS1':100 , 'NAXIS2': 100 , 'CDELT1': -7.165998823000E-03, 'CRPIX1': 5.100000000000E+01 , 'CRVAL1': -5.128208479590E+01, 'CTYPE1': 'RA---NCP', 'CUNIT1': 'DEGREE ', 'CDELT2': 7.165998823000E-03 , 'CRPIX2': 5.100000000000E+01, 'CRV...
import neptune.new as neptune import os from GTApack.GTA_hotloader import GTA_hotloader from GTApack.GTA_Unet import GTA_Unet from GTApack.GTA_tester import GTA_tester from torchvision import datasets, transforms from torch.optim import SGD, Adam from torch.optim.lr_scheduler import (ReduceLROnPlateau, CyclicLR, ...
# -*- coding: utf-8 -*- import json import re import requests import urllib import logging logger = logging.getLogger('nova-playlist') class YouTubeAPI(object): clientID = 'CLIENTID' clientSecret = 'CLIENTSECRET' refreshToken = 'REFRESHTOKEN' accessToken = None def get_access_token(self): ...
import asyncio import datetime def get_time(): d = datetime.datetime.now() return d.strftime('%M:%S') async def coro(group_id, coro_id): print('group{}-task{} started at:{}'.format(group_id, coro_id, get_time())) await asyncio.sleep(coro_id) # 模拟读取文件的耗时IO return 'group{}-task{} done at:{}'.form...
import cv2 def draw_yolo_detections(image, detections, color=(0,255,0)): img = image.copy() with open("..//Data//model//yolov4/coco.names", 'rt') as f: classes = f.read().rstrip('\n').split('\n') for detect in detections: bbox = detect[1] category = classes[int(detect[0])] ...
import dataclasses import vk_api from vk_api import VkUpload from vk_api.bot_longpoll import VkBotLongPoll from vk_api.longpoll import VkLongPoll, VkEventType from vk_api.utils import get_random_id @dataclasses.dataclass class __cfg__: """ Bot config is struct for every bot. Easy to use because of fields """ ...
# F2x installation script (setup.py) # # Copyright 2018 German Aerospace Center (DLR) # # 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 # # Un...
from hashlib import md5 def part_1(data): i, p = 0, "" while True: if len(p) == 8: break hash = md5((data + str(i)).encode()).hexdigest() if hash[:5] == "00000": p += hash[5] i += 1 return p def part_2(data): i, p = 0, "________" while True...
import logging from typing import Iterable from septentrion import core, db, files, migration, style, versions logger = logging.getLogger(__name__) def initialize(settings_kwargs): quiet = settings_kwargs.pop("quiet", False) stylist = style.noop_stylist if quiet else style.stylist settings = core.initi...
# Copyright (c) 2020, Huawei Technologies.All rights reserved. # Licensed under the BSD 3-Clause License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # Unless required by applicable...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Date string field.""" from __future__ import absolute_import, print_function imp...
import unittest import numpy as np from modem.util.channel import Channel def get_random(samples=2048): """Returns sequence of random comples samples """ return 2 * (np.random.sample((samples,)) + 1j * np.random.sample((samples,))) - (1 + 1j) class test_channel(unittest.TestCase): def setUp(s...
# !/usr/bin/env python3 # -*- coding: utf-8 -*- import urllib.request requestUrl = 'http://www.tvapi.cn/movie/getMovieInfo' webhead = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0', 'charset':'utf-8'} urlRequest = urllib.request.Request(url = requestUrl, headers = webhea...
import ckan.logic as logic import ckan.model as model import unicodedata import ckanext.hdx_users.model as umodel import ckanext.hdx_user_extra.model as ue_model import ckanext.hdx_theme.tests.hdx_test_base as hdx_test_base class TestAboutPageController(hdx_test_base.HdxBaseTest): #loads missing plugins ...
# -*- coding: utf-8 -*- """ Utilities for analysis Author: G.J.J. van den Burg License: See LICENSE file. Copyright: 2021, The Alan Turing Institute """ from collections import namedtuple Line = namedtuple("Line", ["xs", "ys", "style", "label"]) def dict2tex(d): items = [] for key, value in d.items(): ...
""" Dexter Legaspi - dlegaspi@bu.edu Class: CS 521 - Summer 2 Date: 07/22/2021 Term Project Main view/window """ import tkinter as tk from tkinter import messagebox, filedialog from PIL import ImageTk, Image as PILImage import appglobals from appcontroller import AppController from appstate import AppState from image ...
import typing import pytest from energuide import bilingual from energuide import element from energuide.embedded import code from energuide.exceptions import InvalidEmbeddedDataTypeError @pytest.fixture def raw_wall_code() -> element.Element: data = """ <Code id='Code 1'> <Label>1201101121</Label> <Layer...
__doc__ = """ 样例: 传给topic_metadata函数的内容 args = { 'pattern' : "https://mirrors.tuna.tsinghua.edu.cn/help/%s", 'themes' :["AOSP", "AUR","CocoaPods" , "anaconda","archlinux","archlinuxcn" ,"bananian","centos","chromiumos","cygwin" ,"docker","elpa","epel","fedora","git-repo" ,"git...
"""This module demonstrates basic Sphinx usage with Python modules. Submodules ========== .. autosummary:: :toctree: _autosummary """ VERSION = "0.0.1" """The version of this module."""
#!/usr/bin/env python3 # pyreverse -p contexts_basecontext_basecontext ../Lib/pagebot/contexts/basecontext/basecontext.py # dot -Tpng classes_contexts_basecontext_basecontext.dot -o classes_contexts_basecontext_basecontext.png import os import subprocess def getDirs(root): return [d for d in os.listdir(root) if ...
#!/usr/bin/env python3 # # Copyright 2021 Google LLC # # 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 o...
# from django.contrib.oauth.models import User from rest_framework import authentication from rest_framework import exceptions import logging log = logging.getLogger(__name__) import json, re from django.core.cache import cache from django.conf import settings class TokenAuthentication(authentication.BaseAuthentic...
# Input: a list of "documents" at least containing: "sentences" # Output: a list of "documents" at least containing: "text" from .simplifier import Simplifier class SimplifierByKGen: def __init__(self, parameters): # some prepartion # no parameter is needed print("Info: Simplifier By KGe...
from django.conf import settings from django.core.files.storage import get_storage_class from storages.backends.s3boto3 import S3Boto3Storage # if settings.DEBUG: # PublicMediaStorage = get_storage_class() # PrivateMediaStorage = get_storage_class() # else: from config.settings import dev class PublicMediaSto...
######### # Copyright (c) 2015 GigaSpaces Technologies Ltd. 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...
""" Represents a square stop. """ from BeamlineComponents.Stop.StopRectangle import StopRectangle class StopSquare(StopRectangle): def __init__(self, side_length): StopRectangle.__init__(self, side_length, side_length) def sideLength(self): return self.lengthVertical()
import urllib, json from jwcrypto import jwt, jwk class OpenIDTokenValidator: def __init__(self, config_url, audience): """ Retrieve auth server config and set up the validator :param config_url: the discovery URI :param audience: client ID to verify against """ # ...
""" Tests for attention module """ import numpy as np import theano import theano.tensor as T import agentnet from agentnet.memory import GRUCell from agentnet.memory.attention import AttentionLayer from lasagne.layers import * def test_attention(): """ minimalstic test that showcases attentive RNN that reads...
# coding: utf-8 # $Id: $ from celery import Celery from celery.utils.log import get_task_logger, get_logger CELERY_CONFIG = { 'BROKER_URL': 'amqp://guest@localhost/', 'CELERY_RESULT_BACKEND': "redis://localhost/0", 'CELERY_TASK_SERIALIZER': "pickle", 'CELERY_RESULT_SERIALIZER': "pickle", 'CELERYD_...
from pyparsing import * import act topnum = Forward().setParseAction(act.topnum) attacking = Forward().setParseAction(act.attacking) blocking = Forward().setParseAction(act.blocking) tapped = Forward().setParseAction(act.tapped) untapped = Forward().setParseAction(act.untapped) enchanted = Forward().setParseAction(a...
import functools import numpy as np import pytest from ansys import dpf from ansys.dpf.core import examples from ansys.dpf.core import misc NO_PLOTTING = True if misc.module_exists("pyvista"): from pyvista.plotting import system_supports_plotting NO_PLOTTING = not system_supports_plotting() @pytest.fixtu...
import os.path as osp from .builder import DATASETS from .custom import CustomDataset @DATASETS.register_module() class Combine(CustomDataset): """PascalContext dataset. In segmentation map annotation for PascalContext, 0 stands for background, which is included in 60 categories. ``reduce_zero_label`` i...
<CustButton@Button>: font_size: 32 <SudGridLayout>: id = sudoku cols: 9 rows: 9 spacing = 10 BoxLayout: spacing = 10 CustButton: text: = "7" CustButton: text: = "8"
#!/usr/bin/env python # Returns a list of datetimes ranging from yesterday's # date back to 2014-03-30 or if passed a first argument # back to the first argument import sys import datetime yesterday = (datetime.datetime.today() - datetime.timedelta(days=1)) opening_date = datetime.datetime(2014, 03, 30) if len(sys....
from patchify import patchify, unpatchify from matplotlib import image as mpimg from matplotlib import pyplot as plt import cv2 as cv from PIL import Image import numpy as np from patchfly import patchfly, unpatchfly import os # ---------------------- # get a image from internet # ---------------------- # url = "htt...
from unittest import TestCase from moff.parser import Parser from moff.node import VideoNode, SourceNode, ParagraphNode, LinkNode, TextNode class TestReadVideo (TestCase): def test_parse1(self): parser = Parser() node1 = parser.parse_string("@video example.mp4") node2 = VideoNode( ...
#!/usr/bin/python import json import sys from datetime import datetime from pprint import pprint def dateconv(d): return datetime.strptime(d, "%Y-%m-%dT%H:%M:%S.%fZ").strftime("%Y-%m-%d %a %H:%M") def printtask(task, lev): print("%s %s %s" % ( lev, ("DONE" if task["completed"] else "TODO"), ...
import unittest from mitama._extra import _classproperty class TestClassProperty(unittest.TestCase): def test_getter(self): class ClassA: @_classproperty def value(cls): return "hello, world!" self.assertEqual(ClassA.value, "hello, world!")
from asyncio.events import AbstractEventLoop import inspect from typing import Any, Coroutine, List, Tuple, Protocol, Union from xml.etree.ElementTree import Element, XML from aiohttp import web import xml.etree.ElementTree as ET import socket XMLRPCValue = Any #TODO FIXME def parse_args(params: List[Element]): a...
from abc import ABC from abc import abstractmethod from dataclasses import dataclass from dataclasses import field from io import IOBase from numpy import integer from syntax import SyntaxBlock from syntax import SyntaxStatement from syntax import SyntaxTerm from typing import Dict from typing import List from typing i...
from flask import render_template_string from datetime import datetime from actions.action import BaseAction from models import ISTHISLEGIT_SVC from models.email import EmailResponse from models.event import EventReportResponded from models.template import Template from services.email import email_provider def get_t...
from account.conf import settings from account.models import Account def account(request): ctx = { "account": Account.for_request(request), "ACCOUNT_OPEN_SIGNUP": settings.ACCOUNT_OPEN_SIGNUP, } return ctx
def create_info_2dfaces(cellid:'int[:,:]', nodeid:'int[:,:]', namen:'int[:]', vertex:'double[:,:]', centerc:'double[:,:]', nbfaces:'int', normalf:'double[:,:]', mesuref:'double[:]', centerf:'double[:,:]', namef:'int[:]'): from numpy import double, zeros, sqrt ...
import datetime import hashlib import json from typing import Dict import uuid class Utility(object): @staticmethod def make_json_serializable(doc: Dict): """ Make the document JSON serializable. This is a poor man's implementation that handles dates and nothing else. This method modi...
image_directory = "./images/"
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- try: ...
from abc import ABC, abstractmethod import pandas as pd class ReducerAbstract(ABC): @abstractmethod def transform(self, df: pd.DataFrame) -> pd.DataFrame: ...
import difflib import json import re from itertools import zip_longest try: import html except ImportError: html = None def _mark_text(text): return '<span style="color: red;">{}</span>'.format(text) def _mark_span(text): return [_mark_text(token) for token in text] def _markup_diff(a, ...
project = "Programmation en Python" copyright = "2020, Dimitri Merejkowsky" author = "Dimitri Merejkowsky - Contenu placé sous licence CC BY 4.0" version = "0.3" language = "fr" copyright = "CC BY 4.0" templates_path = ["_templates"] exclude_patterns = [] keep_warnings = True extensions = [ "notfound.extension"...
""" Implements a decorator that counts the number of times a function was called, and collects statistics on how long it took to execute every single function call. """ from time import time from sys import stderr, stdout import numpy as np class FunctionLogger(object): """ stores two dictionaries: - ...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. 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 cop...
from .walker import RandomWalker class Node2Path: def __init__(self, graph, walk_length, num_walks, p=1.0, q=1.0, workers=1): self.graph = graph self.walk_length = walk_length self.num_walks = num_walks self.p = p self.q = q self.workers = workers def get_path...
#!/usr/bin/env python import json import argparse import docker # A Simple module that returns stats for given ids. def get_nested_elements(info, elements): # Function to traverse dictionaries and print when value is # not a dict (instead it's a str) # pdb.set_trace() if isinstance(elements, str): ...
from pyspark.sql import SparkSession from pyspark.ml import Pipeline from pyspark.ml.feature import VectorAssembler from pyspark.ml.regression import LinearRegression from pyspark.ml.evaluation import RegressionEvaluator import matplotlib.pyplot as plt import numpy as np def read_data(file_path): cars_df = spark....
from collections import OrderedDict from typing import Optional from queryfs.db.schema import Schema class File(Schema): table_name: str = "files" fields: OrderedDict[str, str] = OrderedDict( { "id": "integer primary key autoincrement", "name": "text", "hash": "text...
#!/usr/bin/env python2.7 import os import sys sys.path.append(os.path.realpath(__file__ + '/../../../../lib')) import udf from udf import useData, expectedFailure class GetpassTest(udf.TestCase): def setUp(self): self.query('CREATE SCHEMA getpass', ignore_errors=True) self.query('OPEN SCHEMA get...
from scipy.io import netcdf import numpy as np import numpy.matlib tave = 900 basedir = '/marconi_work/FUA34_MULTEI/stonge0_FUA34/rad_test/2nd_deriv/T1/' basedir = '/marconi_work/FUA34_MULTEI/stonge0_FUA34/rad_test/2nd_deriv/rho_scan2/r0.001/' basedir = '/marconi_work/FUA34_MULTEI/stonge0_FUA34/rad_test/fg_drive/r...
"""Data structures supporting the who wrote this news crawler. ---- Copyright 2019 Data Driven Empathy LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without ...
""" Module for controlling motors. """ __all__ = [ "stepper", ]
from rest_framework import serializers from .models import CrashCourse, CourseChapter, ChapterSection class CrashCourseSerializer(serializers.ModelSerializer): no_of_chapter = serializers.SerializerMethodField() class Meta: model = CrashCourse fields = ('id', 'title', 'slug', 'no_of_chapter') ...
#!/usr/bin/env python3 # Test whether a PUBLISH to a topic with QoS 2 results in the correct packet flow. from mosq_test_helper import * rc = 1 keepalive = 60 connect_packet = mosq_test.gen_connect("test-helper", keepalive=keepalive) connack_packet = mosq_test.gen_connack(rc=0) mid = 128 publish_packet = mosq_test....
import time class Logger: def __init__(self) -> None: pass def log(self, message: str) -> None: print(f'{time.ctime()}: {message}')
# coding: utf-8 from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model from bitmovin_api_sdk.models.av1_adaptive_quant_mode import Av1AdaptiveQuantMode from bitmovin_api_sdk.models.av1_key_placement_mode import Av1KeyPlacementMode from bitmovin_api_sdk...
#!/usr/bin/env python # Copyright 2016 The TensorFlow 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 # # Unle...
import hassapi as hass # # App to turn lights on and off at sunrise and sunset # # Args: # # on_scene: scene to activate at sunset # off_scene: scene to activate at sunrise class OutsideLights(hass.Hass): def initialize(self): # Run at Sunrise self.run_at_sunrise(self.sunrise_cb) # Run ...
#Hello World python script print("Hello World") for i in range(0, 100, 5): print(i**2) # y = 'Hello' # y * 5 # y * 5.0 w = 5 / 3 x = 5.0 / 3 y = 5.0 // 3.0 z = 5 % 3 print(w, x, y, z) # Variable points to the "object" (unlike C it does not hold the value) # y = 'Hello' # z = 'hello' # print(id(y), id(z)) # a...
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # import sys from destination_google_sheets import DestinationGoogleSheets if __name__ == "__main__": DestinationGoogleSheets().run(sys.argv[1:])
PK
import uuid import os from django.db import models from django.urls import reverse from django.utils import timezone from django.conf import settings from django.utils.translation import gettext_lazy as _ from .utils import auto_delete_filefields_on_delete class File(models.Model): name = models.CharField(max_len...
from aiomotorengine import StringField, IntField, BooleanField, FloatField, DateTimeField, ReferenceField, ListField from xt_base.document.source_docs import InfoAsset from xt_base.document.base_docs import Project from dtlib.aio.base_mongo import MyDocument from dtlib.tornado.account_docs import Organization from dtl...
<caret>a = 1 # surprise! b = 2
# VNA_characteristics_classes_creators from enum import enum print "U R in VnaEnums" # Flag 4 debug SweepType = enum(LINEAR=1, LOG=2, SEGM=3, POW=4) SParameters= enum(S11=1, S12=2, S21=3, S22=4) CalType = enum(OPEN=1, SHORT=2, THRU=3, FULL_2PORT=4, FULL_1PORT=5, TRL_2PORT=6) DataFormat = enum(LOG=1, LIN=2, LIN_PHASE=...
from mongoengine import ( DateTimeField, IntField, EmbeddedDocument, StringField, EmbeddedDocumentListField, BooleanField, ) from mongoengine import Document class UserEvent(EmbeddedDocument): event_id = StringField() type = StringField() timestamp = DateTimeField() state = Str...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.TimePeriodRule import TimePeriodRule from alipay.aop.api.domain.TimePeriodRule import TimePeriodRule class VoucherTemplateInfo(object): def __init__(self): self._amou...
""" Script for generating AE examples. """ import argparse import importlib import numpy as np import os from PIL import Image import shutil import sys import torch from tqdm import tqdm from apfv21.attacks.tidr import TIDR from apfv21.attacks.afv import AFV from apfv21.utils import img_utils, imagenet_utils import ...
import csv import os import pandas as pd import numpy as np import matplotlib.pyplot as plt import math pd.options.display.max_columns = None pd.options.display.max_rows = None # Load the pre-processsed dataset df = pd.read_hdf('pre-processed.h5') # Shuffling the dataset df = df.sample(frac=1).reset_inde...
import matplotlib.pyplot as plt import cv2 as cv from color_component import get_channel, remove_channel img = cv.imread('color_img.png') plt.subplot(3, 1, 1) imgRGB = img[:, :, ::-1] plt.imshow(imgRGB) ch = 1 imgSingleChannel = get_channel(img, ch) imgRGB = cv.cvtColor(imgSingleChannel, cv.COLOR_BGR2RGB) plt.subp...
# Generated by Django 3.0 on 2020-01-06 16:21 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('content', '0001_initial'), migrations.swappable_dependency(settin...
from django.shortcuts import render from django.http import HttpResponse from .models import Pizza def index(request): messages = ['Welcome Pizza Lovers', 'Our currently available Pizzas are:'] for pizza in Pizza.objects.all(): messages.append(str(pizza)) for topping in pizza.topping_set.all...
import time import traceback import logging import os import matplotlib.pyplot as plt log = logging.getLogger(__name__) log.setLevel(logging.INFO) from pycqed.analysis import analysis_toolbox as a_tools class AnalysisDaemon: """ AnalysisDaemon is a class that allow to process analysis in a separate pytho...
# Copyright (c) 2015 Scott Christensen # # This file is part of htpython modified from condorpy # # condorpy/htpython is free software: you can redistribute it and/or modify it under # the terms of the BSD 2-Clause License. A copy of the BSD 2-Clause License # should have be distributed with this file. from collection...
#!/usr/bin/env python # landScraper.py -v 1.7 # currently designed for python 3.10.2 # Author- David Sullivan # # Credit to Michael Shilov from scraping.pro/simple-email-crawler-python for the base for this code # # As a reminder, web scraping for the purpose of SPAM or hacking is illegal. This tool has been provided f...
""" Dailymotion OAuth2 support. This adds support for Dailymotion OAuth service. An application must be registered first on dailymotion and the settings DAILYMOTION_CONSUMER_KEY and DAILYMOTION_CONSUMER_SECRET must be defined with the corresponding values. User screen name is used to generate username. By default ac...
import sys import urllib2 import zlib import time import re import xml.dom.pulldom import operator import codecs from optparse import OptionParser nDataBytes, nRawBytes, nRecoveries, maxRecoveries = 0, 0, 0, 3 def getFile(serverString, command, verbose=1, sleepTime=0): global nRecoveries, nDataBytes, nRawBytes if s...
from WonderPy.core.wwConstants import WWRobotConstants from .wwSensorBase import WWSensorBase _rcv = WWRobotConstants.RobotComponentValues _expected_json_fields = ( _rcv.WW_SENSOR_VALUE_DISTANCE, ) class WWSensorWheel(WWSensorBase): def __init__(self, robot): super(WWSensorWheel, self).__init__(robo...
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2022, Anaconda, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #---------------------------------------------------...
from ..check import Check from ..exceptions import CheckError def is_number(check_obj): try: assert isinstance(check_obj._val, check_obj.NUMERIC_TYPES) return check_obj except AssertionError: raise CheckError('{} is not a number'.format(check_obj._val)) def is_not_number(check_obj): ...
import os import json import time import torch from torch import optim import models from utils import reduce_lr, stop_early, since _optimizer_kinds = {'Adam': optim.Adam, 'SGD': optim.SGD} class SimpleLoader: def initialize_args(self, **kwargs): for key, val in kwargs.i...
# -*- coding: utf-8 -*- # # This file is part of File Dedupe # Copyright (C) 2015 Lars Holm Nielsen. # # File Dedupe is free software; you can redistribute it and/or # modify it under the terms of the Revised BSD License; see LICENSE # file for more details. """Small utility for detecting duplicate files.""" import o...