content stringlengths 5 1.05M |
|---|
#necessary packages
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import email
import email.mime.application
import smtplib
import csv
# csv path
csv_path = 'recipients.csv'
with open(csv_path, 'r') as f:
reader = csv.reader... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2021 4Paradigm
#
# 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 ... |
"""
Module: DMS Browser Django Settings URLs
Project: Adlibre DMS
Copyright: Adlibre Pty Ltd 2011
License: See LICENSE for license information
"""
from django.conf.urls import patterns, url
urlpatterns = patterns('browser.views',
url(r'^$', 'setting', name='setting'),
url(r'^plugins$', 'plugins', name='plugi... |
from scraper import *
s = Scraper(start=128304, end=130085, max_iter=30, scraper_instance=72)
s.scrape_letterboxd() |
import sys
sys.path.insert(0, "../")
sys.path.insert(0, ".")
from expanded_checklist.checklist.editor import Editor
from src.tests.fill_the_lexicon import fill_the_lexicon
from src.tests.test_model import quick_test, test_model_on_saved_suite
from src.tests.save_and_load import *
import src.tests.test_creation_utils a... |
# Ke Chen
# knutchen@ucsd.edu
# HTS-AT: A HIERARCHICAL TOKEN-SEMANTIC AUDIO TRANSFORMER FOR SOUND CLASSIFICATION AND DETECTION
# Convert the DESED dataset
import numpy as np
import os
import librosa
import config
from utils import float32_to_int16
import soundfile as sf
def main():
desed_folder = os.path.join(conf... |
from gpiozero import Button
from gpiozero import DigitalInputDevice
from pump_move import PumpMove
import board
import busio
import adafruit_mpr121
from ids import IDS
import time
import math
import os
file_dir = "/home/pi/SocialDrinking/{}"
def pump_calibration(step_size, fname):
old_step = step_size
step =... |
# flake8: noqa
"""
Copyright 2020 - Present Okta, Inc.
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 ... |
import matplotlib.pyplot as plt
import numpy as np
from numpy import linspace, polyfit, polyval
def function(x, func, p):
k=[]
for i in range(p):
k.append(np.polyval(func,x[i]))
return k
def max_err(f1, f2, p):
err=[]
for i in range(p):
err.append(f1[i] - f2[i])
if(err[i]<0... |
import math
from datetime import datetime, timedelta
from .data_types import (
Header, FileControl, BatchHeader,
BatchControl, EntryDetail, AddendaRecord
)
class AchFile(object):
"""
This class is what stores the ach data. Its main external methods
are `add_batch` and `render_to_string`.
""... |
import discord
from discord.ext import commands
from events import *
matchtable = {
'rotmg': "Realm of the Mad God",
'hearthstone': "Hearthstone",
'terraria': "Terraria"
}
tick_emoji = '<:tick:835557074090983434>'
history_id = 835552730563084299
tick_id = int( tick_emoji.strip('>')[7:] )#86085322286432257... |
from .multilayer import *
|
import aoareader as reader
import torch
import time
import argparse
# torch.backends.cudnn.enabled=True
parser = argparse.ArgumentParser(description="train.py")
# train options
parser.add_argument('-traindata', default='data/train.txt.pt',
help='Path to the *-train.pt file from preprocess.py, de... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Написать программу, которая считывает из текстового файла три предложения и выводит их
в обратном порядке.
"""
if __name__ == "__main__":
with open("ind.txt", "r") as txt:
content = txt.readlines()[0:3]
content.reverse()
count ... |
import re
from typing import List
def replace(origin:str,source_list:List[str],target_list:List[str])->str:
for source,target in zip(source_list,target_list):
origin = re.sub(source,target,origin)
return origin
|
from nas_201_api import NASBench201API as API
if __name__ == "__main__":
api = API('/nfs/data/chengdicao/data/NAS-Bench-201/NAS-Bench-201-v1_1-096897.pth', verbose=False)
#api = API('/nfs/data/chengdicao/data/NAS-Bench-201/NAS-Bench-201-v1_0-e61699.pth', verbose=True)
for i in range(5):
config = ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020 Sarubee
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... |
"""
Tree-Controled Grammer parser.
python3
tcgp.py
-g tests/test10.in -i tests/input10.in
"""
import sys
import traceback
import argparse
from parser import Parser
from lr_table import LRTable
from input_parser import InputParser
from debug_print import Debug
from debug_print import debug_print
from debug_print impor... |
class Solution:
def XXX(self, nums: List[int]) -> List[List[int]]:
res = [[]]
for i in nums:
res += [t+[i] for t in res]
return res
|
#!/usr/bin/env python
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8
#
# MDAnalysisData --- https://www.mdanalysis.org
# Copyright (c) 2018 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the ... |
"""Core AppConfig."""
from django.apps import AppConfig
class CoreConfig(AppConfig):
"""Core AppConfig."""
name = "tdpservice.core"
|
# Copyright 2020 The TEMPO Collaboration
#
# 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... |
"""Example of a rule that accesses its attributes."""
def _impl(ctx):
# Print debug information about the target.
print("Target {} has {} deps".format(ctx.label, len(ctx.attr.deps)))
# For each target in deps, print its label and files.
for i, d in enumerate(ctx.attr.deps):
print(" {}. label = {}".format(... |
from socket import *
IP_ADD = 0 # 클라이언트 주소의 주소와 포트 중 주소 인덱스를 가리킴
if __name__ == "__main__":
server_port = 12000
server_socket = socket(AF_INET, SOCK_DGRAM)
server_socket.bind(("", server_port))
print("The server is ready to receive")
while True:
message, client_address = server_socket.rec... |
# -*- coding: utf-8 -*-
from csv import DictWriter
from os import path
from app_logger import app_logging
from execution_error import ExecutionError
class DeviceDataCsvWriter:
def __init__(self):
self.csv_writer = None
@staticmethod
def __get_merged_dict(log_date_time, dev_data, dev_names):
... |
from twilio.rest import Client
account_SID = "AC38e55d46375c83c3a4928ac77fb95526"
auth_token = "71a90f0be1ae9f20c228ea04d932bac7"
client = Client(account_SID, auth_token)
sms = client.messages.create(
to="+92 3351927492",
from_="+1 734 418 6151",
body="Hey, Raja! Congratulaions! You have been place... |
# (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
from functools import wraps
import logging
import subprocess
import tempfile
log = logging.getLogger(__name__)
class SubprocessOutputEmptyError(Exception):
pass
def get_subprocess_output(command,... |
class BACONLangEvaluationError(Exception):
"""Could not find proper method of evaluation"""
pass
|
from django.conf import settings
from django.http import HttpResponseRedirect, HttpResponseNotAllowed
def ssl_required(view_func):
def _checkssl(request, *args, **kwargs):
# Only validate request if ssl enabled (defaults to debug disabled).
if getattr(settings, 'BARBEQUE_SSL_ENABLED', not settings... |
from numpy.matlib import matrix, divide
def diff(mat: matrix, axis: int = 0):
if axis == 0:
return mat[1:, :]-mat[:-1, :]
if axis == 1:
return mat[:, 1:]-mat[:, :-1]
def mean(mat: matrix, axis: int = 0):
if axis == 0:
return (mat[1:, :]+mat[:-1, :])/2
if axis == 1:
retu... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import matplotlib.pyplot as plt
import numpy as np
import time, timeit
import six
import pandas
import CoolProp as CP
from math import ceil
CP.CoolProp.set_debug_level(00)
from matplotlib.backends.backend_pdf import PdfPages
# ... |
import hoi4
import os
import hoi4
import pyradox
techs = hoi4.load.get_technologies()
# child tech -> [parent_tech, ...]
techs_or_dependencies = {}
for tech_key, tech in techs.items():
if isinstance(tech, pyradox.Tree):
for path in tech.find_all('path'):
child_tech_key = path['... |
################################################################################
# #
# This file is part of the Morphomatics library #
# see https://github.com/morphomatics/morphomatics ... |
# =============================
# Variants of Lagrange elements
# =============================
#
# When creating high degree function spaces, it is important to define the
# degrees of freedom (DOFs) of a space in a way that leads to well behaved
# basis functions. For example, if a Lagrange space is created using equ... |
# -*- coding: utf-8 -*-
__author__ = 'gzp'
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from utils import Tree
class Solution:
def binaryTreePaths(self, root):
"""
:type root: Tre... |
"""Unit test for telegram received callback."""
import asyncio
import unittest
from unittest.mock import Mock, patch
from xknx import XKNX
from xknx.dpt import DPTBinary
from xknx.exceptions import CouldNotParseTelegram
from xknx.telegram import (
AddressFilter, GroupAddress, Telegram, TelegramDirection)
class T... |
from __future__ import absolute_import
from future.utils import PY3
__future_module__ = True
if PY3:
from html.parser import *
else:
from HTMLParser import *
|
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ...testing import assert_equal
from ..utility import Merge
def test_Merge_inputs():
input_map = dict(axis=dict(usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault=True,
),
no_flatten=dict(usedefault=True,
),
)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on 12/01/18
@author: Maurizio Ferrari Dacrema
"""
import scipy.sparse as sps
import numpy as np
import pickle
from course_lib.Data_manager.DataSplitter import DataSplitter
class DataSplitter_k_fold(DataSplitter):
"""
The splitter tries to load from... |
'''
202. Happy Number
https://leetcode.com/problems/happy-number/
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the squares of its digits.
Repeat the process until the number eq... |
info = {'personal_data':
{'name': 'Lauren',
'age': 20,
'major':'Information Science',
'physical_features':
{'color': {'eye':'blue',
'hair':'brown'},
'height': '80kg'}
},
'other':
{'favorite_colors': ['purple','gr... |
# ACL Types
PRIVATE = 'private'
PUBLIC_READ = 'public-read'
PUBLIC_READ_WRITE = 'public-read-write'
AUTHENTICATED_READ = 'authenticated-read'
ACCESS_CONTROL_TYPES = [PRIVATE, PUBLIC_READ, PUBLIC_READ_WRITE, AUTHENTICATED_READ]
|
######################################################################
#
# File: b2sdk/upload_source.py
#
# Copyright 2019 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
import hashlib
import os
from ... |
# initting it :)
|
from os import path
import sys
import geoip2.database
import requests
__version__ = '0.20200616.2'
def main(domain, provider=None):
ipa = resolve(domain, provider)
reader = geoip2.database.Reader(
path.join(
path.dirname(__file__),
f'GeoLite2-Country_{__version__[2:-2]}/GeoL... |
import os
import shutil
def copytree(src, dst):
for f in os.listdir(src):
src_path = os.path.join(src, f)
if os.path.isfile(src_path):
shutil.copy2(src_path, dst)
if os.path.isdir(src_path):
dst_path = os.path.join(dst, f)
shutil.copytree(src_path, dst_pa... |
import time
import os
import shutil
import sys
from sys import argv
import pickle
import csv
from collections import defaultdict
import cProfile
import pstats
import pandas as pd
import numpy as np
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import FeatureUnion, Pipeline
from sklearn.preprocessin... |
import uuid
def generate_name(filename):
return "{}/{}/{}".format(
"uploads",
uuid.uuid4(),
filename
)
|
from .common import *
from .utils import *
from .model import *
from .__main__ import *
|
IMUTANT3_URL = "http://gpcr.biocomp.unibo.it/cgi/predictors/I-Mutant3.0/I-Mutant3.0.cgi"
def fetch_IMutant3(driver, sample):
driver.get(IMUTANT3_URL)
driver.find_element_by_xpath("/html/body/center/form/p/table/tbody/tr[4]/td/div/input").click()
driver.find_element_by_xpath("/html/body/center/form/p/table... |
from utils import detector_utils as detector_utils
import cv2
import tensorflow as tf
import multiprocessing
from multiprocessing import Queue, Pool
import time
from utils.detector_utils import WebcamVideoStream
import datetime
import argparse
import json
import time
frame_processed = 0
score_thresh = 0.2
# Create ... |
#!/bin/zsh
'''
Project: Phone Number and Email Address Extractor
Say you have the boring task of finding every phone number and email address in a long web page or document. If you manually scroll through the page, you might end up searching for a long time. But if you had a program that could search the text in your... |
#!/usr/bin/env python
"""Hunts and hunt implementations."""
# pylint: disable=unused-import
from grr_response_server.hunts import process_results
# pylint: enable=unused-import
|
import falcon
from ebl.fragmentarium.application.folio_pager_schema import FolioPagerInfoSchema
from ebl.fragmentarium.application.fragment_finder import FragmentFinder
from ebl.fragmentarium.web.dtos import parse_museum_number
from ebl.users.web.require_scope import require_scope
class FolioPagerResource:
def _... |
from src import reader_utils
import os
import sys
data_path = "data/atomic/"
filename = sys.argv[1]
with open(os.path.join(data_path, filename)) as f:
data = f.readlines()
edge_dict = {}
for inst in data:
inst = inst.strip()
if inst:
inst = inst.split('\t')
src, rel, tgt = inst
sr... |
"""Сборка и настройка параметров рабочего окружения."""
import logging
from pathlib import Path
from dynaconf import Dynaconf
settings = Dynaconf(
environments=True,
envvar_prefix="HLB", # `envvar_prefix` = export envvars with `export HLB_FOO=bar`.
settings_files=("settings.toml", "local_settings.toml")... |
load(
":write_file_private.bzl",
_write_file = "write_file",
)
write_file = _write_file
|
'''
Created on Oct 28, 2015
@author: kashefy
'''
from nose.tools import assert_equals, assert_true, assert_raises
import numpy as np
import nideep.blobs.mat_utils as mu
def test_cwh_to_chw_invalid_dims():
assert_raises(AttributeError, mu.cwh_to_chw, np.random.rand(3))
assert_raises(AttributeError, mu.cwh_to_... |
from hashlib import sha256
from pathlib import Path
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
def create_dir_if_not_exists(path: Path):
if not path.exists():
path.mkdir(parents=Tru... |
import numpy as np
import pandas
import math
import os
import types
import h5py
import pickle
from pathlib import Path
import pandas as pd
from typing import Dict, Any, Optional, List, Tuple
import multiprocessing as mp
import json
from functools import partial
import timeit
from sklearn.metrics import roc_auc_score
... |
"""
Notebook configuration schema.
"""
from __future__ import annotations
import pathlib
from pydantic import PrivateAttr
from mcookbook import CODE_ROOT_DIR
from mcookbook.config.base import BaseConfig
class NotebookConfig(BaseConfig):
"""
Notebook configuration schema.
"""
keep_temp_notebook: bo... |
"""Global index view."""
import pkg_resources
from django.shortcuts import render
def index(request):
"""Basic view."""
plugins = \
[plugin.load() for plugin in
pkg_resources.iter_entry_points(group='elrados.plugins')]
return render(request, "index.html", {
"plugins": plugins
... |
#!/usr/bin/env python
# -----------------------------------------------------------------------------
# VORONOI.BIN_ROUNDESS
# Laura L Watkins [lauralwatkins@gmail.com]
# - converted from IDL code by Michele Cappellari (bin2d_roundness)
# -----------------------------------------------------------------------------
fr... |
"""Pascal Transparent Semantic Segmentation Dataset."""
import os
import logging
import torch
import numpy as np
from PIL import Image
from .seg_data_base import SegmentationDataset
class SberNewSegmentationAll(SegmentationDataset):
"""ADE20K Semantic Segmentation Dataset.
Parameters
----------
root... |
'''
02 - Building a logistic regression model
Time to build your first logistic regression model! As Hugo showed in the video, scikit-learn
makes it very easy to try different models, since the Train-Test-Split/Instantiate/Fit/Predict
paradigm applies to all classifiers and regressors - which are known in scikit-lea... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
# -*- coding: utf-8 -*-
"""
Command-line application controller for opc-diag
"""
from opcdiag.model import Package
from opcdiag.presenter import DiffPresenter, ItemPresenter
from opcdiag.view import OpcView
_CONTENT_TYPES_URI = '[Content_Types].xml'
class OpcController(object):
"""
Mediate between the com... |
#!/usr/bin/env python
from numpy import *
import matplotlib
from ginput_rect import ginput_rect
# Disable interactive mode so that plots are only updated on show() or draw().
# Note that the interactive function must be called before selecting a backend
# or importing pyplot, otherwise it will have no effect.
matplot... |
# [h] adjust vertical metrics
# import
from mojo.roboFont import CurrentFont, CurrentGlyph
from vanilla import *
from hTools2 import hDialog
from hTools2.modules.fontutils import get_full_name
from hTools2.modules.messages import no_font_open
# object
class adjustVerticalMetrics(hDialog):
"""A dialog to adjus... |
# !/usr/bin/env python
# coding: utf-8
# Author: Axel ARONIO DE ROMBLAY <axelderomblay@gmail.com>
# Author: Henri GERARD <hgerard.pro@gmail.com>
# License: BSD 3 clause
"""Test mlbox.preprocessing.drift_thresholder module."""
import pytest
from mlbox.preprocessing.drift_thresholder import Drift_thresholder
from mlbox.... |
# Copyright 2011-2012 the original author or 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... |
from __future__ import print_function, unicode_literals, division
import time
import logging
import os
from subprocess import Popen, PIPE
from tornado.gen import coroutine, sleep
from mpikat.utils.pipe_monitor import PipeMonitor
log = logging.getLogger('mpikat.process_tools')
class ProcessTimeout(Exception):
pas... |
from flask import Flask, jsonify
from flask.views import MethodView
from flask_swagger import swagger
app = Flask(__name__)
class UserAPI(MethodView):
def get(self, team_id):
"""
Get a list of users
First line is the summary
All following lines until the hyphens is added to descri... |
"""
==========================================================================
Fu.py
==========================================================================
Simple generic functional unit for CGRA tile.
Author : Cheng Tan
Date : November 27, 2019
"""
from pymtl3 import *
from pymtl3.stdlib.ifcs impor... |
__author__ = "Fengming Liu"
__status__ = "prototype"
import calendar
import os
import pymongo
import sys
import tarfile
import time
from tw_funcs import create_dir, process_bz2_db, download_archive
import subprocess
# essential variables
year = 2018
month = sys.argv[1]
day_start = int(sys.argv[2])
day_end = int(sys.a... |
#!/usr/bin/env python3
"""
Main file
"""
Server = __import__('1-simple_pagination').Server
server = Server()
try:
should_err = server.get_page(-10, 2)
except AssertionError:
print("AssertionError raised with negative values")
try:
should_err = server.get_page(0, 0)
except AssertionError:
print("Asse... |
"""profile_ex
This module contains supporting code to be used by cProfile
The cProfile can be run on this file (from the commandline) as:
$python -m cProfile profile_ex.py
This module is compatible with Python 3.5.x. It contains
supporting code for the book, Learning Python Application Development,
Packt Publishing.
... |
# Tai Sakuma <tai.sakuma@gmail.com>
##__________________________________________________________________||
import collections
##__________________________________________________________________||
EventBuilderConfig = collections.namedtuple(
'EventBuilderConfig',
'inputPaths treeName maxEvents start name comp... |
import torch
import torch.nn as nn
def optimizer():
pass
def scheduler():
pass
|
# Copyright 2020 Roeland Wiersema
#
# 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 writ... |
# Private credentials. Careful with this information.
# Yes, the filename 'configPrivate.py' is in .gitignore
# but perhaps there are more secure ways. Tell me, thx.
PRODUCTION=False
# Coinbase API credentials:
if not PRODUCTION:
# Sandbox
API_KEY=""
API_SECRET=""
else:
# PRODUCTION
API... |
from fastlmm.util.compute_auto_pcs import compute_auto_pcs
from fastlmm.util.util import manhattan_plot
|
"""
# PROBLEM 7
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime
is 13.
What is the 10,001st prime number?
"""
# Well, the Wikipedia article on the segmented Sieve of Eratosthenes is pretty unclear,
# so I guess I just have to take my best shot at it...
primes = [2]
bits ... |
from ca.base.generations import Generations
from ca.base.gui import play
class Worms(Generations):
states = 6
def birth(self):
return self.live_count in [2, 5]
def survival(self):
return self.live_count in [3, 4, 6, 7]
play(Worms)
|
# encoding: utf-8
'''
@author: developer
@software: python
@file: run8.py
@time: 2021/7/28 22:35
@desc:
'''
str1 = input()
str2 = input()
output_str1 = str2[0:2] + str1[2:]
output_str2 = str1[0:2] + str2[2:]
print(output_str1)
print(output_str2)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Find Regions of interest (ROIs) in a spectrogram
================================================
A spectrogram is a time-frequency (2d) representation of a audio recording.
Each acoustic event nested in the audio recording is represented by an acoustic
signature. W... |
from servicediscovery.methods.method import Method
from servicediscovery.methods.ip import StaticIPMethod, ScanIPRangeMethod
from servicediscovery.methods.dns import DNSMethod
__all__ = ['Method', 'StaticIPMethod', 'ScanIPRangeMethod', 'DNSMethod']
|
import datetime
from collections import defaultdict
import discord
from discord.ext import commands
from mods.cog import Cog
from utils import cache, checks
from utils.time import human_timedelta
class Raids(Cog):
def __init__(self, bot):
super().__init__(bot)
self.mode_map = {'off': 0, 'on': 1, 'strict': 2}
... |
import argparse
import itertools
import json
import os
import re
from collections import defaultdict
from pathlib import Path
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
from tensorboard.backend.event_processing import event_accumulator
numbers = re.compile(r'(\d+)')
BENCHMA... |
#!/usr/bin/env python3
# encoding: utf-8
#
# This file is part of ckanext-doi
# Created by the Natural History Museum in London, UK
from ckan.model import Package, meta
from ckan.model.domain_object import DomainObject
from sqlalchemy import Column, ForeignKey, Table, types
from sqlalchemy.orm import backref, relation... |
# Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module provides a model for a monitoring station, and tools
for manipulating/modifying station data
"""
class MonitoringStation:
"""This class represents a river level monitoring station"""
def __init__(self, station_id, measure_id... |
# coding=utf-8
# @Time : 2020/12/1 11:05
# @Auto : zzf-jeff |
import random
from django.conf import settings
from directory_constants import cms
from rest_framework import serializers
from wagtail.api.v2.serializers import StreamField as StreamFieldSerializer
from wagtail.images.api import fields as wagtail_fields
from core import fields as core_fields
from core.helpers import ... |
# 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
# distributed under t... |
import sys
import os
simulator = sys.platform != "pyboard"
# to overwrite these settings create a config.py file
if simulator:
storage_root = "./fs"
try:
os.mkdir(storage_root)
except:
pass
else:
storage_root = ""
# pin that triggers QR code
# if command mode failed
QRSCANNER_TRIGGE... |
#!/usr/bin/env python
import sys
from greedy_3 import greedy
from score import score
V = E = R = C = X = 0
def read_line():
return [int(i) for i in raw_input().split()]
def parse():
global V, E, R, C, X
V, E, R, C, X = read_line()
latencies = [0] * E
cache_latencies = [[] for _ in xrange(E)]
... |
"""
tf prob for the variational encoder without using Keras Sequential
"""
#%% Imports
import tensorflow as tf
import tensorflow_probability as tfp
# import tensorflow_probability.layers as tfpl
# import tensorflow.keras.layers as tfkl
# is this a better way to import shortcuts??
tfpl = tfp.layers
tfkl = tf.keras.l... |
from osbrain import run_agent
from osbrain import run_nameserver
if __name__ == '__main__':
# System deployment
ns = run_nameserver()
run_agent('Agent0')
run_agent('Agent1')
run_agent('Agent2')
# Show agents registered in the name server
for alias in ns.agents():
print(alias)
... |
from graphviz import Digraph
import os
from pathlib import Path
os.chdir(Path(__file__).parent)
dot = Digraph(comment="Code Flow", format="png")
dot.node("A", "Check option coherence", style="filled", fillcolor="#add8e6")
dot.node("B", "Start default logging", style="filled", fillcolor="#add8e6")
dot.node("C... |
# -*- coding: utf-8 -*-
__author__ = 'aosn'
from flask import Flask, request, jsonify
import random
import json
from entity import Player, Board, Cell
app = Flask(__name__)
# ゲーム開始時のデフォルト設定
players = []
current_player_id = -1
board = Board()
DEFAULT_CASH = 1500 # 開始時の資金$1500
@app.route("/")
def hello():
retur... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.