content stringlengths 5 1.05M |
|---|
# Copyright 2021 The Duet Authors
#
# 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 agreed to in wri... |
"""
Nisarg Shah
1001553132
"""
import sys
import math
import numpy as np
from statistics import stdev as stdev
def gaussian(x, mean=0.0, sigma=1.0):
temp = float((x-mean)/sigma)
e_factor = np.exp(-(np.power(temp,2) / 2))
deno = sigma*(np.sqrt(2*np.pi))
return e_factor / deno
def naive_bayes(train_... |
# Helper functions used by other files
from io import BytesIO
import aiohttp
import re
import os
def convert_to_url(url):
""" Makes a search string url-friendly """
# Use regex to remove anything that isn't a number or letter
url = re.sub(r"[^\w\s]", '', url)
# Substitute spaces with a '+' symbol
... |
"""."""
from flask import Blueprint, current_app, request, jsonify
from werkzeug.exceptions import BadRequest, Unauthorized
import jwt
from arxiv import status
import arxiv.users.domain
from arxiv.base import logging
from .services import sessions
logger = logging.getLogger(__name__)
blueprint = Blueprint('authentic... |
# red-r linux setup. Several things we need to do here.
# imports
import sys, os, subprocess
# install the required files
os.system("apt-get install python-qt4")
os.system("apt-get install python-docutils")
os.system("apt-get install python-numpy")
os.system("apt-get install python-qwt5-qt4")
os.system('apt-get ins... |
"""Tests for ops.
"""
import unittest
import numpy as np
import tensorflow as tf
from tf_utils import utils
from tf_utils import ops
class TestOps(unittest.TestCase):
def test_concat_with_shape(self):
data = np.array([[0.5, 0.5, 0.0, 0.0, 0.6, 0.0],
[0.0, 0.6, 0.0, 0.0, 0.0, 0.... |
import tensorflow as tf
hparams = tf.contrib.training.HParams(
# Audio:
num_mels=80,
n_fft=1024,
sample_rate=22050,
win_length=1024,
hop_length=256,
preemphasis=0.97,
min_level_db=-100,
ref_level_db=20,
# train
lr=6e-4, #1e-3
train_steps=1000000,
epochs=100,
sa... |
import requests
import sys
import json
import os
import time
import logging
import tabulate
import yaml
import pandas as pd
from pandas import ExcelWriter
from logging.handlers import TimedRotatingFileHandler
requests.packages.urllib3.disable_warnings()
from requests.packages.urllib3.exceptions import InsecureRequest... |
#!/usr/bin/env python3
"""Module containing the MakeNdx class and the command line interface."""
import os
import argparse
from pathlib import Path
from biobb_common.generic.biobb_object import BiobbObject
from biobb_common.configuration import settings
from biobb_common.tools import file_utils as fu
from biobb_common... |
"""Replacement for Django's migrate command."""
from __future__ import unicode_literals
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import CommandError
from django.utils.translation import ugettext as _
try:
from django.core.management.command... |
#!/usr/bin/env python3
import nelly.main
if '__main__' == __name__:
nelly.main.main()
|
from records_mover.records.records_format import DelimitedRecordsFormat
import unittest
import json
class TestDelimitedRecordsFormat(unittest.TestCase):
def test_dumb(self):
records_format = DelimitedRecordsFormat(variant='dumb')
# Should match up with
# https://github.com/bluelabsio/recor... |
# coding=utf-8
# Copyright 2021 The Reach ML Authors.
#
# 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 ... |
import sys
sys.path.append('..')
from utils import iplib
if __name__ == "__main__":
if len(sys.argv) < 2:
print(f"Usage: {sys.argv[0]} <IP address>")
exit(-1)
try:
ip = iplib.IPAddress(sys.argv[1])
except:
print(f"{sys.argv[1]} is not a valid IPv4 address")
exit(-... |
from common_fixtures import * # NOQA
from test_services \
import service_with_healthcheck_enabled
from test_machine \
import action_on_digital_ocean_machine, get_dropletid_for_ha_hosts
ha_droplets = []
if_test_host_down = pytest.mark.skipif(
not os.environ.get('DIGITALOCEAN_KEY') or
not os.environ.get... |
# Generated by Django 3.0.2 on 2020-01-11 13:34
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Accruals",
fields=[
... |
import sys
from PyQt5 import QtWidgets
from ui import UI
app = QtWidgets.QApplication(sys.argv)
ui = UI(app)
sys.exit(app.exec_()) |
from alfred.utils.config import *
from alfred.utils.directory_tree import *
from alfred.utils.misc import create_logger, select_storage_dirs
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--from_file', type=str, default=None,
help="Path containing all the stora... |
#!/usr/bin/env python3
# wb2sc_file_converter.py
#
# Copyright 2019 E. Decker
#
# 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 req... |
def countSegments(s):
s = s.lstrip()
s = s.rstrip()
count = 1
for i in range (len(s)):
if s[i]==" " and s[i+1]!=" ":
count+=1
return count
s = ", , , , a, eaefa"
print(countSegments(s)) |
import time
class SessionHelper:
def __init__(self, app):
self.app = app
def Marker_login(self, username, password):
wd = self.app.wd
self.app.open_marker_home_page()
wd.find_element_by_css_selector("button.mainbtn").click()
wd.find_element_by_name("username").click()... |
# Copyright (c) 2020-2021, NVIDIA CORPORATION.
#
# 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 agr... |
import numpy as np
import pytest
from highway_env.road.lane import StraightLane, CircularLane, PolyLane
from highway_env.road.road import Road, RoadNetwork
from highway_env.vehicle.controller import ControlledVehicle
@pytest.fixture
def net() -> RoadNetwork:
# Diamond
net = RoadNetwork()
net.add_lane(0, ... |
from OpenGLCffi.GL import params
@params(api='gl', prms=['pname', 'param'])
def glConservativeRasterParameteriNV(pname, param):
pass
|
num = int(input('Digite um número inteiro: '))
choose = int(input('Qual a base de conversão?'
'\n[1] para binário'
'\n[2] para octal'
'\n[3] para hexadecimal '
'\nDigite sua opção: '))
if choose == 1:
print(f'\033[37;1m{num}\033[m convertid... |
import spacy
import pandas as pd
import wikipediaapi
import csv
from IPython.display import display
from tabulate import tabulate
wiki_wiki = wikipediaapi.Wikipedia('en')
while True:
try:
chemical = input("Write the name of entity: ")
page_py = wiki_wiki.page(chemical)
sumary = page_py.summ... |
#!/usr/bin/python
#https://practice.geeksforgeeks.org/problems/common-subsequence/0
def sol(a, b):
"""
Follows the standard DP approach of finding common subsequence.
The common length can be >=1 so if we find a common character in both
the strings, it does the job
"""
m = len(a)
n = len(b)... |
from charm import SplunkCharm
from ops.testing import Harness
import pytest
@pytest.fixture
def harness():
_harness = Harness(SplunkCharm)
_harness.set_model_name("testing")
_harness.begin()
yield _harness
_harness.cleanup()
|
from django.contrib import admin
from paper.models import PaperInfo
@admin.register(PaperInfo)
class PaperInfoAdmin(admin.ModelAdmin):
# 表头显示
list_display = (
'paper_id', 'title', 'degree', 'subject', 'score', 'owner_id', 'creator_id', 'is_public',
'create_time', 'update_time'
)
# 支持... |
mixed_list = ['cat', 5, 'flower', 10]
string_list = []
num_list = []
for item in mixed_list:
if type(item)== str:
string_list.append(item)
else:
num_list.append(item)
print(string_list)
print(num_list)
|
from credentials import INSTANCE_CONNECTION_NAME
def main():
f = open("Makefile", 'a')
sql = '"{}"=tcp:{}'.format(INSTANCE_CONNECTION_NAME, 3306)
f.write(sql)
f.close()
print("Makefile updated!")
if __name__ == "__main__":
main()
|
"""
This scripts allows the user to create train, validation, test datasets by:
* Dropping unnecessary columns
* Removing Duplicates
* Creating time window pairs
* Splitting with Session UID to prevent any data leakages
This file can be imported as a module to use following functions:
* prepare_da... |
n = int(input())
for i in range(0, n):
if i == n - 1:
print("Ho!")
else:
print("Ho ", end="")
|
from .read_tles import (
read_tles,
satellite_ephem_to_str
)
from .generate_tles_from_scratch import (
generate_tles_from_scratch_manual,
generate_tles_from_scratch_with_sgp
)
|
#!/usr/bin/env python3
# Copyright (c) 2020 The Bitcoin Unlimited developers
"""
Tests specific for the electrum call 'blockchain.scripthash.get_history'
"""
import asyncio
from test_framework.util import assert_equal
from test_framework.electrumutil import (
ElectrumTestFramework,
ElectrumConnection,
... |
# -*- coding: utf-8 -*-
# Copyright 2018 the HERA Project
# Licensed under the MIT License
'''Tests for abscal.py'''
import nose.tools as nt
import os
import shutil
import json
import numpy as np
import aipy
import optparse
import sys
from pyuvdata import UVCal, UVData
from pyuvdata import utils as uvutils
import her... |
from capstone.x86_const import *
JMPS = [
X86_INS_JA,
X86_INS_JAE,
X86_INS_JB,
X86_INS_JBE,
X86_INS_JCXZ,
X86_INS_JE,
X86_INS_JECXZ,
X86_INS_JG,
X86_INS_JGE,
X86_INS_JL,
X86_INS_JLE,
X86_INS_JMP,
X86_INS_JNE,
X86_INS_JNO,
X86_INS_JNP,
X86_INS_JNS,
X86... |
#
# Torque log parser and UR generator
#
# Module for the SGAS Batch system Reporting Tool (BaRT).
#
# Author: Henrik Thostrup Jensen <[email protected]>
# Author: Andreas Engelbredt Dalsgaard <[email protected]>
# Author: Magnus Jonsson <[email protected]>
# Copyright: Nordic Data Grid Facility (2009, 2010)
im... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
import sys
from yachalk import chalk
class Output:
def __init__(self, lnd):
self.lnd = lnd
@staticmethod
def print_line(message, end='\n'):
sys.stdout.write(f"{message}{end}")
@staticmethod
def print_without_linebreak(message):
sys.stdout.write(message)
def print_ro... |
#!/usr/bin/python3
# Module for parsing arguments
import argparse
parser = argparse.ArgumentParser()
# Add an argument and save it in a variable named "src_dir"
# Also add description for -h (help) option
parser.add_argument("src_dir", help = "Directory to backup")
# Add an argument and save it in a vari... |
# -*- coding: utf-8 -*-
"""
@Project: pytorch-train
@File : utils
@Author : TonyMao@AILab
@Date : 2019/11/12
@Desc : None
"""
import torch
import torchvision.transforms as transforms
from PIL import Image
def get_transform(opt):
transform_list = []
if opt.resize_or_crop == 'resize_and_crop':
... |
from django.shortcuts import render
from django.shortcuts import HttpResponse
import json
from django.core import serializers
from cloud.models import Data
# Create your views here.
def index(request):
return render(request, 'cloud/index.html', context={
'title': 'PRP-DGPS',
'content': 'Welcome PRP-DGPS Server :... |
#import libraries
import picamera
from time import sleep
from PIL import Image
#set up the camera
camera = picamera.PiCamera()
try:
#capture at maximum resolution (~5MP)
camera.resolution = (1280, 720)
camera.framerate = 60
camera.vflip = True
camera.hflip = True
camera.start_preview()
#allow camera to AWB
... |
import requests
import json
import base64
from urllib.parse import quote
import os
# 百度AI平台 文字识别API
API_Key = '7ozPdYCKWpXQhGLZingB9Cm8'
Secret_Key = '53GBqlVoF3PNdCNKT4h3G4YTnoAa0uhI'
# 获取文字识别的access_token
def getAipAccessToken():
# client_id 为官网获取的AK, client_secret 为官网获取的SK
host = 'https://aip.baidubce.com... |
# -*- encoding: utf-8 -*-
"""
License: MIT
Copyright (c) 2019 - present AppSeed.us
"""
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.template import loader
from django.http import HttpResponse
from django.contrib import messages
f... |
# Generated by Django 3.0.6 on 2020-05-22 12:10
from django.db import migrations, models
def migrate_data(apps, schema_editor):
RRset = apps.get_model('desecapi', 'RRset')
RRset.objects.filter(touched__isnull=True).update(touched=models.F('created'))
class Migration(migrations.Migration):
dependencies... |
import numpy as np
import scipy.misc
from gym.spaces.box import Box
from scipy.misc import imresize
from cached_property import cached_property
# TODO: move this to folder with different files
class BaseTransformer(object):
"""
Base transformer interface, inherited objects should conform to this
"""
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .layers import DownBlock, Conv, ResnetTransformer
from .stn_losses import smoothness_loss
sampling_align_corners = False
sampling_mode = 'bilinear'
# The number of filters in each block of the encoding part (down-sampling).
ndf = {'A': [32, 64, ... |
#import json
import discord
from discord.ext import commands
#resultsFile = open('polls.json')
#resultsLoad = json.load(resultsFile)
emojiList = [
'1️⃣',
'2️⃣',
'3️⃣',
'4️⃣'
]
class Polling(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def poll... |
from .framework import (
managed_history,
selenium_test,
SeleniumTestCase
)
class HistoryStructureTestCase(SeleniumTestCase):
ensure_registered = True
@selenium_test
@managed_history
def test_history_structure(self):
def assert_details(expected_to_be_visible):
error_... |
damage_data = {}
#Don't touch the above line
"""
mystats module for BombSquad version 1.5.29
Provides functionality for dumping player stats to disk between rounds.
"""
ranks=[]
top3Name=[]
import threading,json,os,urllib.request,ba,_ba,setting
from ba._activity import Activity
from ba._music import setmusic, MusicType... |
import os, re, string
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import bokeh.palettes as bp
from loguru import logger
from GEN_Utils import FileHandling
from ProteomicsUtils import StatUtils
logger.info('Import OK')
input_folder = 'results/recombinant_denaturation/i... |
import torch
from torch import nn
# Disentangle NCE loss in MoCo manner
class DisNCELoss(nn.Module):
def __init__(self, opt):
super().__init__()
self.opt = opt
# feat_B for the background, feat_R for the rain
# shape: (num_patches * batch_size, feature length)
def forward(self, featB,... |
#!/usr/bin/env python
import argparse
from collections import OrderedDict
import sys
from glob import glob
from os.path import join, splitext, basename
XRDB2REM = [
("# Head", "\n" "[ssh_colors]" ),
("background_color", "background = "),
("cursor_color", "cursor = "),
("foreground_color", "for... |
"""Store version constants."""
MAJOR_VERSION = 0
MINOR_VERSION = 17
PATCH_VERSION = '0'
__version__ = '{}.{}.{}'.format(MAJOR_VERSION, MINOR_VERSION, PATCH_VERSION)
|
"""
Support for reading and writing the `AXT`_ format used for pairwise
alignments.
.. _AXT: http://genome.ucsc.edu/goldenPath/help/axt.html
"""
from bx.align import *
import itertools
from bx import interval_index_file
# Tools for dealing with pairwise alignments in AXT format
class MultiIndexed( object ):
""... |
import math
import pickle
import time
from functools import wraps
import cv2
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import scipy.ndimage
### define profilers (https://stackoverflow.com/questions/3620943/measuring-elapsed-time-with-the-time-module)
PROF_DATA = {}
def prof... |
from flask import Flask
from flask_cors import CORS
import os
app = Flask(__name__)
CORS(app)
@app.route('/')
@app.route('/api')
@app.route('/api/get')
async def invalid_request():
return 'Invalid request', 400
@app.route('/api/get/plugins', methods=['GET'])
async def plugins_list():
pluginsListDir ... |
import sklearn, re, nltk, base64, json, urllib2, os
import numpy as np
import cPickle as pickle
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer
import os
MIN_RESULTS = 30 # Minimum number of results needed for valid user input
BASE_SEARCH_URL = 'h... |
import tweepy
import sys
import jsonpickle
import os
# Don't buffer stdout, so we can tail the log output redirected to a file
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# API and ACCESS KEYS
API_KEY = sys.argv[1]
API_SECRET = sys.argv[2]
userIdfName = sys.argv[3]
outfName = sys.argv[4]
auth = tweepy.AppA... |
# 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 u... |
from conans import ConanFile, CMake, tools
class NlohmannjsonConan(ConanFile):
name = "nlohmann_json"
version = "3.1.2"
license = "MIT"
url = "https://github.com/elshize/conan-nlohmann_json"
code_url = "https://github.com/nlohmann/json"
description = "JSON for Modern C++"
build_policy = "a... |
"""
Command line utility to remove files through glob patterns.
"""
import argparse
import glob
from os import path, remove
from sys import exit
from denverapi.colored_text import print
def main():
parser = argparse.ArgumentParser("rmr")
parser.add_argument(
"file", help="the file to ... |
d = {'x':1,'y':2,'z':3}
def a(x,y,z):
return x,y,z
print "\nFunction"
print a(1,2,3)
print a(z=3,x=1,y=2), a(z=3,y=2,x=1), a(y=2,z=3,x=1), a(y=2,x=1,z=3)
def b(x=0,y=0,z=0):
return x,y,z
print "\nFunction with defaults"
print b()
print b(1,2,3)
print b(1), b(2), b(3)
print b(x=1), b(y=2), b(z=3)
print b(x=1... |
from . import callbacks, metrics, nlp_utils
|
import multiprocessing
import os
import time
from multiprocessing import freeze_support
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from datetime import datetime, timedelta
import runpy
def run_py():
runpy.run_path(path_name='main.py')
def rerun_script():
gl... |
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets Authors.
#
# 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 appl... |
# Copyright 2012 Ning Ke
#
# 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, softw... |
# -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function
from .. import __author__, __version__
import win32com.client as x32
import pythoncom
|
# Copyright (c) 2017-2021 Neogeo-Technologies.
# 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... |
#!/home/pi/Python-3.8.5
"""
For modifications and text not covered by other licences:
Original software Copyright (C) 2020 Ward Hills
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Found... |
import json
import pytest
from gidgetlab import RedirectionException
from gidgetlab import abc as gl_abc
class MockGitLabAPI(gl_abc.GitLabAPI):
DEFAULT_HEADERS = {
"ratelimit-limit": "2",
"ratelimit-remaining": "1",
"ratelimit-reset": "0",
"content-type": "application/json",
}... |
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense,Activation
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection import cross_val_score,train_test_split
from sklearn.model_selection import KFold
fro... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class BizOrderQueryResponse(object):
def __init__(self):
self._action = None
self._action_mode = None
self._apply_id = None
self._biz_context_info = None
... |
"""Gravatar Username Data Digger - Digger Downloaded Data for Usefull Information."""
import re
import logging
import urllib
import urllib.parse
from configparser import ConfigParser
from typing import Dict, List, Optional
from bs4 import BeautifulSoup, ResultSet, Tag
from OSIx.core.base_username_data_digger import... |
if __name__ == "__main__":
import sys
sys.path.append("/Users/mike.barrameda/Projects/mfadvisor/mfadvisor-api")
from db import local_engine
from db.base import Base
from models import Account, Category, Transaction, TransactionType
from scripts.seed_categories import seed_categories
from... |
# =============================================================================
# Copyright 2020 NVIDIA. 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://ww... |
"""Helper functions."""
class Board:
def __init__(self, text):
self.has_won = False
self.number_rows = [
(int(rows_text[0:2]),
int(rows_text[3:5]),
int(rows_text[6:8]),
int(rows_text[9:11]),
int(rows_text[12:14])) for rows_text in text.split('\n')]
self.unmarked_set = s... |
from ..engine.agent import Agent
from ..engine.decision import *
import numpy as np
from typing import Union
PlayDecision = Union[ActionPhaseDecision, TreasurePhaseDecision]
def find_card_in_decision(decision, card_name):
if isinstance(decision, PlayDecision.__args__):
for idx, move in enumerate(decisio... |
from requests import post, get
"""
Related methods for submitting requests to the HTB V4 API
"""
def api_get(url: str, endpoint: str, headers: dict) -> list:
"""
api_get: Make a get request to HTB API
:param url: Target url to send request
:param endpoint: API path to a specific resource
:param hea... |
class rotate:
def __init__(self, image=[[0.0]], angle=0):
from scipy import ndimage
self.rot_img = ndimage.rotate(image, angle)
def rotate_img(self: 'array_float'):
return self.rot_img
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2018-03-18 11:50
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("camps", "0024_populate_camp_shortslugs")]
operations = [
migrations.AlterField(
... |
#
# Simson's Sharepoint implementation
# This is how you can read from sharepoint with Windows Domain authentication.
import win32com.client
url = 'https://....'
h = win32com.client.Dispatch('WinHTTP.WinHTTPRequest.5.1')
h.SetAutoLogonPolicy(0)
h.Open('GET', url, False)
h.Send()
result = h.responseText
result
|
from storages.backends.s3boto3 import S3Boto3Storage
from furl import furl
from django.utils.module_loading import import_string
from django.conf import settings
import os
class BaseS3Storage(S3Boto3Storage):
def url(self, name):
url = super(BaseS3Storage, self).url(name)
if not self.querystring... |
from re import fullmatch
pattern1 = r"\s*\w{12,}\s*"
pattern2 = r"[^ieaou]+"
pattern3 = r"^[^ieaou]\w+[^ieaou]$"
pattern4 = r"^[ieaou]\w+[ieaou]$"
pattern5 = r"^\w{3}$"
for i in range(5, 21, 2):
pattern = r"^\w{" + str(i) + "}$"
pattern5 = pattern5 + "|" + pattern
print(pattern5)
with open("dictionary-tur.t... |
from typing import Optional
from botocore.client import BaseClient
from typing import Dict
from typing import Union
from botocore.paginate import Paginator
from datetime import datetime
from botocore.waiter import Waiter
from typing import List
class Client(BaseClient):
def can_paginate(self, operation_name: str ... |
# Copyright 2019 Nokia
#
# 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, softwa... |
"""Maintains a persistent connection to the USRP.
Example usage:
>>> from scos_usrp.hardware import radio
>>> radio.is_available
True
>>> rx = radio
>>> rx.sample_rate = 10e6
>>> rx.frequency = 700e6
>>> rx.gain = 40
>>> samples = rx.acquire_time_domain_samples(1000)
"""
import logging... |
from kratos import *
from lake.modules.aggregator import Aggregator
from lake.attributes.config_reg_attr import ConfigRegAttr
from lake.passes.passes import lift_config_reg
import kratos as kts
class StorageConfigSeq(Generator):
'''
Sequence the reads and writes to the storage unit - if dealing with
a sto... |
from dis_snek import InteractionContext, slash_command
from ElevatorBot.commands.base import BaseScale
from ElevatorBot.core.destiny.dayOneRace import DayOneRace
from Shared.functions.readSettingsFile import get_setting
# =============
# Descend Only!
# =============
class DayOneRaceCommand(BaseScale):
# todo ... |
import os
from unittest import TestCase
from symbol.symbol_maker.reader import Reader
from django.conf import settings
class TestElement(TestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tearDownClass(cls):
pass
def read_by_name(self, name):
path = os.pa... |
#!/usr/bin/env python3
import pygame
import sys
import time
import os
from pygame.locals import *
from .button import Button
from .globals import (screen_width, screen_height, FPS, fps_clock,
fontPath, assetsPath)
from .tool import blit_on, game_quit, remove_plant, show_plant, show_obstacle, set_water
class... |
needs_sphinx = '1.1'
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.imgmath', 'numpydoc',
'sphinx.ext.intersphinx', 'sphinx.ext.coverage',
'sphinx.ext.autosummary', 'matplotlib.sphinxext.plot_directive']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project =... |
import matplotlib.pyplot as plt
import csv
import numpy as np
import os
import re
def getJobHatch(job):
if job == "Foraging" :
return '/';
elif job == "FeedLarvae":
return '\\';
else:
return '';
larvaTask = "LarvaTask";
nurseTask = "FeedLarvae";
foragerTask = "Foraging";
giveFoodTask = "GiveFood";
askFoodTa... |
"""
Client creation action.
~~~~~~~~~~~~~~~~~~~~~~~
"""
from .action import Action
from .action import ActionExecutionException
from .action import InvalidActionConfigurationException
from .utils import get_user_roles
from .utils import InvalidUserResponse
from .utils import process_user_roles
import requests
import ... |
# coding=utf-8
"""
"""
from typing import List, Optional
from modelscript.megamodels.dependencies.metamodels import (
MetamodelDependency
)
from modelscript.megamodels.metamodels import Metamodel
from modelscript.base.metrics import Metrics
# ---------------------------------------------------------------
# A... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import csv
import decimal
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
import http.server
import socketserver
from datetime import datetime
# from pprint import pprint
import r... |
def fact(n):
return 1 if n == 0 else n*fact(n-1)
def p(k, l):
e = 2.71828
return (l**k)*(e**-l) / fact(k)
l = float(input())
k = int(input())
print(round(p(k, l), 3))
|
#!/usr/bin/env python3
import logging
try:
import discord
from discord.ext import commands
except ImportError:
print("Discord.py is required. See the README for instructions on installing it.")
exit(1)
from cogs import get_extensions
from constants import colors, info
from utils import l, LOG_SEP
imp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.