content stringlengths 5 1.05M |
|---|
import logging
import os
from processFolder import loadTrajectories
from processXML import loadTrajectory
from processXML import loadTrajectoryFromString
from predict import predictDiversion
classifyLogger = logging.getLogger(__name__)
def classifyXml(clf, scaler, interval, xmlstring, threshold):
try:
tr... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class JingdongItem(scrapy.Item):
# define the fields for your item here like:
filename = scrapy.Field()
intruduce = scrapy.Field()
img_... |
def cnd(ip,username,password):
net_dev = {}
net_dev['ip'] = ip
net_dev['username'] = username
net_dev['password'] = password
return net_dev |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
.. module:: filter
:platform: Unix
:synopsis: the top-level submodule of T_System that contains the classes related to T_System's data filter ability.
.. moduleauthor:: Cem Baybars GÜÇLÜ <[email protected]>
"""
import numpy as np
from scipy.signal import butt... |
import Tkinter as tk
import tkMessageBox
import ttk
import tkFont as tkFont
import tkColorChooser
from Tkinter import StringVar, IntVar
class ClockForegroundOptions(tk.Frame):
def __init__(self, master, parent):
tk.Frame.__init__(self, master)
self.parent = parent
self.grid()
self.c... |
import Qt.QtWidgets as QtWidgets
import Qt.QtCore as QtCore
import Qt.QtGui as QtGui
import kitsupublisher.utils.data as utils_data
from kitsupublisher.utils.colors import combine_colors
from kitsupublisher.views.TasksTabItem import TasksTabItem
from kitsupublisher.ui_data.color import (
main_color,
table_alte... |
# Generated by Django 3.1.12 on 2021-06-28 20:03
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
("extras", "0005_configcontext_device_types"),
("contenttypes", "0002_remove_content_... |
class CombineAction(object):
@staticmethod
def combine(action, action_to_combine):
method_name = '_' + action.type
if hasattr(CombineAction, method_name):
return getattr(CombineAction, method_name)(action, action_to_combine)
raise ValueError('Action type {0} is not supported'... |
from __future__ import print_function
import boto3
import json
# needs to be generated
required_steps = {}
required_steps['sum'] = {'sq'}
required_steps['count'] = {'sq'}
required_steps['avg'] = {'sum', 'count'}
required_steps['out'] = {'avg', 'sum', 'count'}
# needs to be generated
work_flow = {
'inputs': {
... |
from sqlalchemy import Column, Integer, String, ForeignKey, Text, or_, desc
from app.models.base import Base, db
from app.models.contest import Contest
from app.models.problem import Problem
from app.models.user import User
from app.models.relationship.problem_contest import ProblemContestRel
class Clarification(Ba... |
import click
import logging.config
import datetime
from config import LOGGING, STUDOMATIC_URL
from session import ScrapeSession
from lxml import html
from ics import Calendar, Event
from pytz import timezone
logging.config.dictConfig(LOGGING)
logger = logging.getLogger('studomatic-scrapper')
class Scrapper(object):
... |
import os
import shutil
import time
from collections import OrderedDict
from copy import deepcopy
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import numpy as np
from skimage import io
from FfmpegWrapper.ffmpeg_wrapper import FfmpegWrapper
from Tracker.tracks_data import VideoMotAssignment
fro... |
# python function def
print '************** Function def Test Programs **************'
def my_abs(x):
if x>=0:
return x
else:
return -x;
print my_abs(-1)
def empty_func(x):
pass
print empty_func(None)
raw_input() |
from temboo.Library.CloudMine.ObjectStorage.ObjectDelete import ObjectDelete, ObjectDeleteInputSet, ObjectDeleteResultSet, ObjectDeleteChoreographyExecution
from temboo.Library.CloudMine.ObjectStorage.ObjectGet import ObjectGet, ObjectGetInputSet, ObjectGetResultSet, ObjectGetChoreographyExecution
from temboo.Library.C... |
from django.conf.urls import patterns, include, url
from .views import MapView
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url('^$', 'mobiletrans.views.index', { 'template_name':'index.html'},
name="index"),
url('^abou... |
from unittest.mock import patch
import pytest
from hydep.settings import SerpentSettings
from hydep.serpent import SerpentRunner
MAGIC_OMP_THREADS = 1234
@pytest.mark.serpent
@patch.dict("os.environ", {"OMP_NUM_THREADS": str(MAGIC_OMP_THREADS)})
def test_runner():
r = SerpentRunner()
assert r.executable is N... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
import time, inspect, re
from datetime import datetime
class PerfBenchmark(object):
PerfNameResults = {} ## <string, List<long>>
ExecutionTimeList = [] # List<l... |
from Collection import *
def topNTime(collection):
time = []
for i in collection:
tmp = str()
tmp += i.__getitem__("StartTime") +" - " + i.__getitem__("EndTime")
time.append(tmp)
counts = []
dell = []
for i in range(len(time)):
count = 1
for j in range(len(ti... |
import autofit as af
from autofit.mock.mock import MockSearch, MockSamples
class MockResult(af.MockResult):
def __init__(
self,
samples=None,
instance=None,
model=None,
analysis=None,
search=None,
mask=None,
model_image=None,
ma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
File to produce Gutzwiller coefficients
Needs some installation from
https://github.com/tcompa/BoseHubbardGutzwiller
Credits:
- https://github.com/tcompa/BoseHubbardGutzwiller
Author: Patrick Huembeli
"""
import math
import numpy
# import matplotlib
# ... |
#!/usr/bin/python
# TODO:
# * Give a useful error if the serial port disappears or has an error.
# * Save and restore state.
import itertools
import logging
import optparse
import subprocess
import sys
import time
import trollius
import trollius as asyncio
sys.path.append('../../legtool/')
from legtool.async imp... |
import numpy as np
import pandas as pd
from orion.primitives.timeseries_anomalies import _find_sequences
from orion.evaluation.utils import from_list_points_timestamps
def format_anomalies(y_hat, index, interval=21600, anomaly_padding=50):
"""Format binary predictions into anomalous sequences.
Args:
y... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
import sys
import getopt
import array
import xml.etree.cElementTree as ET
import subprocess
# from abc import ABCMeta
# class CartelTemplate:
# __metaclass__ = ABCMeta
# @abstractmethod
# def width: raise NotImplementedError
# @abstractmethod
... |
import numpy as np
import random
def blobs(
width=8,
height=8,
k=3,
min_extend=0,
max_extend=1,
random_seed=None):
"""Generates a 1 to k number of blobs on a 2D grid
Args:
width: width of grid generated
height: height of grid generated
k... |
# -*- coding: utf-8 -*-
"""
A class for FFT filtering General-mode spectroscopic imaging data as reported in:
[Rapid mapping of polarization switching through complete information acquisition](http://www.nature.com/articles/ncomms13290)
Created on Tue Nov 07 11:48:53 2017
@author: Suhas Somnath
"""
from __future__ ... |
"""
Assuming that we have some email addresses in the "[email protected]" format, please write program to print the user name of a given email address. Both user names and company names are composed of letters only.
"""
"""Question:
Assuming that we have some email addresses in the "[email protected]" fo... |
from pathlib import Path
import os
import logging
# Build paths inside the project like this: BASE_DIR / 'subdir'.
PROD_STATUS = os.environ.get("PRODUCTION", False)
# Using the production status of the server to set the DEBUG value
# (doing it this way because of a qwerk of the django-celery module).
if PROD_STATUS:... |
import os, sys, re, os.path, copy, pickle, gc, string, weakref, math, new
try:
import numpy # Request, but do not require
except:
pass
import paraview
import paraview.annotation
import paraview.benchmark
import paraview.calculator
import paraview.collaboration
import paraview.compile_all_pv
import paraview.cop... |
'''tzinfo timezone information for America/Port_of_Spain.'''
from pytz.tzinfo import DstTzInfo
from pytz.tzinfo import memorized_datetime as d
from pytz.tzinfo import memorized_ttinfo as i
class Port_of_Spain(DstTzInfo):
'''America/Port_of_Spain timezone definition. See datetime.tzinfo for details'''
zone = '... |
# from data import models
# from algo import pde
# %%
from scipy.linalg import cholesky
import numpy as np
import datetime
from opricer.model import models
from opricer.algo import pde, analytics, mc
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
from scipy.sparse import diags
from scipy.linalg i... |
# PLOTS THE FIELD GENERATED BY THE PF COILS
# Andre Torres
#18.01.19
from field import getPFFlux2
from coilDefinitions import PF0, PF1, PF2, v, ht, hb
import matplotlib.pyplot as plt
import numpy as np
<<<<<<< HEAD
#%matplotlib qt4
=======
%matplotlib qt4
>>>>>>> e2761a0bad5346fc8b93f67684dcc2c0a49829ff
def plotPF(P... |
import json
import uuid
from enum import Enum, IntEnum
from typing import Optional
from fastapi import HTTPException
from pydantic import BaseModel
from sqlalchemy import text
from sqlalchemy.exc import NoResultFound
from sqlalchemy.sql.expression import select
from .db import engine
class InvalidToken(Exception):
... |
import os
import subprocess
prefix = 'raw/'
for id in range(1,105):
filetoread = prefix + 'id_'+str(id)+'.txt'
with open(filetoread, "r") as ins:
linecounter = 0
for line in ins:
linecounter += 1
if linecounter == 1:
year = int(line[-5:])
... |
# Generated by Django 2.1.7 on 2019-03-03 14:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('topic', '0008_auto_20190216_1712'),
]
operations = [
migrations.AlterField(
model_name='topic',
name='pin',
... |
from django.conf import settings
from django.contrib.auth.models import User
from theJekyllProject.models import (
Page, Post, PostCategory, SiteData, SiteSocialProfile, SiteTheme, Repo
)
from github import Github
from markdown2 import Markdown
import html2markdown
import os
import re
import shutil
import subproc... |
# coding: utf-8
#
# Copyright 2014 The Oppia 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
#
# Unless requi... |
import logging
import argparse
import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "3"
import random
import numpy as np
import paddle
from visualdl import LogWriter
from tqdm import tqdm
import paddle.nn.functional as F
from models.modeling import VisionTransformer
from utils.data_utils import get_loader
... |
from TextGameModule import TextGame
# Game start
# To get user's name, we need to build a welcome scene to do it.
TextGame.clearScreen()
# print('歡迎來到文字遊戲世界')
# name = input('請輸入你的名字: ')
# TextGame.clearScreen()
# print("Hello", name)
# print("遊戲即將開始...")
# TextGame.screenWait(500)
# TextGame.showString('abcdefg')
# i... |
names = input().split(", ")
dict_names = {name: {} for name in names}
while True:
command = input()
if command == "End":
break
d_name, d_item, d_value = command.split("-")
if d_item not in dict_names[d_name]:
dict_names[d_name][d_item] = int(d_value)
# [print(f"{k} -> Items: {len(di... |
#!/usr/bin/env python3
from yateto import *
def add(generator, dim, nbf, Nbf, nq, Nq, petsc_alignment):
J_Q = Tensor('J_Q', (Nq,))
Jinv_Q = Tensor('Jinv_Q', (Nq,))
G_Q = Tensor('G_Q', (dim, dim, Nq))
K = Tensor('K', (Nbf,))
K_Q = Tensor('K_Q', (Nq,))
W = Tensor('W', (Nq,))
E_Q = Tensor('E_... |
import numpy as anp
def metadata(A):
return anp.shape(A), anp.ndim(A), anp.result_type(A), anp.iscomplexobj(A)
def unbroadcast(x, target_meta, broadcast_idx=0):
target_shape, target_ndim, dtype, target_iscomplex = target_meta
while anp.ndim(x) > target_ndim:
x = anp.sum(x, axis=broadcast_idx)
... |
from codecs import open
from os import path, listdir
import re
from setuptools import setup, find_packages
from setuptools.command.install import install
here = path.abspath(path.dirname(__file__))
NAME = "mockquitto"
class InstallWithBabel(install):
def run(self):
self.babel_compile()
super().run... |
import scandir
import sys
import os
import re
DEP_RE = re.compile(r"(\s*\.*)(\w+\()")
'''
run from root dir of project
'''
EXCLUDE_DIR = ["venv", ".ipynb_checkpoints","ipynb"]
EXCLUDE_FILE = ["__init__", "auto_doc"]
EXCLUDE_DEPS = ["print","list","enumerate","Exception"]
EXCLUDE_ARG = ["self"]
def get_annotation_list(... |
from django.urls import path
from . import views
app_name = "news"
urlpatterns = [
path("", views.IndexView.as_view(), name="index"),
path(
"<int:year>/<int:month>/<int:day>/<slug:slug>/",
views.ArticleView.as_view(),
name="article",
),
]
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T N A N O
#
# Copyright (c) 2020+ Buro Petr van Blokland + Claudia Mens
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# ---... |
from sqlalchemy import create_engine, Column, Integer, String, Numeric
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.engine.url import URL
import settings
DeclarativeBase = declarative_base()
def create_competitor_prices_table(engine):
DeclarativeBase.metadata.create_all(engine)
def db_c... |
# Generated by Django 3.1.5 on 2021-01-31 17:57
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('network', '0004_auto_20210128_2324'),
]
operations = [
migrations.AlterFie... |
import numpy as np
def vertical_grid(h,dz):
"""
Description:
Computes vertical grid for column model.
Input:
h : depth of ocean [ m ]
dz : size of grid box [ m ]
Output:
zt : vertical grid for ... |
from .util import find_keywords
# putting the old parser back in here for now until there's a solution
# making Automat faster
from .spaghetti import FSM, State, Transition
class MicrodescriptorParser(object):
"""
Parsers microdescriptors line by line. New relays are emitted via
the 'create_relay' call... |
# -*- coding: utf-8 -*-
#from datetime import datetime
# import time
# DateTime
from sqlalchemy import Column, Integer, String, Sequence, ForeignKey, \
create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker, relationship, joinedload, lazyload
... |
"""
Field-like classes that aren't really fields. It's easier to use objects that
have the same attributes as fields sometimes (avoids a lot of special casing).
"""
from django.db.models import fields
class OrderWrt(fields.IntegerField):
"""
A proxy for the _order database field that is used when
Meta.or... |
from converter.qiskit.transpiler._basepasses import TransformationPass
class CXCancellation(TransformationPass):
pass
def run(self, dag):
pass
|
import vsketch
class PenElectrophoresisSketch(vsketch.SketchClass):
rows = vsketch.Param(250)
cols = vsketch.Param(25)
def draw(self, vsk: vsketch.Vsketch) -> None:
vsk.size("a4", landscape=False)
vsk.scale("cm")
vsk.penWidth('.3mm') # Sharpie Ultra Fine
for y in range(1,... |
import unittest
from conans.test.utils.genconanfile import GenConanfile
from conans.test.utils.tools import TestClient
class QbsGeneratorTest(unittest.TestCase):
def test(self):
client = TestClient()
client.run("new dep/0.1 -b")
client.run("create . user/testing")
pkg = GenConan... |
from __future__ import print_function
import sys
from setuptools import setup
from Cython.Build import cythonize
with open('requirements.txt') as f:
INSTALL_REQUIRES = [l.strip() for l in f.readlines() if l]
try:
import numpy
except ImportError:
print('numpy is required during installation')
sys.exit(... |
# Generated by Django 3.1.7 on 2021-04-24 13:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0002_auto_20210424_1632'),
]
operations = [
migrations.AlterModelOptions(
name='auto_brands',
options={'managed': Tr... |
import sys
import os
import signal
from getopt import getopt
from .helper import TujianHelper
from .tools import printSort, getToday, getArchive, getAll, printByPID, getByPID
from .upload import upoladPics
from . import print2
pars = sys.argv[1:]
try:
opt, par = getopt(pars, 'hp:', ['help', 'path='])
except:
T... |
# -*- coding: utf-8 -*-
"""
module containing the logic for the chart abstract base class
"""
__author__ = 'Samir Adrik'
__email__ = '[email protected]'
from abc import abstractmethod
from itertools import chain
import numpy as np
from pyqtgraph import PlotWidget
from PyQt5.QtCore import QObject
from source.ut... |
import os
import glob
import shutil
import pathspec
import click
@click.command()
@click.argument('src',
metavar='<source>',
type=click.Path(exists=True,
dir_okay=True,
readable=True),
required=True,
... |
import cupy
def test_bytes():
out = cupy.random.bytes(10)
assert isinstance(out, bytes)
|
from django.apps import AppConfig
from django.core import checks
from .checks import storage_check
class S3FileConfig(AppConfig):
name = "s3file"
verbose_name = "S3File"
def ready(self):
from django import forms
from django.core.files.storage import FileSystemStorage, default_storage
... |
# -*- coding: utf-8 -*-
from django.http import JsonResponse
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# from django.template import RequestContext
from django import forms
from django.forms import ModelForm
from django.db.models import Q
from django.template.loader i... |
from .graph import Graph
from .vertex import Vertex
import numpy as np
def generate_K(x):
spacing = 2*np.pi/(x)
g = Graph(monitor=False, figsize=(x, x))
for i in range(x):
g.add_vertex(Vertex(name=i, position=((x+3)*np.cos(spacing*i), (x+3)*np.sin(spacing*i)), radius=1))
for j in range(i):
... |
"""
Functies specifiek voor waterschap Vallei en Veluwe
"""
import math
import numpy as np
import geopandas as gpd
import pandas as pd
import fiona
from shapely.geometry import LineString
from tohydamogml.domeinen_damo_1_4 import *
from tohydamogml.read_database import read_filegdb
# Columns in DAMO to search for id ... |
import os
import json
import pathlib
import eland as ed
import pandas as pd
from elasticsearch import Elasticsearch
from slugify import slugify
from typer import Typer
app = Typer()
column_values = {
"INSTNM": str,
"INSTURL": str,
"CITY": str,
"ST_FIPS": int,
"PBI": float,
... |
import os
ROOT_DIR = os.path.abspath(os.path.dirname(__file__))
STATIONS_PATH = os.path.join(ROOT_DIR, "stations.json")
|
from django.urls import path
from django.contrib.auth import views as auth_views
from . import views
from django.conf.urls import url
app_name = "departments"
urlpatterns = [
path('create/new/', views.CreateDepartment , name='create_department'),
path('UIC/all/departments/', views.AllDepartments.as_view(), n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###################################################
#
# pitch2svg.py
#
# Make an SVG of a pitch trace.
#
# Based loosely off code from Martijn Millecamp
# ([email protected]) and
# Miroslav Masat ([email protected]):
# https://github.com/miromasat/... |
# Copyright 2014 Diamond Light Source Ltd.
#
# 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 t... |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Defines the UIAutomatorOptions named tuple."""
import collections
UIAutomatorOptions = collections.namedtuple('UIAutomatorOptions', [
'tool',
'c... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/760/A
m,d = list(map(int,input().split()))
l = [None] + [31,28] + [31,30]*2 + [31,31] + [30,31]*2
print((l[m]+d+5)//7)
|
"""
a person object: fields + behavior
change: the tax method is now a computed attribute
"""
class Person:
def __init__(self, name, job, pay=0):
self.name = name
self.job = job
self.pay = pay # real instance data
def __getattr__(self, attr): # on person.attr... |
from django.db import models
from django.urls import reverse
# Create your models here.
class Schedule(models.Model):
DAY_CHOICES = [
('A','A'),
('B','B'),
('C','C'),
('D','D'),
('E','E'),
]
day = models.CharField(max_length=1,choices=DAY_CHOICES)
date = models.DateField(auto_now_add=True)
def __str__(self):... |
'''
Functions given the file list of korenberg photography
For each block, the entier file list is split into 3 groups:
filelist = bad + moderate + great
good files = moderate + great
'''
import matplotlib.pyplot as plt
import PyCACalebExtras.Common as cc
import PyCACalebExtras.Display as cd
import PyCA.Core as ca
... |
""" Example of using the API class """
from filmweb_api import FilmwebApi
if __name__ == '__main__':
filmweb_api = FilmwebApi('USERNAME', 'PASSWORD')
filmweb_api.login()
films = filmweb_api.get_user_films_want_to_see()
print(films)
films = filmweb_api.get_film_info_full(824633)
print(films)
|
import time
import logging
import threading
class Log(object):
_loggers = {}
CRITICAL=logging.CRITICAL
ERROR=logging.ERROR
WARNING=logging.WARNING
INFO=logging.INFO
DEBUG=logging.DEBUG
NOTSET=logging.NOTSET
chosen_level=logging.INFO
COLOURS = {
"critical": "\033[1;31;40m... |
import numpy as np
import numpy.linalg as la
class GROUSE(object):
def __init__(self, n, d, U = None, eta = None):
self.n = n
self.d = d
if U is not None:
self.U = U
else:
self.U = np.eye(N=self.n, M=self.d)
if eta is not None:
self.eta0... |
# I was going to do numbers and strings together but nope, we ain't doing it that way
# write a string using " " or ' '
"this is a string"
'this is also a string'
""" this
is
also
a
string
"""
'''
this
as
well
'''
"i'll stop being annoying now"
a_string_variable = "assign a string to a variable"
print("i know th... |
# yedict_script.py
"""Script for generating two files from the yedict dictionary. One for traditional
characters and one for simplified characters. One word per line.
"""
path = 'data/yedict.txt'
simp_path = 'data/yue-Hans.txt'
trad_path = 'data/yue-Hant.txt'
def main():
with open(path, 'r') as f:
wi... |
import os
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import MonthLocator
# import matplotlib.ticker
import numpy as np
from sense.canopy import OneLayer
from sense.soil import Soil
from sense import model
import scipy.stats
from scipy.optimize import min... |
# Copyright (c) 2014 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Proof for adding 3 operand xmm/memory fp scalar ops."""
import proof_tools
from proof_tools_templates import XmmOrMemory3operand
# FP scalar (... |
from django.test import TestCase
from ..models import Puppy
class PuppyTest(TestCase):
""" Test module for Puppy model """
def setUp(self):
Puppy.objects.create(
name='Casper', age=3, breed='Bull Dog', color='Black')
Puppy.objects.create(
name='Muffin', age=1, breed='G... |
"""
Implementation for AWS SecretsManager
@author Arttu Manninen <[email protected]>
"""
import re
from config.external.aws.boto3 import Boto3
from config.external.interface import ExternalInterface
boto3 = Boto3()
class SecretsManager(ExternalInterface):
def load(self):
""" Load AWS SecretManager secrets ... |
ip_ranges = {
"Bank of Canada": [
"140.80.0.0/16"
],
"CRTC": [
"199.246.230.0/23",
"199.246.232.0/21",
"199.246.240.0/21",
"199.246.248.0/22",
"199.246.252.0/23"
],
"Canada Centre for Inland Waters": [
... |
# coding: utf-8
"""
EVE Swagger Interface
An OpenAPI for EVE Online # noqa: E501
OpenAPI spec version: 0.8.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from swagger_client.models.get_loyalty_stores_corporation_id_off... |
import boto3
import sure # noqa # pylint: disable=unused-import
from moto import mock_ec2, mock_kms
from tests import EXAMPLE_AMI_ID
@mock_ec2
@mock_kms
def test_run_instance_with_encrypted_ebs():
kms = boto3.client("kms", region_name="us-east-1")
resp = kms.create_key(Description="my key", KeyUsage="ENCRYP... |
# 1046. Last Stone Weight - LeetCode Contest
# https://leetcode.com/contest/weekly-contest-137/problems/last-stone-weight/
class Solution:
def lastStoneWeight(self, stones) -> int:
stones = sorted(stones,reverse=True)
while len(stones) > 1:
first_stone = stones.pop(0)
second... |
import eel
import random
from time import sleep
eel.init("front")
@eel.expose
def randGen(top):
for num in range(top):
#print in front end
eel.diceShow(random.randint(1,top))
if top > 100:
sleep(.015)
else:
sleep(.15)
eel.start("front.html")
|
from datetime import datetime
from django.shortcuts import get_object_or_404
from django.views import generic
from django.conf import settings
from django.db.models import Sum, Count, ExpressionWrapper, Max, Min, DurationField
import json
from .models import Observations, Pulsars, Proposals, Ephemerides, Utcs, get_o... |
import sys
from ai_interface import *
from utils import *
class TestAI:
def __init__(self):
pass
def action(self, state):
res = {}
for ship in state.my_ships:
if state.my_side == Side.DEFENSE:
if ship.params.soul > 1 and ship.temp > 0:
... |
def count_subsets(nums, sum):
n = len(nums)
dp = [[-1 for x in range(sum + 1)] for y in range(n)]
# populate the sum = 0 columns, as we will always have an empty set for zero sum
for i in range(0, n):
dp[i][0] = 1
# with only one number, we can form a subset only when the required sum is e... |
import numpy as np
import matplotlib.pyplot as plt
import reltest
from reltest.mctest import MCTestPSI, MCTestCorr
import reltest.mmd as mmd
import reltest.ksd as ksd
from reltest import kernel
from kmod.mctest import SC_MMD
from freqopttest.util import meddistance
import logging
import sys
import os
from ex_models imp... |
#
# This file is part of ravstack. Ravstack is free software available under
# the terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2015 the ravstack authors. See the file "AUTHORS" for a
# complete list.
from __future__ impo... |
import os
from leapp.actors import Actor
from leapp.models import RpmTransactionTasks
from leapp.tags import IPUWorkflowTag, FactsPhaseTag
class TransactionWorkarounds(Actor):
"""
Provides additional RPM transaction tasks based on bundled RPM packages.
After collecting bundled RPM packages, a message wi... |
# Copyright 2014 Florian Ludwig
#
# 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 writin... |
import math
import random
import numpy as np
from src.dataclass import Context
from src.model import LinearAttention, Trainer
from src.utils.formatting import pretty_print
import tensorflow as tf
def setup_torch(seed: int):
random.seed(seed)
np.random.seed(seed)
def get_model(ctx: Context, load_model: b... |
#!/usr/bin/env python
from __future__ import print_function
import optparse
import re
from bs4 import BeautifulSoup
def ftp_profile(publish_settings):
"""Takes PublishSettings, extracts ftp user, password, and host"""
soup = BeautifulSoup(publish_settings, 'html.parser')
profiles = soup.find_all('publishprofi... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
from jpype import *
import yaml
import numpy as np
import sys
sys.path.append("resources")
from python.TreeBuilder import *
import unittest
startJVM(getDefaultJVMPath(), "-ea", "-Djava.class.path=%s" % "./RiverSolver.jar")
PokerSolver = JClass('icybee.solver.runtime.PokerSolver')
class TestSolver(unittest.TestCase):
... |
# Robert Li 18 March 2019 <[email protected]>
# Predicting 2019 AFL results for fun
# Based on https://github.com/dashee87/blogScripts/blob/master/Jupyter/
# 2017-06-04-predicting-football-results-with-statistical-modelling.ipynb
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.stat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.