content
stringlengths
0
894k
type
stringclasses
2 values
#!/usr/bin/env python import os import sys path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) sys.path.insert(0, path) import django def manage_16ormore(): os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line execut...
python
#Adding python objects to database import sqlite3 from employee import Employee #we are calling in the Employee class from the program which we made earlier, they must be in the same directory conn=sqlite3.connect('sql.db') c = conn.cursor() #c.execute("""CREATE TABLE employees ( # first text, # ...
python
from XTax import Tax import io import unittest import unittest.mock class Test_XTax(unittest.TestCase): def test_TaxInitYear(self): MyTax = Tax(2019,autoload=False) self.assertEqual(MyTax.Year, 2019) @unittest.mock.patch('sys.stdout', new_callable=io.StringIO) def test_TaxInitLog(self,mock...
python
import sys try: import threading except ImportError: import dummy_threading as threading py32 = sys.version_info >= (3, 2) py3k = sys.version_info >= (3, 0) py2k = sys.version_info <= (3, 0) if py3k: string_types = str, import itertools itertools_filterfalse = itertools.filterfalse if py3...
python
import sys import Heuristic import RandomProblem import SolveProblem def main(): # auto random file if no input if len(sys.argv) != 4: RandomProblem.createRandomProblem('rand_in.txt', 8, 16) pf = SolveProblem.ARA('rand_in.txt', 'rand_log.txt', 3, Heur...
python
"""Playbook Create""" # standard library import base64 import json import logging from typing import Any, Dict, Iterable, List, Optional, Union # third-party from pydantic import BaseModel # first-party from tcex.key_value_store import KeyValueApi, KeyValueRedis from tcex.utils.utils import Utils # get tcex logger l...
python
from moviepy.editor import * clip = (VideoFileClip("../output_videos/project_video.mp4").subclip(10, 40).resize(0.3)) clip.write_gif("../output_videos/project_video.gif")
python
# -*- coding: utf-8 -*- """ admin security exceptions module. """ from pyrin.core.exceptions import CoreException, CoreBusinessException from pyrin.security.exceptions import AuthorizationFailedError class AdminSecurityException(CoreException): """ admin security exception. """ pass class AdminSecu...
python
# -*- coding: utf-8 -*- # # Copyright (c), 2018-2019, SISSA (International School for Advanced Studies). # All rights reserved. # This file is distributed under the terms of the MIT License. # See the file 'LICENSE' in the root directory of the present # distribution, or http://opensource.org/licenses/MIT. # # @author ...
python
#! /usr/bin/env python3 # Conditions: # * A child is playing with a ball on the nth floor of a tall building # * The height of this floor, h, is known # * He drops the ball out of the window. The ball bounces (for example), # to two-thirds of its height (a bounce of 0.66). # * His mother looks out of a window 1.5 me...
python
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: lbrynet/schema/proto/source.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import ...
python
# -*- coding: utf-8 -*- """ Created on Mon Aug 9 23:58:12 2021 @author: AKayal """ from collections import namedtuple from typing import List, NamedTuple import datetime from datetime import date class personal_details(NamedTuple): """ Using the typing module, we can be even more explicit about our data stru...
python
from whirlwind.store import create_task from delfick_project.norms import sb, dictobj, Meta from tornado.web import RequestHandler, HTTPError from tornado import websocket import binascii import logging import asyncio import json import uuid log = logging.getLogger("whirlwind.request_handlers.base") class Finished(...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 22 14:33:38 2017 @author: paul """ from weatherTLKT import Weather typ='ens' for ss in range(1,9): if typ=='solo': mydate='20171127' website='http://nomads.ncep.noaa.gov:9090/dods' model='gfs' resolution='0p25' url=website+'...
python
from django.views.generic import TemplateView, ListView, DetailView from . import models class DashboardView(TemplateView): template_name = "organizations/dashboard.html" class OrganizationDetailView(DetailView): template_name = "organizations/organization_details.html" model = models.Organization clas...
python
import csv import xlsxwriter import datetime # Sequence Analysis Data Object # Holds all items needed for analysis class SeqData: its_dict = None seq_config = None num_threads = None output_format = None def __init__(self, its_dict, seq_config, num_threads, output_format): self.num_threads...
python
import pandas as pd from strategy.astrategy import AStrategy from processor.processor import Processor as p from datetime import timedelta import pytz from tqdm import tqdm from time import sleep pd.options.mode.chained_assignment = None class ProgressReport(AStrategy): def __init__(self,start_date,end_date,modelin...
python
from functools import reduce from operator import mul import numpy as onp from numpy.testing import assert_allclose import pytest import scipy.stats as osp_stats import jax from jax import grad, lax, random import jax.numpy as np from jax.scipy.special import logit import numpyro.contrib.distributions as dist from n...
python
import os import os.path as osp import sys import numpy.random import torch.nn from deltalogger.deltalogger import Deltalogger from reinforce_modules.utils import ConfusionGame, get_defense_visual_fool_model from utils.train_utils import StateCLEVR, ImageCLEVR_HDF5 sys.path.insert(0, osp.abspath('.')) import random ...
python
from django.conf import settings from django.urls import path, include from rest_framework.routers import DefaultRouter from api.search.product import views # Create a router and register our viewsets with it. router = DefaultRouter() router.register(r"search", views.ProductDocumentView, basename="product_search") ...
python
import copy import numpy as np # configure matplotlib for use without xserver import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def get_neuron_features(features, neurons): """ Gets neuron activations from activations specified by `neurons`. Args: features: numpy arraylike of s...
python
''' Multiples of 3 and 5 ''' sum = 0 for i in range(1000): if i%3 == 0 or i%5 == 0: sum = sum + i print sum
python
#!/usr/bin/env python import sys, gym, time # # Test yourself as a learning agent! Pass environment name as a command-line argument, for example: # # python keyboard_agent.py SpaceInvadersNoFrameskip-v4 # import gym_game import pygame if len(sys.argv) < 3: print('Usage: python keyboard_agent.py ENV_NAME CONFIG_FILE...
python
import enum import re import string from typing import Text, List from xml.sax import saxutils import emoji from six import string_types from collections.abc import Iterable from tklearn.preprocessing import TextPreprocessor __all__ = [ 'Normalize', 'TweetPreprocessor', ] @enum.unique class Normalize(enum.E...
python
from flask import Flask, request, jsonify, render_template from flask_cors import CORS import math import pickle app = Flask(__name__) CORS(app) uniq_fire_date = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] uniq_county = ['No Data', 'Skamania', 'Cowlitz', 'Thurston', 'Okanoga...
python
def mallow(y, y_pred, y_sub, k, p): """ Return an mallows Cp score for a model. Input: y: array-like of shape = (n_samples) including values of observed y y_pred: vector including values of predicted y k: int number of predictive variable(s) used in the model p: int number of predictive var...
python
import functools,fractions n=int(input()) a=list(map(int,input().split())) print(functools.reduce(fractions.gcd,a))
python
from pymining import itemmining from pymining import seqmining import sys if(len(sys.argv) != 3): print("Please provide the data file and the minimum support as input, e.g., python freq_seq.py ./output.txt 40") sys.exit(-1) f = open(sys.argv[1], 'r') lines = f.read().splitlines() seqs = [] for s in lines: seq = s....
python
""" 属性的使用 - 访问器/修改器/删除器 - 使用__slots__对属性加以限制 Version: 0.1 Author: BDFD Date: 2018-03-12 """ class Car(object): __slots__ = ('_brand', '_max_speed') def __init__(self, brand, max_speed): self._brand = brand self._max_speed = max_speed @property def brand(self): return self._...
python
# Lint as: python3 # Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agr...
python
# Generated by Django 4.0.2 on 2022-02-19 14:09 from django.conf import settings import django.core.validators from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AU...
python
import cv2 import numpy as np import torch from ..builder import MOTION @MOTION.register_module() class CameraMotionCompensation(object): """Camera motion compensation. Args: warp_mode (str): Warp mode in opencv. num_iters (int): Number of the iterations. stop_eps (float): Terminate ...
python
""" Access to data resources installed with this package """ from servicelib.resources import ResourcesFacade resources = ResourcesFacade( package_name=__name__, distribution_name="simcore-service-storage", config_folder="", )
python
#!/usr/bin/env python import time from slackclient import SlackClient import os, re base_dir = os.path.dirname(os.path.realpath(__file__)) player = 'afplay' text2voice = 'espeak' sounds_dir = 'sounds' filetype = 'mp3' debug = True bots_channel = 'build' play_fixed = re.compile("FIXED") play_cancelled = re.compile("C...
python
""" Produces Fig. A1 of Johnson & Weinberg (2020), a single axis plot showing the abundance data of several dwarf galaxies taken from Kirby et al. (2010) in comparison to a smooth and single-burst model simulated in VICE. """ import visuals # visuals.py -> matplotlib subroutines in this directory import matplotl...
python
# Copyright © 2021 Lynx-Userbot (LLC Company (WARNING)) # GPL-3.0 License From Github (General Public License) # Ported From Cat Userbot For Lynx-Userbot By Alvin/LiuAlvinas. # Based On Plugins # Credits @Cat-Userbot by Alvin from Lord-Userbot from userbot.events import register from userbot import CMD_HELP, bot from...
python
"""https://de.dariah.eu/tatom/topic_model_python.html""" import os import numpy as np # a conventional alias import sklearn.feature_extraction.text as text from sklearn import decomposition class TM_NMF: def __init__(self, all_documents, num_topics, num_top_words, min_df, max_df, isblock): self.all_docum...
python
import RoothPath import os import re import yaml import json if __name__ == '__main__': yaml_dic = {} with open(os.path.join(os.path.join(RoothPath.get_root(), 'Benchmarks'), 'den312d.map')) as ascii_map: ascii_map.readline() h = int(re.findall(r'\d+', ascii_map.readline())[0]) w = int(...
python
# Copyright 2015, Ansible, Inc. # Luke Sneeringer <lsneeringer@ansible.com> # # 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 requi...
python
# -*- coding: utf-8 -*- import json from typing import Iterable from pyrus_nn.rust.pyrus_nn import PyrusSequential from pyrus_nn import layers class Sequential: # This is the actual Rust implementation with Python interface _model: PyrusSequential def __init__(self, lr: float, n_epochs: int, batch_siz...
python
from django import template from cart.utils import get_or_set_order_session register = template.Library() @register.filter def cart_item_count(request): order = get_or_set_order_session(request) count = order.items.count() return count
python
from visions.utils.monkeypatches import imghdr_patch, pathlib_patch __all__ = [ "imghdr_patch", "pathlib_patch", ]
python
from pprint import pprint from ayesaac.services.common import QueueManager from ayesaac.utils.logger import get_logger logger = get_logger(__file__) class Interpreter(object): """ The Interpreter class purpose is a simple comparison with what the vision part find and what the user asked for. (Whic...
python
from core.models import MedicalCare, Pets, Tutor, Vet from django.contrib import admin admin.site.register(Vet) class MedicalCareAdmin(admin.ModelAdmin): list_display = ('id', 'date', 'time', 'pet_name', 'procedure', 'report') admin.site.register(MedicalCare, MedicalCareAdmin) class PetsAdmin(admin.ModelAdm...
python
#Test Array Implementation import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from pyds import array #test array print("01 : ======= Creating Array of size 5 =======") arr = array(5) print("02: ======= Traversing Array =======") arr.print() print("03: ======= In...
python
import json import time import logging import requests import functools class WechatAppPush: """ WechatAppPush decorator Push the msg of the decorated function Example 1: @WechatAppPush(corpid, corpsecret, agentid) def func(): return 'xxx' Example 2: def f...
python
N = int(input()) print(f'{((N + 1) // 2 / N):.10f}')
python
try: from datetime import datetime import pandas as pd import numpy as np from pathlib import Path from sklearn.experimental import enable_iterative_imputer from sklearn.impute import IterativeImputer from sklearn.linear_model import BayesianRidge from sklearn import preprocessing excep...
python
from .util import * from .db import Database from .optimizer import * from .ops import Print, Yield from .parseops import * from .udfs import * from .parse_sql import parse from .tuples import * from .tables import * from .schema import Schema from .exprs import Attr from .compile import * from .context import *
python
from __future__ import print_function import getopt def usage(): print("""Usage: check_asdis -i <pcap_file> [-o <wrong_packets.pcap>] -v increase verbosity -d hexdiff packets that differ -z compress output pcap -a open pcap file in append mode""", file=sys.stderr) def main(argv): PCA...
python
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. # # 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...
python
from mr_scraper.api import dispatch, ScraperMessage def levels_fyi(): """Scraper using Puppeter""" message = ScraperMessage( scraper="example.scrapers.levels_fyi", type='companies', payload={'url': '/company/'} ) return dispatch(message)
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from setuptools import setup, find_packages version = '0.12.0' setup( name='SerpScrap', version=version, description=''' SEO python scraper to extract data from major searchengine result pages. Extract data like url, title, snippet, richsnippet and t...
python
import json import subprocess from oslo_log import log as logging from magnum.common import exception LOG = logging.getLogger(__name__) class KubeCtl(object): def __init__(self, bin='kubectl', global_flags=''): super(KubeCtl, self).__init__() self.kubectl = '{} {}'.format(bin, global_flags) ...
python
import json import cfnresponse def lambda_handler(event, context): print(json.dumps(event)) response_data = {} response_data['Data'] = None if event['RequestType'] != 'Create': cfnresponse.send(event, context, cfnresponse.SUCCESS, response_data, "CustomResourcePhysic...
python
from typing import NamedTuple from thundersnow.precondition import check_argument from thundersnow.predicate import is_not_blank class Version(NamedTuple): """Sematnic Version object""" major: str minort: str patch: str def __str__(self): return '.'.join(self) def from_string(s): ""...
python
import sys from loguru import logger logger.remove() logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True) def div(x, y): x / y def cause(x, y): try: div(x, y) except Exception: raise ValueError("Division error") def context(x, y): try: cause(x,...
python
import numpy as np print("Did you know 2 + 2 = {}".format(2+2)) print("Of course I knew that, I have 4 fingers") print("Well, I knew you had 4 fingers. I didn't know that you knew how to count!")
python