text stringlengths 3.07k 12.6k |
|---|
# Copyright 2017-2020 TensorHub, 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 writ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2016 <NAME> <<EMAIL>>
#
# 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 requ... |
import json
import requests
from flask import render_template, render_template_string, request, jsonify, make_response, send_from_directory, url_for
from markupsafe import Markup
from urllib.parse import quote
from app import app, db
from app.models import Dump, ZenodoTarget, Zenodo, Run
from datetime import datetime, ... |
# Jordans attempt at Conways Game of Life
#
import pygame, sys, random, copy
width = 640 # window width
height = 480 # window height
bin_size = 8 # window bins
stall = 200 # milliseconds between refresh
dorand = True # fill random bins
rand_amount = 10000 # how many ran... |
from __future__ import print_function
import h5py
import numpy as np
np.random.seed(0)
# ----------------------------------------------------------------------
fname = '../dst_bolo.hdf'
print('Reading:', fname)
f = h5py.File(fname, 'r')
pulses = np.array(sorted(f.keys()))
print('pulses:', len(pulses))
# ----------... |
#!/usr/bin/python3
# <NAME>
# 2020-1-28
# media_db.py
"""Simple database for various forms of media."""
import pickle
def menu():
print()
print("| Simple Media Database |")
print("_________________________")
print()
print("Enter a number at the arrow prompt (->):")
print()
print("Co... |
import platform
import sys
from django.conf import settings
from django.db.models import F
from django.http import HttpResponseServerError
from django.shortcuts import render
from django.template import loader
from django.template.exceptions import TemplateDoesNotExist
from django.urls import reverse
from django.views... |
# Copyright 2018 <NAME>
#
# 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... |
#############################################################################
# Copyright (C) 2020-2021 German Aerospace Center (DLR-SC)
#
# Authors: <NAME>
#
# Contact: <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License... |
import random
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d
from firefly import Firefly
from config_file import POP_SIZE, MAX_GEN, DIM_SIZE, UB, LB, BUILDING, Location_Array, Firefly_List, O_Firefly_List, Fitnesses, Best
# check if the drone is inside the building or not
def ... |
import requests
import six
from dictutils import AttrDict
from .utils import import_module
class Empty(object):
pass
class Request(object):
def __init__(self, resource):
self.resource = resource
self.method = 'get'
self.headers = {
'User-Agent': 'http-resource/1.0',
... |
#!/usr/bin/env python3.6
"""run rdflib performance tests
Usage:
rdflib_profile [options]
Options:
-s --setup run setup only
-p --pipenv setup pipenv
-l --local run tests in the parent process rather than forking
"""
from __future__ import print_function
import os
import sys
import strin... |
import json
import sys
sys.path.append("../../../")
from tf2onnx import utils
import tensorflow as tf
def write(lists, filename):
writer = open(filename, 'w+')
for idx, item in enumerate(lists):
print(idx, file=writer)
print(item, file=writer)
writer.close()
def write_nodes(ops, filename):
writer = open(file... |
# Tested on python 2.6.6, 2.7
from __future__ import absolute_import, with_statement
import base64
import datetime
import hashlib
import hmac
import json
import contextlib
from lenddo_api_client import compat
def build_query(params):
"""Return a URL-encoded query string from parameter dict ready
for use in ... |
# -*- coding: utf-8 -*-
from __future__ import with_statement, unicode_literals
from ziggurat_foundations.tests.conftest import (
User,
Group,
GroupPermission,
UserPermission,
UserResourcePermission,
GroupResourcePermission,
Resource,
ResourceTestObj,
ResourceTestobjB,
)
from ziggur... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import and_, or_
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///advanced-condition.sqlite"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db... |
# Copyright 2020 Cortex Labs, 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 wri... |
"""
Class to encapsulate geo-coding jobs in the Geocode Dataflow API.
See API documentation:
https://docs.microsoft.com/en-us/bingmaps/spatial-data-services/geocode-dataflow-api/
"""
import time
import requests
from dataclasses import dataclass
from .exceptions import BingAPIError, BingStallError, BingTimeoutError... |
#!/usr/bin/env python
# encoding: utf-8
import collections
from intervaltree import IntervalTree,Interval
import math
import os
import six
import sys
import pfp.utils as utils
class EOFError(Exception): pass
def bits_to_bytes(bits):
"""Convert the bit list into bytes. (Assumes bits is a list
whose length is... |
import pytest
from bs4 import BeautifulSoup
from deutschland.lebensmittelwarnung.lebensmittelwarnung import (
WarningFeed,
WarningFeedUrl,
Warning,
Lebensmittelwarnung,
)
def test_lebensmittelwarnung_all_content_types_all_regions():
"""
Checks if any results are returned without search limitat... |
import json
from collections import defaultdict
from django.urls import reverse
from django.utils.http import urlencode
from geonames_place.models import Place
from radical_translations.agents.models import Organisation, Person
from radical_translations.core.models import Contribution, Resource, ResourceLanguage
cl... |
import requests
from bs4 import BeautifulSoup
import struct
from fortranformat import FortranRecordReader
from contextlib import contextmanager
import datetime
import numpy as np
import re
import pandas as pd
import sys
import locale
import threading
class Sounding(object):
COLUMNS = ["TYPE", "PRESSURE", "HEIGHT"... |
# Copyright 2020-2022 Huawei Technologies Co., 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 agre... |
import datetime
import shutil
import pytest
from ramp_utils import read_config
from ramp_utils.testing import database_config_template
from ramp_utils.testing import ramp_config_template
from ramp_database.model import Model
from ramp_database.utils import setup_db
from ramp_database.utils import session_scope
from... |
import asyncio
from enum import Enum, unique
from logging import getLogger
from typing import Optional, Union
import aiormq
from .message import Message
from .types import TimeoutType
log = getLogger(__name__)
@unique
class ExchangeType(Enum):
FANOUT = "fanout"
DIRECT = "direct"
TOPIC = "topic"
HE... |
# -*- coding:utf-8 -*-
"""
OOP,model 类声明
"""
from __future__ import unicode_literals
from django.db import models
# Create your models here.
'''
ForumUser 对应的 attribute:
topic_author:发表的帖子对应的 author
last_reply_author:最后回复的作者
reply_author:作者发表的每一篇回复对应的 author
notify_user:当有回复的时候,参与回复的 author
trigger_user:当有回复的时候,... |
# algorithm:
# 0. remove from consideration any QC test that fails to produce TPR / FPR >= some tunable threshold
# 1. remove from consideration any bad profile not flagged by any test; put these aside for new qc test design
# 2. accept all individual qc tests with 0% fpr; remove these from consideration, along with al... |
"""Test the integrators using a simple system
Two isotope system, with isotope A initially present and B absent.
The transmutation chain is A (n,gamma) -> B (n,gamma) -> removed,
and contained in a companion xml file. The isotopes are named U235
and Xe135 because the chain and framework expects real isotope names.
For... |
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.autograd import Variable
from torch.optim import lr_scheduler
import time
import numpy as np
###############################################################################
# Functions
##############################################... |
from itertools import product
import torch
import torch.nn as nn
import torch.nn.functional as F
def conv3x3(in_features, out_features, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(
in_features, out_features, kernel_size=3, stride=stride, padding=1, bias=False
)
# Net of flow a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------------------------------------------------------------
# includes
# 2+3 compat
from __future__ import absolute_import, division, print_function, unicode_literals
# standards
import re
# 3rd par... |
# Copyright 2015 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.
"""Model types for describing description xml models."""
from xml.dom import minidom
import sys
import os
import pretty_print_xml
def GetComments(node):... |
# Copyright (c) 2019 Horizon Robotics. 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 applicab... |
"""
IPCS commands
=============
Shared parsers for parsing output of the ``ipcs -s`` and ``ipcs -s -i``
commands.
IpcsS - command ``ipcs -s``
---------------------------
IpcsSI - command ``ipcs -s -i {semaphore ID}``
----------------------------------------------
"""
from insights.util import deprecated
from .. imp... |
""""
Read data from Mi Temp environmental (Temp and humidity) sensor.
"""
from datetime import datetime, timedelta
from enum import Enum
import logging
from threading import Lock
from btlewrap.base import BluetoothInterface, BluetoothBackendException
_HANDLE_READ_BATTERY_LEVEL = 0x0018
_HANDLE_READ_FIRMWARE_VERSION =... |
import json, sys, os, zipfile, shutil, cv2
import tensorflow as tf
import numpy as np
from google.cloud import firestore, storage
from tensorflow import keras
from tensorflow.keras import layers
modelFilenames = [] # Stores list of filenames, to delete after execution
modelDirectories = [] # Stores list of directories... |
#!/usr/bin/env python3
import tarfile
from tarfile import TarFile, TarInfo
import zipfile
from zipfile import ZipFile, ZipInfo
import json
import os
from io import BytesIO
import stat
from shutil import copyfileobj
import time
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
with open(os.pa... |
import re
from . import orm
from sqlalchemy import Table, Column, Integer, Index, ForeignKey, sql
from sqlalchemy.orm import Session
class TempTableStateError(RuntimeError):
"""Raised when a manipulation requires the temp table to exist in the database but it does not, or vice versa."""
class TempTableState(objec... |
'''
Nasdaq Stock
Stock data extractory
To Use:
ticker = 'xxx'
stock_data = nasdaq_stock.stock(ticker)
'''
import requests
from lxml import html
from lxml import etree
import datetime
price_xp = '/html/body/div[1]/div/div/div[1]/div/div[2]/div/div/div[5]/div/div/div/div[3]/div[1]/div/span[1]/text()'
rang... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import logging
from contextlib import contextmanager
import torch
import torch.distribut... |
# Modified from TensorFlow object detection code in
# https://github.com/tensorflow/models/blob/master/research/object_detection/dataset_tools/create_pascal_tf_record.py
#
# Changed input data structure from XML to JSON
# Added randomizing to split the data into training and validation data
#
# Original license:
#
#... |
import re
import utilities.misc as misc
from config.regex_patterns import patterns, hindi_numbers
from anuvaad_auditor.loghandler import log_info, log_exception
from utilities import MODULE_CONTEXT
import numpy as np
'''
Below funtions are meant to handle date, numbers and URls as part of pre and post translation proc... |
# Timer that matches machine.Timer (https://docs.micropython.org/en/latest/library/machine.Timer.html)
# for the unix port.
#
# MIT license; Copyright (c) 2021 <NAME>
#
# Based on timer.py from micropython-lib (https://github.com/micropython/micropython-lib/blob/master/unix-ffi/machine/machine/timer.py)
import ffi
... |
# -*- coding: utf-8 -*-
# DjangoRest imports
from django.db import connection
from django.shortcuts import render, HttpResponse, redirect
import requests,json
from rest_framework import viewsets
# Local DjangoRest and API Swagger doc imports
from natural_search.models import Project, Proponent
from natural_search.seri... |
import json
import tempfile
import time
from contextlib import suppress
from datetime import datetime
from pathlib import Path
import pytest
from httpie.internal.daemon_runner import STATUS_FILE
from httpie.internal.daemons import spawn_daemon
from httpie.status import ExitStatus
from .utils import PersistentMockEnv... |
import pytest
from fakeredis import FakeStrictRedis
from sentry_sdk.integrations.rq import RqIntegration
import rq
try:
from unittest import mock # python 3.3 and above
except ImportError:
import mock # python < 3.3
@pytest.fixture(autouse=True)
def _patch_rq_get_server_version(monkeypatch):
"""
P... |
import os, logging, fnmatch
from subprocess import check_output
logger = logging.getLogger(__name__)
# PulseBlaster boards from SpinCore stream digital pulses on many RF channels.
# TODO: Add more documentation, make client robust to crashes by stashing in file
def find_files(directory, pattern):
'''Recur... |
"""Contains the functions to complete montecarlo calculations and graphing"""
from .hamiltonian import *
import numpy as np
import matplotlib.pyplot as plt
plt.clf()
plt.cla()
plt.close()
import random
import math
def average(list):
"""Computes the average of any input list, in our case the list of energies
:... |
#!/usr/bin/python3
import pytest
from brownie import accounts, compile_source
module_source = """
pragma solidity 0.4.25;
contract TestModule {{
address owner;
constructor(address _owner) public {{ owner = _owner; }}
function getOwner() external view returns (address) {{ return owner; }}
function... |
"""
Unit tests for Moab simulator
"""
__copyright__ = "Copyright 2020, Microsoft Corp."
# Temporarily set reportIncompatibleMethodOverride to false to work
# around a short-term bug in the typeshed stub builtins file.
# This can be removed at a later time.
# pyright: strict, reportIncompatibleMethodOverride=false
imp... |
# Copyright (c) 2020, <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
from IPython.display import clear_output
from time import time
import os.path
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
from sklearn.metrics import confusion_matrix
import pyro
from pyro import distributions as dist
from pyro.infer.mcmc import MCMC, NUTS
from pyro.nn i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2019 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the ... |
import requests
import sys
from colorama import Fore, Back, Style, init
import os
import random
from random import randint
import time
init(convert=True)
sucess = 0
failed = 0
counter = 1
# -*- coding: ascii -*-
version = "3.0 DEV"
build = "27"
characters = ' !"#$%&()*+,-./0123456789:;<=>?@ABCDE... |
from encoder.visualizations import Visualizations
from encoder.data_objects import SpeakerVerificationDataLoader, SpeakerVerificationDataset
from encoder.params_model import *
from encoder.model import SpeakerEncoder
from utils.profiler import Profiler
from pathlib import Path
from accelerate import Accelerator
import ... |
from config import *
import numpy as np
from numba import jit,njit,prange
import pygame
from cv2 import imwrite,transpose,imread,imshow,waitKey
import matplotlib.pyplot as plt
# -----------------------------------------------------------------------------
# Funções fora da classe para usar o numba já que por algum mot... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... |
import warnings
from contextlib import contextmanager
from kombu import Connection
from kombu.exceptions import ChannelError
from kombu.pools import connections, producers
from nameko.constants import (
DEFAULT_RETRY_POLICY, DEFAULT_TRANSPORT_OPTIONS, PERSISTENT
)
class UndeliverableMessage(Exception):
""" ... |
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
dhtPin = 17
MAX_UNCHANGE_COUNT = 100
STATE_INIT_PULL_DOWN = 1
STATE_INIT_PULL_UP = 2
STATE_DATA_FIRST_PULL_DOWN = 3
STATE_DATA_PULL_UP = 4
STATE_DATA_PULL_DOWN = 5
def read_dht():
GPIO.setup(dhtPin, GPIO.OUT)
GPIO.output(dhtPin, GPIO.HIGH)
time.... |
import pygame
import textures
import map
from pygame.math import Vector2 as vect
from settings import *
from os import path
class Player(pygame.sprite.Sprite):
def __init__(self, game, character):
pygame.sprite.Sprite.__init__(self)
self.game = game
self.character = character
... |
# Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/.
import os
import os.path
import re
from typing import Any, Dict, NamedTuple, Optional, cast
from pithy.dict import dict_set_defaults
from pithy.eon import parse_eon_or_fail
from pithy.fs import find_project_dir, list_dir, ... |
import torch
import gym
import numpy as np
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import matplotlib.pyplot as plt
# Constants
GAMMA = 0.99
class ActorCriticNetwork(nn.Module):
def __init__(self, num_inputs, num_actions, hidden_size1=6... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright © 2014 <EMAIL>
#
# MIT Licence. See http://opensource.org/licenses/MIT
#
# Created on November 18, 2014
#
from __future__ import unicode_literals
import os
import sys
import unittest
if __name__ == '__main__':
# add path to module root to `$PATH`
root = os... |
import math
import torch
from torch import nn as nn
from models.archs.arch_util import make_layer
class Upsample(nn.Sequential):
"""Upsample module.
Args:
scale (int): Scale factor. Supported scales: 2^n and 3.
num_feat (int): Channel number of intermediate features.
"""
def __init__... |
from __future__ import unicode_literals
from collections import OrderedDict
from datetime import datetime
from dateutil.tz import tzoffset
from javaproperties import dumps
def test_dumps_nothing():
assert dumps({}, timestamp=False) == ''
def test_dumps_simple():
assert dumps({"key": ... |
def image():
root = Tk()
canvas = Canvas(root, width = 600, height = 600)
canvas.pack()
img = PhotoImage(file="/Users/sidneysadel/Downloads/final proj/gui/roulette2.png")
canvas.create_image(20,20, anchor=NW, image=img)
exit_button = Button(root, text="Exit", command=root.dest... |
import csv
import itertools
import os
import pprint
import math
import config
class Environment(object):
def __init__(self, mapping, time_scaling_factor, reactivation_hours, start_time_step=0):
self._mapping = mapping
self._current_hour = 0
self._tsf = time_scaling_factor
self._cur... |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
from datetime import datetime, timedelta
import logging
import sys
import re
from signal import signal, SIGINT, SIGTERM, SIGUSR1
from apscheduler.schedulers import SchedulerNotRunningError
from fasteners import InterProcessLock
from deck_chores import __version__ # noqa: F401 # used only in f-string
from deck_chore... |
import unittest
from wilson.util.qcd import alpha_s, m_b, m_c, m_s
# All numbers compared to Mathemetica version of RunDec
delta = 1e-8
deltam = 1e-4
class TestMb(unittest.TestCase):
def test_m_b(self):
self.assertAlmostEqual(m_b(4.2, 50, 5),
3.03526,
... |
#!/usr/bin/env python3
# dcfac0e3-1ade-11e8-9de3-00505601122b
# dce9cf60-42b6-11e9-b0fd-00505601122b
# 7d179d73-3e93-11e9-b0fd-00505601122b
import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
import sklearn.metrics
from sklearn.metrics.pairwise import rbf_kernel,polynomial_kernel
def kernel(... |
def get_view_posts(day, links):
#linksP = [[60,'<NAME>','https://www.linkedin.com/posts/rodneydaut_failuretosuccess-linkedin30daysprint-activity-6886695645353127936-sRQx'],[61,'<NAME>','https://www.linkedin.com/posts/roseyhwang_coaching-business-entrepreneurship-activity-6886698097083224064-Lvdi']]
#linksC =... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""rudimentary unit tests
"""
import unittest
from pathlib import Path
import pint.quantity as pq
try:
import ruamel_yaml as yaml
except ImportError:
from ruamel import yaml
import warnings
# add exception as pywintypes imports a deprecated module
warnings.filter... |
import operator
from typing import Any, Callable, TypeVar, Generic
from amino.util.fun import format_funcall
A = TypeVar('A')
B = TypeVar('B')
def lop(op, s):
def oper(self, a):
return self.__lop__(op, s, a)
return oper
def rop(op, s):
def oper(self, a):
return self.__rop__(op, s, a)
... |
from time import sleep
import sys
import os
from playsound import playsound
from game.World import *
# Non-dependant sound directory setup ##################################################################################
root_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
prompt_continue = os.pat... |
import spacy
import neuralcoref
import csv
import nltk
import json,os
import time
nlp = spacy.load("en_core_web_sm")
nlp = spacy.load('en')
neuralcoref.add_to_pipe(nlp)
doc = nlp("The ball is underneath the table and it is beside the cat")
nouns =[]
visited = []
landmark = []
prep = []
trajector = []
with open('Spat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Module containing useful functions for testing with PyTorch.
Created on Thu Oct 25 16:09:50 2018
@author: nicolas
"""
import numpy as np
import matplotlib.pyplot as plt
import torch, torchvision
from utils_data import make_images_valid
from utils_common.image impor... |
from glados.es.ws2es.es_util import DefaultMappings
import glados.es.ws2es.progress_bar_handler as progress_bar_handler
import glados.es.ws2es.signal_handler as signal_handler
import requests
import sys
import zlib
BASE_EBI_URL = 'https://www.ebi.ac.uk'
UNICHEM_FTP_URL = 'http://ftp.ebi.ac.uk/pub/databases/chembl/UniC... |
# Copyright 2020 The Bazel 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 required by applicable la... |
from tensorflow.keras.models import Model
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
import numpy as np
def plot_history(history, save=True, base_name='fig'):
for i in range(len(history)):
plt.plot(h... |
# Copyright 2022 The Bazel 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 required by applicable la... |
#!/usr/bin/env python
"""
ctypesgen.descriptions contains classes to represent a description of a
struct, union, enum, function, constant, variable, or macro. All the
description classes are subclassed from an abstract base class, Description.
The descriptions module also contains a class, DescriptionCollection, to ho... |
import sys
from typing import List, Tuple
import time
import random
import math
import copy
"""
SA for example problem:
https://atcoder.jp/contests/future-contest-2018-qual/tasks/future_contest_2018_qual_a
"""
class Mountain:
def __init__(self, y: int, x: int, height: int):
self.y: int = y
self... |
# Image Resizer
# imported necessary library
import tkinter
from tkinter import *
import tkinter as tk
import tkinter.messagebox as mbox
from resizeimage import resizeimage
from tkinter import ttk
from tkinter import filedialog
import PIL
from PIL import ImageTk, Image
import cv2
import os
import numpy as np
import r... |
from typing import Dict, Tuple
from django.test import SimpleTestCase
from corehq.util.metrics.datadog import DatadogMetrics
from corehq.util.metrics.prometheus import PrometheusMetrics
from corehq.util.metrics.tests.utils import patch_datadog
from prometheus_client.samples import Sample
from prometheus_client.utils ... |
""" HSC Datasets """
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from . import hsc_utils
from . import astroimage_utils
from tensor2tensor.data_generators import generator_utils
from tensor2tensor.data_generators import image_utils
from tensor2tensor.d... |
from abc import ABC
from enum import Enum
from pubsub import pub
class PinType(Enum):
"""An enum type to denote the type of pin"""
Testable = 0,
GPIO = 1,
ADC = 2,
PWM = 3,
UART = 4
class Pin(ABC):
"""Holds information about a BBB pin."""
def __init__(self, config):
"""Creat... |
import argparse
import glob
import html
import os
import pickle
import re
import time
from collections import Counter
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy
from tqdm import tqdm
REGEX_TOKEN = re.compile(r'(?<![#@])\b[a-z]{1,15}\b')
REGEX_URL = re.compile(
r"(https?:\/\/(... |
#!/usr/bin/python2.4
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Visual Studio user preferences file writer."""
import common
import os
import re
import socket # for gethostname
import xml.dom
import xm... |
"""
Given an input string, return all permutations of the string in an array.
Example 1:
* `string = 'ab'`
* `output = ['ab', 'ba']`
Example 2:
* `string = 'abc'`
* `output = ['abc', 'bac', 'bca', 'acb', 'cab', 'cba']`
Strings in Python are immutable,
which means that we cannot overwrite the characters of the S... |
from random import *
from khayyam import JalaliDatetime
from gtts import gTTS
import telebot
import qrcode
TOKEN = '<KEY>'
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=['start'])
def start_func(message):
bot.send_message(message.chat.id,'Welcome ' + (message.chat.first_name) + '!')
RANDOM_NUMBE... |
"""
Implement the distributions of transformations.
@author: <NAME> (y(dot)meng201011(at)gmail(dot)com)
"""
import numpy as np
from enum import Enum
import random
from models.image_processor import transform
from utils.data import set_channels_first, set_channels_last
def batch_sample_from_distribution(X, distributi... |
#! /usr/bin/python3
# FIRST TRY
import pprint
import re
from copy import deepcopy
# def parser(line, i, bracket):
# ts = []
# _char = line[i]
# le = None
# line_length = len(line) - 1
# # preprocessing
# _k = 0
# while not bracket and _k <= line_length:
# _xyz = line[_k]
# ... |
""" This module is used to call through to the Octopus Deploy APIs"""
# MIT License
#
# Copyright (c) 2018 Huddle
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, inclu... |
# ============================================================================
#
# Copyright (C) 2007-2016 Conceptive Engineering bvba.
# www.conceptive.be / <EMAIL>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
... |
from fractions import Fraction
from numpy import diff
def _bjorklund(subsequences):
"""
Distribute onsets as evenly as possible by modifying subsequences
"""
while True:
remainder = subsequences[-1]
distributed = []
while subsequences and subsequences[-1] == remainder:
... |
import numpy as np
#: Earth radius in km.
EARTH_RADIUS = 6371.0
#: Maximum elevation on Earth in km.
EARTH_ELEVATION = -8.848
def geodetic_distance(lons1, lats1, lons2, lats2, diameter=2 * EARTH_RADIUS):
"""
Calculate the geodetic distance between two points or two collections
of points.
Parameters... |
# coding: utf-8
# 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... |
#!/usr/bin/env python
#
# Goal: To check existence of files required for registration, for each subject.
#
# Steps:
# (1) Identifies list of subjects based on entries from config["csv_clinicalInfo"]
# (2) Checks if following files exist and are correct:
# (Please ensure below organisation / folder structure.)
# ... |
# Copyright (c) 2020 PaddlePaddle 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 required by appli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.