content
stringlengths
5
1.05M
import FWCore.ParameterSet.Config as cms from L1Trigger.TrackTrigger.ProducerSetup_cfi import TrackTrigger_params TrackTriggerSetup = cms.ESProducer("tt::ProducerSetup", TrackTrigger_params)
from django.contrib import admin # Register your models here. from .models import UserInfo, Owns, Balance, Ticket admin.site.register(UserInfo) admin.site.register(Owns) admin.site.register(Balance) admin.site.register(Ticket)
#!/usr/bin/env python2 from __future__ import print_function import sys import json import base64 from time import sleep import urllib2 import ssl import subprocess def get_credentials(): """ Get consul api password from security.yml """ # TODO: is this the correct YAML key for the Consul API password? yam...
# Utils for dealing with VCF generated by nextstrain.py, with a particular style of ID # and clades appearing in genotypes... from collections import defaultdict def readVcfSampleClades(vcfFile): """Read VCF sample IDs from the #CHROM line, and parse out clades from the first row GT cols""" samples = [] s...
from astropy.coordinates import jparser from io import BytesIO import urllib.request import logging import re from pathlib import Path import numbers import numpy as np from astropy.io import fits from astropy.time import Time from astropy.coordinates import SkyCoord, EarthLocation, UnknownSiteException from astropy.c...
#!/usr/bin/python # -*- coding: utf-8 -*- import pika # 加入验证,不加默认user=guser,password=guser credentials = pika.PlainCredentials(username="admin", password="123") # 构造链接对象 connection = pika.BlockingConnection( pika.ConnectionParameters( host="192.168.1.100", # 交换机ip port=5672, # 队列端口 virtua...
from PyQt5 import QtGui from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt from PyQt5.QtGui import QPainter from PyQt5.QtCore import QRect, QPoint, Qt from pyqtgraph.parametertree import Parameter, ParameterTree from ..helpers import QtHelpers from ..parameters.parameters import Parameters from typing import Di...
import unittest from app.models import Category from app import db class CategoryModelTest(unittest.TestCase): """Class that tests the Category Model.""" def setUp(self): """Set Up Test that creates a new category instance""" self.new_category = Category(name="interview pitch") ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from .common import CHROMATICITY_DIAGRAM_TRANSFORMATIONS, Cycle __all__ = ['CHROMATICITY_DIAGRAM_TRANSFORMATIONS', 'Cycle']
# http://www.codingdojo.org/cgi-bin/index.pl?KataPokerHands from enum import Enum RESULTS = Enum('RESULTS', 'WIN DRAW LOSE') def poker_hands(a, b): def get_score(x): return ask_rank_score(ask_rank(x)) rank_a, rank_b = ask_rank(a), ask_rank(b) win_card, win_rank = None, None score_a, score_b...
### # Sample data loading code. Adapted from MNE Python. # # All credit to: ## #### # Authors: Alexandre Gramfort <[email protected]> # Martin Luessi <[email protected]> # Eric Larson <[email protected]> # Denis Egnemann <[email protected]> # License: BSD Sty...
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url urlpatterns = patterns( 'dnd.races.views', # races url( r'^$', 'race_index', name='race_index', ), # races > by rulebooks url( r'^by-rulebooks/$', 'race_list_by_rulebook', name=...
from itertools import chain from typing import List from collections import namedtuple, defaultdict import logging logger = logging.getLogger() EC2Url = namedtuple('EC2Url', ['url', 'instance_id']) def get_ec2_urls(ec2_client) -> List[EC2Url]: """ Returns a collection of EC2 instances URL addresses whic...
from django.shortcuts import render def home(request): return render(request, 'pages/home.html')
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from .base_armour import Armour from ... import material as M class BaseCloak(Armour): pass class MummyWrapping(Bas...
from .core import * from .interaction import * from .normalization import * from .activation import * from .sequence import *
# Copyright 2016 Hewlett Packard Enterprise Development LP # # 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 ...
import os from datetime import datetime, timedelta import pandas as pd import populartimes from apikeys import API_KEY HOURS_OF_INTEREST = { 'restaurant': range(9, 23), 'bar': list(range(12, 24)) + list(range(0, 4)), 'club': list(range(20, 24)) + list(range(0, 6)), 'train station': range(5, 21), ...
--- ffi/build.py.orig 2018-09-21 19:31:30 UTC +++ ffi/build.py @@ -155,7 +155,7 @@ def main(): main_win32() elif sys.platform.startswith('linux'): main_posix('linux', '.so') - elif sys.platform.startswith(('freebsd','openbsd')): + elif sys.platform.startswith(('freebsd','openbsd', 'dragonfl...
""" Display a labels layer above of an image layer using the add_labels and add_image APIs """ from skimage import data from skimage.color import rgb2gray from skimage.segmentation import slic import napari with napari.gui_qt(): astro = data.astronaut() # initialise viewer with astro image viewer = napa...
import traceback from requests_futures.sessions import FuturesSession from time import sleep from urllib.parse import urljoin import json from requests.exceptions import ConnectionError import urllib3 import logging from typing import List logger = logging.getLogger('PROV') offline_prov_log = logging.getLogger("OFFLINE...
try: from urllib.request import urlopen # Python 3 except ImportError: from urllib2 import urlopen # Python 2 import os import re import tempfile from contextlib import contextmanager import six URL_REGEX = re.compile(r'http://|https://|ftp://|file://|file:\\') def is_url(filename): """Return True if...
# -*- coding: utf-8 -*- # Copyright (c) 2019 by University of Kassel, Tu Dortmund, RWTH Aachen University and Fraunhofer # Institute for Energy Economics and Energy System Technology (IEE) Kassel and individual # contributors (see AUTHORS file for details). All rights reserved. import pytest import os from copy impor...
""" MinHash Module """ from utils import * import math def minhash(rmat, num_shingles, num_signatures): """ Apply Min Hash per document Return: ----- pyspark.rdd [("business_id", {rating indexes}),..] -> i.e. [("ieuhg", {2, 3}] """ # Get hash functions hash_fns = ...
#python 3.5.2 print ( 'Linked List (Unorder List)' ) print('-'*20) class Node: def __init__(self, data=None): self.dataNode = data self.nextNode = None def getData(self): return self.dataNode def setData(self, data=None): self.dataNode = da...
# Author: Chris Moody <[email protected]> # License: MIT # This simple example loads the newsgroups data from sklearn # and train an LDA-like model on it import os.path import pickle import time from chainer import serializers from chainer import cuda import chainer.optimizers as O import chainer.link as L import...
from art import logo print(logo)
import unittest from os import path import os import shutil import sys import json from subprocess import Popen, PIPE, call import pprint from lxml import etree, objectify from lxml.cssselect import CSSSelector import pprint from pyquery import PyQuery as pq import_path = path.abspath(__file__) while path.split(impor...
#!/usr/bin/env python3 from kubernetes import client, config k8s_sizing = { 'Ti': 1024 ** 4, 'T': 1000 ** 4, 'Gi': 1024 ** 3, 'G': 1000 ** 3, 'Mi': 1024 ** 2, 'M': 1000 ** 0, 'Ki': 1024 ** 1, 'K': 1000 ** 1, } def mem_to_bytes(k8s_size): unit = ''.join(filter(lambda x: x.isalpha()...
from setuptools import setup, find_packages setup( name='telegram-media-bot', version="2.1", packages=find_packages(), scripts=['telegram-media-bot/telegram-media-bot.py'], install_requires=['tweepy>=3.5.0', 'praw<=3.6.0', 'requests>=2.12.3'], author='Murat Özel', description='Send picture...
"""This module implements patch-level prediction.""" import copy import os import pathlib import warnings from collections import OrderedDict from typing import Callable, Tuple, Union import numpy as np import torch import tqdm from tiatoolbox.models.architecture import get_pretrained_model from tiatoolbox.models.da...
from mp4box.box import MediaHeaderBox def parse_mdhd(reader, my_size): version = reader.read32() box = MediaHeaderBox(my_size, version, 0) if version == 0: box.creation_time = reader.read32() box.modification_time = reader.read32() box.timescale = reader.read32() ...
import os user = os.geteuid() print(user) if user != 0: print("You must be root user!") else: print("Hello root user! How are you?")
class Solution: def XXX(self, m: int, n: int) -> int: dp = [0 for _ in range(n)] for i in range(m): for j in range(n): if i == 0 or j == 0: dp[j] = 1 else: dp[j] = dp[j] + dp[j - 1] return dp[-1]
from pyDatalog import pyDatalog import action import match from reg import * from logicalview import * from flow_common import TABLE_LSP_EGRESS_FIRST, TABLE_LRP_INGRESS_IP_ROUTE, \ TABLE_EMBED2_METADATA, TABLE_DROP_PACKET, TABLE_OUTPUT_PKT pyDatalog.create_terms('Table, Priority, Match, Action')...
import itertools import pytest from streamlit_prophet.lib.dataprep.clean import _log_transform, _remove_rows, clean_future_df from tests.samples.df import df_test from tests.samples.dict import make_cleaning_test @pytest.mark.parametrize( "df, cleaning", list( itertools.product( [df_test[...
#DDoS.py #Imports: import os import sys import socket from platform import platform from os import listdir os.system('pip3 install scapy') from scapy.all import * import threading version = 'v Alpha 0.3' def get_ip_address(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) r...
#!/usr/bin/env python import os import random import json import tqdm import ltron.settings as settings from ltron.bricks.brick_scene import BrickScene breakout = { '4096 - Micro Wheels - AB Truck and Trailer.mpd' : [ '4096 - ab truck.ldr' ], '8123' : ['8123 - 1.ldr'], #'8123 - 2....
from os import listdir from os import path from flyingpigeon import sdm p = '/home/nils/birdhouse/var/lib/pywps/cache/malleefowl/esgf1.dkrz.de/thredds/fileServer/cordex/cordex/output/AFR-44/MPI-CSC/MPI-M-MPI-ESM-LR/historical/r1i1p1/MPI-CSC-REMO2009/v1/day/tas/v20160412/' ncs = [path.join(p, nc) for nc in listdir(...
import numpy as np # ai格式范例 # 需要决定吃碰杠/立直/和的时候被调用 def action(info, action_type): if (action_type in ['pon', 'chii', 'kan']): return False # 取消 if (action_type in ['ron', 'tsumo']): return True # 确认 return None # 什么都不做 # 需要出牌时被调用 def discard(info): return len(info.hand) - 1 # 打最后一张...
# Даны целые числа , указывающие момент времени. # Определить угол между положением часовой стрелки в начале суток и в указанный момент времени. (lambda hour, minute, second: print(abs(hour * 30 + minute * 0.5 + second * 0.5/60))) \ (float(input()), float(input()), float(input()))
# -*- coding: utf-8 -*- """ @file:maketrain.py @time:2019/5/6 16:42 @author:Tangj @software:Pycharm @Desc """ import pandas as pd import numpy as np import gc import time name = ['log_0_1999', 'log_2000_3999', 'log_4000_5999','log_6000_7999', 'log_8000_9999', 'log_10000_19999', 'log_20000_29999', 'log_30000_39...
import tweepy import json import os.path """ read in auth data """ auth_data = None with open('auth.json') as f: auth_data = json.load(f) f.close() handle = auth_data['twitter_handle'] cons_key = auth_data['consumer_key'] cons_sec = auth_data['consumer_secret'] acc_tok = auth_data['access_token'] acc_tok_...
from datetime import time # TODO make them constant # URL # TODO format BOATRACEJP_MAIN_URL = 'https://www.boatrace.jp/' BOATRACEJP_LOGIN_URL = f'{BOATRACEJP_MAIN_URL}owpc/pc/login?authAfterUrl=/' BOATRACEJP_LOGOUT_URL = f'{BOATRACEJP_MAIN_URL}owpc/logout' BOATRACEJP_BASE_URL = f"{BOATRACEJP_MAIN_URL}owpc/pc/race" ...
def binary_search(arr: list, left: int, right: int, key: int) -> int: """Iterative Binary Search""" if left > right: return -1 while left <= right: mid = left + (right - left) // 2 if arr[mid] == key: return mid elif arr[mid] < key: left = mid + 1 ...
#Steer Left - Left LS #Steer Right - Right LS from vjoy import vJoy, ultimate_release import time vj = vJoy() XYRANGE = 16393 ZRANGE = 32786 vj.open() # print('gass') # time.sleep(2) # joystickPosition = vj.generateJoystickPosition(wAxisZ = ZRANGE) # pilna gaaze # vj.update(joystickPosition) # time.sleep(2) # jo...
"""Extends crowddynamics commandline client with gui related commands""" import logging import sys import click from PyQt4 import QtGui, QtCore from crowddynamics.logging import setup_logging from qtgui.main import MainWindow def run_gui(simulation_cfg=None): r"""Launches the graphical user interface for visual...
import bokeh.sampledata bokeh.sampledata.download()
import numpy as np def vecNum(vec): return int("".join(str(int(n)) for n in vec), base=2) def printBinary(mat, width): for vec in mat: print("0b{:0{}b},".format(vecNum(vec), width)) def genToParityCheck(genParity): xpose = genParity.transpose() return np.hstack((xpose, np.eye(xpose.shape[0]))...
# -*- coding: utf-8 -*- from django.db import models from datetime import datetime class Feedback(models.Model): name = models.CharField('Name', max_length=50, default="Anonym", blank=True) email = models.EmailField('E-Mail', max_length=254, blank=True) note = models.TextField('Anmerkung', max_length=102...
""" **Description** A Finite Impulse Response ( FIR ) filter realizes a discrete difference equation as a function of a forward coefficient array and a state array of a specified order, consuming an incident signal and producing a reference signal. .. math:: y_{n} = ...
''' Antenna array gain =========================== ''' import time import numpy as np import pyant xv, yv = np.meshgrid(np.linspace(-50,50, num=22), np.linspace(-50,50, num=22)) antennas = np.zeros((22**2, 3)) antennas[:,0] = xv.flatten() antennas[:,1] = yv.flatten() ant = pyant.Array( azimuth=0, elevation=9...
""" App Messages Enum Module for Flambda APP Version: 1.0.0 """ from enum import IntEnum class MessagesEnum(IntEnum): def __new__(cls, value, label, message=''): obj = int.__new__(cls, value) obj._value_ = value obj.code = value obj.label = label obj.message = message ...
import frappe def get_context(context): context.test="Hello"
from __future__ import print_function import pandas import matplotlib; matplotlib.use('Agg') import sys, os, copy, math, numpy as np, matplotlib.pyplot as plt from tabulate import tabulate from munkres import Munkres from collections import defaultdict try: from ordereddict import OrderedDict # can be installed u...
#!/usr/bin/python3 # Credit https://github.com/oskarhane/dockerpress Written by Oskar Hane <[email protected]> # Credit http://geraldkaszuba.com/quickly-ssh-into-a-docker-container/ import subprocess import sys import re import shutil import json from optparse import OptionParser def create_nginx_config(container_i...
from cardboard import types from cardboard.ability import ( AbilityNotImplemented, spell, activated, triggered, static ) from cardboard.cards import card, common, keywords, match @card("Beast Hunt") def beast_hunt(card, abilities): def beast_hunt(): return AbilityNotImplemented return beast_hunt...
from MultiSC.MultiServer.quick_setup.manager import ( ProtocolsManager, MonitorManager, Runner, ) # Simple protocol that run python command @ProtocolsManager.add("run_command", "command") def func(query): if query["password"] != "runpass12345665": return "password wrong!" try: retur...
# # 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 agreed to in writing, software # ...
import os import csv from datetime import datetime from collections import namedtuple from codonutils import translate_codon ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) with open(os.path.join(ROOT, 'internalFiles', 'consensus.csv')) as fp: CONSENSUS = {c['Gene']: c for c in csv.DictReader(...
# -*- coding: utf-8 -*- from wikiedits.diff_finder import DiffFinder import nltk.data import Levenshtein import math import logging log = logging.getLogger(__name__) class EditFilter(object): def __init__(self, lang='english', min_words=3, max_words=120, ...
import torch from torch import nn class add_coord(nn.Module): def __init__(self): super(add_coord, self).__init__() def forward(self, x): bs, ch, h, w = x.size() h_coord = torch.range(start=0, end=h - 1).unsqueeze(0).unsqueeze(0).unsqueeze(-1).repeat([bs, 1, 1, w]) / ( ...
import win32gui from PIL import ImageGrab import math import sys def getTopWindowList(): root = win32gui.GetDesktopWindow() children = [] def callback(hwnd, extra): try: if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd): children.append( ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import sys, time, re from sympy.solvers import solve from sympy import Symbol def resolve(equation): '''Resolve an equation with 1 unknown var''' #Find the symbol r = re.compile(r"([A-Za-z]{0,})") varList = r.findall(equation) symbol = '' for a in rang...
import IPython import pickle import numpy as np import matplotlib.pyplot as plt import re import stat import os import sys import random from functools import reduce from pathlib import Path import nwalign as nw from interruptingcow import timeout from .classes import * from .decorators import * from .utils import *...
format_on_save_scenarios = [ ({}, '', False), ({'format_on_save': True}, '', True), ({'format_on_save': False}, '', False), ({'format_on_save': '.test$'}, 'file.txt', False), ({'format_on_save': '.test$'}, 'file.test', True) ]
#!/usr/bin/env python # coding: utf-8 __author__ = 'Lrakotoson' __copyright__ = 'Copyright 2020, Jobtimize' __license__ = 'MIT' __version__ = '0.1.5' __maintainer__ = 'Loïc Rakotoson' __email__ = '[email protected]' __status__ = 'planning' __all__ = ['IndeedScrap'] "" from .rotateproxies import RotateProxies ...
"""Entropy functions""" import numpy as np from numba import jit from math import factorial, log from sklearn.neighbors import KDTree from scipy.signal import periodogram, welch from .utils import _embed all = ['perm_entropy', 'spectral_entropy', 'svd_entropy', 'app_entropy', 'sample_entropy', 'lziv_complexity...
#!/usr/bin/env python import os import logging import pymongo from datetime import datetime, timedelta from pymongo import MongoClient from recommender.infrastructure.lastfm import LastFMListeningRepository from recommender.infrastructure.repository.mongodb import ( MongoDBTracksRepository ) logging.basicConfig( ...
import sys, os, time, getopt, subprocess, tempfile from parsec_platform import * abspath = lambda d: os.path.abspath(os.path.join(d)) HOME = abspath(os.path.dirname(__file__)) __allbenchmarks = None def allbenchmarks(): global __allbenchmarks if not __allbenchmarks: try: benchmarks = subprocess.Popen...
#Copyright (C) 2016 Zumium [email protected] # # #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 Lice...
# A part of pdfrw (https://github.com/pmaupin/pdfrw) # Copyright (C) 2006-2015 Patrick Maupin, Austin, Texas # MIT license -- See LICENSE.txt for details ''' Currently, this sad little file only knows how to compress using the flate (zlib) algorithm. Maybe more later, but it's not a priority for me... ''' from .obje...
from app.validators.blocks.unrelated_block_validator import UnrelatedBlockValidator from app.validators.questionnaire_schema import QuestionnaireSchema from tests.test_questionnaire_validator import _open_and_load_schema_file def test_invalid_actions(): filename = "schemas/invalid/test_invalid_relationships_unrel...
from xicam.plugins.operationplugin import operation, output_names, display_name, describe_input, describe_output, \ categories, plot_hint import numpy as np import pyFAI import hipies @operation @display_name('Remesh') @describe_input('data', 'Detector image') @describe_input('geometry', 'pyFAI Geometry') @descri...
from JumpScale import j class LogRotate(object): def start(self): j.system.process.execute('logrotate /etc/logrotate.d/*') def stop(self): pass def restart(self): pass def status(self): pass
""" This module is a wrapper around parsets used in YandaSoft. The code takes template parset(s) and creates custom parsets for pipelines such as the gridded DINGO pipeline. Currently not everything is supported and the wrapper is not complete, i.e. the user can break the wrapper if not careful! """ __all__ = ['list_s...
#!/usr/bin/env python #============================================================================== import traceback from olympus import Logger #============================================================================== try: import sqlalchemy except ModuleNotFoundError: error = traceback.format_exc() f...
""" The experiment combines the Fourier features and the features extraced from HMM generative model. After this augmented dataset is created we train and evaluate Random Forest on it. """ import numpy as np from DataNexus.datahandler import DataHandler from DataNexus.fourier import Fourier from sklearn.ensemble i...
import bpy def write(vert, frag): wrd = bpy.data.worlds['Arm'] is_shadows = '_ShadowMap' in wrd.world_defs is_shadows_atlas = '_ShadowMapAtlas' in wrd.world_defs is_single_atlas = '_SingleAtlas' in wrd.world_defs frag.add_include_front('std/clusters.glsl') frag.add_uniform('vec2 camer...
""" Utility functions for use in neural network construction and processing """ from keras.callbacks import EarlyStopping from keras.models import Sequential from keras.layers import Dense from keras.callbacks import Callback from keras import initializers import keras.backend as K from keras.constraints import maxnor...
# Copyright 2020 Siu-Kei Muk (David). 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...
import os import numpy as np import matplotlib.pyplot as plt data_path = './data/bikeshare/' data_filenames = ['2017-q1_trip_history_data.csv', '2017-q2_trip_history_data.csv', '2017-q3_trip_history_data.csv', '2017-q4_trip_history_data.csv'] # 结果保存路径 output_path = './output' if not os.path.exists(o...
""" Command-module for Microsoft Excel You also can find some good vocola commands for Excel on Mark Lillibridge's Github: https://github.com/mdbridge/bit-bucket/tree/master/voice/my_commands/commands Alex Boche 2019 """ # this function takes a dictionary and returns a dictionary whose keys are sequences of keys of th...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 15 14:33:56 2019 @author: khalilsleimi Notation: ** A raw assembly file is a (*.asm) with comments(single line and multiline) and empty lines, and spaces in actual commands (we suppose a command per line at most) ** A Clean As...
""" Audio file handler """ import scipy.io.wavfile as wavfile import numpy as np class Media: """ Media: I/O functionality to read/write audio files """ def __init__(self, file_path, dtype=None): self.file_path = file_path self._dtype = dtype @property def sample_rate(self):...
""" Change this to set the game speed to see what's going on. """ GAME_SPEED = 1 # Usually there are a bunch of constants in this file... but... MAX_CAR_VEL = 2300
# Calculate a Suite of Bitcoin Specific Metrics #Data Science import pandas as pd import numpy as np import math import datetime as date today = date.datetime.now().strftime('%Y-%m-%d') import quandl from checkonchain.general.coinmetrics_api import * from checkonchain.general.regression_analysis import * from checkon...
class Stacks: Team = "" Value = "" class TeamStack(Stacks): TeamValue = Stacks() Lineups = 0
#!/usr/bin/env python """A simple script to display information about faces from the facetracer dataset. This is useful for quickly seeing all the relevant data for a given face id. It also shows how easy it is to parse the data for your own applications. Note that fiducial point locations are RELATIVE TO THE CROP REC...
word_list_count = [0, 0, 0] word_search = [] text = '' for _ in range(3): print('Введите', _ + 1, 'слово: ', end='') word = input() word_search.append(word) while text != 'end': text = input('Слово из текста: ') for i in range(3): if word_search[i] == text: word_list_count[i] +...
from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.generic.base import TemplateView class HomeView(TemplateView): template_name = 'routes/dashboard.html' @method_decorator(login_required) def...
import requests from celery import shared_task import logging logger = logging.getLogger('django') @shared_task() def test(): print('Hello World') return True
"""A Team Cowboy API client.""" import hashlib import httplib import json import random import sys import time import urllib class TeamCowboyException(Exception): """A Team Cowboy error.""" pass class TeamCowboy(object): """A Team Cowboy API client.""" def __init__(self, public_key, private_key): """C...
import socket from time import sleep import binascii port = 52381 buffer_size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(('', port)) acknowledge_message = bytearray.fromhex('90 4Y FF'.replace('Y', '1')) # 1 = socket number completion_message = bytearray.fromhex('90 5Y FF'.replace('Y', '1')) ...
from enum import Enum class StatBlockType(Enum): ENCRYPTED = "encrypted" COMPRESSED = "compressed" def __str__(self) -> str: return str(self.value)
#!/usr/bin/env python __author__ = 'yuy001' def test1(): print("Hello World") print( 3*3 ) print( 5**2 ) if __name__ == "__main__": test1()
import asyncio from datetime import datetime from typing import Iterable import discord from dateutil.relativedelta import relativedelta from discord.ext import commands, tasks from sqlalchemy import select from common.db import session from common.logging import logger from datamodels.scheduling import ScheduledItem...
from classes.LinkedList import * #The digits are stored in reverse order def addLists_rev(L1, L2): p1 = L1.head p2 = L2.head carry = 0 linkedlist_sum = LinkedList() while (p1 != None) or (p2 != None) or (carry != 0): dig_sum = carry if p1 != None: dig_sum += p1.value ...
""" A module including custom decorators. """ from . import __version__ def add_version(f): """ Add the version of the tool to the help heading. :param f: function to decorate :return: decorated function """ doc = f.__doc__ f.__doc__ = "Version: " + __version__ + "\n\n" + doc return...
# # # Protool - Python class for manipulating protein structuress # Copyright (C) 2010 Jens Erik Nielsen # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (...