text
stringlengths
2
999k
from django import forms from django.contrib.auth import get_user_model from .hooks import hookset from .models import Message class UserModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return hookset.display_name(obj) class UserModelMultipleChoiceField(forms.ModelMultiple...
""" Waffle flags and switches for user authn. """ from edx_toggles.toggles import LegacyWaffleSwitch, LegacyWaffleSwitchNamespace _WAFFLE_NAMESPACE = 'user_authn' _WAFFLE_SWITCH_NAMESPACE = LegacyWaffleSwitchNamespace(name=_WAFFLE_NAMESPACE, log_prefix='UserAuthN: ') # .. toggle_name: user_authn.enable_login_using_...
from common.views import AuthenticatedListView, AuthorizedDetailView from django.db.models import Q from .models import Book class BookListView(AuthenticatedListView): model = Book context_object_name = 'book_list' template_name = 'books/book_list.html' class BookDetailView(AuthorizedDetailView): mo...
import torch import torch.nn as nn import torch.nn.utils import torch.nn.functional as F from torch.autograd import Variable import torch.nn.functional as F import numpy as np from torch.nn.init import xavier_normal_ from transformers import * import random from helpers import * class RelationExtractor(nn.Module): ...
# Generated by Django 2.0.2 on 2018-10-14 21:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('workplace', '0016_address_line_2_blank'), ] operations = [ migrations.AddField( model_name='historicalreservation', ...
from cbse_results_scraper.app import CBSEResultsScraper
import logging import sys from oslo_config import cfg import openstack logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') PROJECT_NAME = 'glance-share-image' CONF = cfg.CONF opts = [ cfg.BoolOpt('dry-run', help='Do not really do anything', default=False), ...
import torch import torch.nn as nn import torch.nn.functional as F import dgl from dgl.nn.pytorch import GraphConv, HeteroGraphConv from openhgnn.models.macro_layer.SemanticConv import SemanticAttention from ..models.layers import homo_layer_dict class HeteroGeneralLayer(nn.Module): '''General wrapper for layers'...
import cgi import datetime import jinja2 import json import os import pickle import redis import urllib import uwsgi import webapp2 JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True) # If your applicatio...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: types.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _mes...
import statsapi import pandas as pd # logging import logging logger = logging.getLogger('statsapi') logger.setLevel(logging.DEBUG) rootLogger = logging.getLogger() rootLogger.setLevel(logging.DEBUG) ch = logging.StreamHandler() formatter = logging.Formatter("%(asctime)s - %(levelname)8s - %(name)s(%(thread)s) - %(me...
from telegram import ReplyKeyboardRemove, Update from telegram.ext import CallbackContext, CallbackQueryHandler, ConversationHandler, Filters, MessageHandler from bot.settings import settings from bot.utils import get_log from bot.commands._states import ( CANCEL, START, ) from ._utils import require_user l...
# Overall complexity : O(n ** 2) def unique1(S): for j in range(len(S)): for k in range(j+1, len(S)): if S[j] == S[k]: return False return True # 1st iteration of outer loop causes n-1 iteraions of inner loop, # 2nd iteration of outer loop causes n-2 iteraions of inner lo...
import django_filters from django import forms from django.forms.models import BaseInlineFormSet, inlineformset_factory from . import models class CheckFilterForm(forms.Form): """Additional filter validations.""" def clean(self): cleaned_data = self.cleaned_data start = cleaned_data.get('st...
TrainingDays = 6 epochs = 50 avg_days = 5 std_days = 5 avg_window = 5 std_window = 5
import huggingface_hub base_model = "sentence-transformers/paraphrase-mpnet-base-v2" revision = "a867aefa094c578256b01667f75d841e5b7e0eaf" model_path = huggingface_hub.snapshot_download(base_model, revision) print(model_path)
#!/usr/bin/env python import os import argparse import pandas import numpy pandas.set_option('display.max_columns', None) # or 1000 pandas.set_option('display.max_rows', None) # or 1000 pandas.set_option('display.max_colwidth', 300) # or 199 def main(): parser = argparse.ArgumentParser(description="Process ...
# -*- coding: utf-8 -*- # @Author: yulidong # @Date: 2019-07-27 01:06:36 # @Last Modified by: yulidong # @Last Modified time: 2019-08-04 22:34:24 """ Training perception and control """ import argparse from os.path import join, exists from os import mkdir import matplotlib.pyplot as plt import torch im...
import time import numpy as np import tensorflow as tf from actor_critic import ActorCritic def pd_test(env_fn, policy, load_path): env = env_fn() actions = env.unwrapped.action_list env._seed(int(time.time())) obs = env.reset() obs = np.expand_dims(obs, axis=0) action_list = [] with ...
from typing import List, Tuple import pweave def _import_block(sparclur_path): if sparclur_path is None: sparclur_path_import = '' else: sparclur_path_import = """ module_path = os.path.abspath('%s') if module_path not in sys.path: sys.path.append(module_path) """ % sparclur_path impor...
# # 682. Baseball Game # # Q: https://leetcode.com/problems/baseball-game/ # A: https://leetcode.com/problems/baseball-game/discuss/107929/C%2B%2B-and-Javascript-solutions # from typing import List class Solution: def calPoints(self, ops: List[str]) -> int: s = [] for op in ops: if op ...
# Copyright (c) 2010 Advanced Micro Devices, Inc. # 2016 Georgia Institute of Technology # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain ...
import torch from sklearn.metrics import r2_score def my_metric(output, target): with torch.no_grad(): #pred = torch.argmax(output, dim=1) #assert pred.shape[0] == len(target) #correct = 0 #correct += torch.sum(output == target).item() output = output.cpu() target =...
""" Activations A collection of activations fn and modules with a common interface so that they can easily be swapped. All have an `inplace` arg even if not used. Hacked together by / Copyright 2020 Ross Wightman """ import torch from torch import nn as nn from torch.nn import functional as F def swish(x, inplace:...
# pylint: disable=no-self-use, unused-argument, redefined-outer-name import logging from pathlib import Path import pytest import drvn.installer._utils as utils @pytest.fixture(scope="class") def workspace(): workspace_path = _set_up_workspace() yield workspace_path _tear_down_workspace() class TestDr...
import os from django.contrib.auth.models import AbstractUser from django.db import models class Icon(models.Model): image = models.ImageField(upload_to="user-icons") def __str__(self) -> str: return os.path.basename(self.image.name) class User(AbstractUser): username = models.CharField( ...
import sys import onnx import numpy as np import tvm from tvm import te import tvm.relay as relay import logging if len(sys.argv) != 2: print("Usage: %s <onnx-file>" % sys.argv[0]) exit(1) onnx_model = onnx.load(sys.argv[1]) input_name = "input.1" x = np.random.randn(10, 3, 224, 224) # # mybert # input_na...
s = 'Python is Awesome' # without start and end print(s.startswith('Python')) # with start index print(s.startswith('Python', 3)) print(s.startswith('hon', 3)) # with start and end index print(s.startswith('is', 7, 10)) print(s.startswith('Python is', 0, 10)) print(s.startswith('Python is', 0, 5)) # prefix as tuple...
import pickle import tensorflow as tf import numpy as np import pandas as pd import yaml import json import os from importlib.machinery import SourceFileLoader def save_pickle_file(outlist, filepath): """Save to pickle file.""" with open(filepath, 'wb') as f: pickle.dump(outlist, f) ...
from pprint import pprint from collections import OrderedDict import json import networkx as nx import math def sigmoid(x): return 1 / (1 + math.exp(-x)) def calc_score(x, y): return x + (1 - x) * math.pow(y, (1/x)) LABELED_FILE = 'data/ORIG/label5000.txt' labeled_pairs = {} # build a simple KB for lin...
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: release-1.19 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import r...
"""Component to embed Aqualink devices.""" from __future__ import annotations import asyncio from functools import wraps import logging import aiohttp.client_exceptions from iaqualink.client import AqualinkClient from iaqualink.device import ( AqualinkBinarySensor, AqualinkDevice, AqualinkLight, Aqual...
# Copyright (c) Microsoft Corporation. # Licensed under the Apache License 2.0. import random import os import azext_aro.vendored_sdks.azure.mgmt.redhatopenshift.v2020_04_30.models as v2020_04_30 from azext_aro._aad import AADManager from azext_aro._rbac import assign_contributor_to_vnet, assign_contributor_to_route...
''' Classes for providing external input to a network. ''' from .binomial import * from .poissongroup import * from .poissoninput import * from .spikegeneratorgroup import * from .timedarray import *
from __future__ import division import numpy as np from scipy.constants import R from scipy.integrate import quad __all__ = [ 'temp_integral', 'time_integral', 'senumyang', 'timeint' ] def temp_integral(E, T): """Evaluates the temperature integral with numerical quadrature. Params ...
from setuptools import setup, find_packages setup( name="repeating_timer", version=0.2, author="Quin Marilyn", author_email="quin.marilyn05@gmail.com", description="Run a function over and over in a thread", long_description=open("readme.md", "r").read(), long_description_content_type="text/markdown", url="htt...
import sys from doctest import testmod import numpy import einops import einops.layers import einops.parsing from einops._backends import AbstractBackend from einops.einops import rearrange, parse_shape, _optimize_transformation from . import collect_test_backends __author__ = 'Alex Rogozhnikov' def test_doctests_...
import csv import re import sys filename = sys.argv[1] print('Parsing ' + filename + '...') csv_contents = open(r''+filename + '.csv', "wb") writer = csv.writer(csv_contents) file = open(filename, "r") file.readline() file.readline() file.readline() #Write data headers writer.writerow(['temperature', 'iterations', ...
# Copyright 2016 Confluent 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 writing, s...
import logging from pyvisdk.exceptions import InvalidArgumentError ######################################## # Automatically generated, do not edit. ######################################## log = logging.getLogger(__name__) def FileBackedVirtualDiskSpec(vim, *args, **kwargs): '''Specification used to create a fi...
from OpenGL.GLUT import glutPostRedisplay class MouseDelegate(object): def onMouse(self, *args): raise NotImplementedError class KeyDelegate(object): def onKey(self, *args): raise NotImplementedError g_events = [] def null_action(): return False class Event(object): def __init__(self, _type, msg=''...
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
#!/usr/bin/env python3 import requests def batch_request(node_ip, user_pass, requests_list): r = requests.post(node_ip, json=requests_list) return r def get_orderbook(node_ip, user_pass, base, rel): params = {'userpass': user_pass, 'method': 'orderbook', 'base': base, 'rel': r...
""" add language server support to the running jupyter notebook application """ import json import traitlets from .handlers import add_handlers from .manager import LanguageServerManager from .paths import normalized_uri def load_jupyter_server_extension(nbapp): """ create a LanguageServerManager and add handle...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # ----------------------------------------------------------------------------- # # P A G E B O T # # Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens # www.pagebot.io # Licensed under MIT conditions # # Supporting DrawBot, www.drawbot.com # ...
#!/usr/bin/env python3 # Copyright 2017 gRPC 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 ...
#!/usr/bin/python3 import enum import pickle from typing import Tuple import torch import torch.distributed.rpc as rpc import torch.testing._internal.dist_utils as dist_utils from torch import Tensor, nn from torch._jit_internal import Future from torch.distributed.nn import RemoteModule from torch.distributed.nn.api....
numero=5 print(numero==5) numero2=145 print(numero2==145) num1=input("Dame un numero") if int(num1)%2==0 : print("Es par") else: print("Es impar") nombre=input("Dame un nombre") if nombre=="Raul": print("Te quiero") elif nombre=="Juan": print("Te odio") else: print("Me da igual") if int(num1)%...
""" Set up defaults and read sentinel.conf """ import sys import os from dash_config import DashConfig default_sentinel_config = os.path.normpath( os.path.join(os.path.dirname(__file__), '../sentinel.conf') ) sentinel_config_file = os.environ.get('SENTINEL_CONFIG', default_sentinel_config) sentinel_cfg = DashC...
from pyb import UART # Setup the connection to your GPS here # This example uses UART 3 with RX on pin Y10 # Baudrate is 9600bps, with the standard 8 bits, 1 stop bit, no parity uart = UART(3, 9600) # Basic UART --> terminal printer, use to test your GPS module while True: if uart.any(): print(chr(uart.re...
import requests import pprint import requests import re import pandas as pd from bs4 import BeautifulSoup import time # encparam def get_encparam(code): url = f"https://navercomp.wisereport.co.kr/v2/company/c1010001.aspx?cmp_cd={code}" resp = requests.get(url) text = resp.text encparam = re.search("e...
import qrcode import numpy as np # data to encode data = "https://www.thepythoncode.com" # instantiate QRCode object qr = qrcode.QRCode(version=1, box_size=10, border=4) # add data to the QR code qr.add_data(data) # compile the data into a QR code array qr.make() # print the image shape print("The shape of...
import sys sys.path.append("src/") sys.path.append("script/") sys.path.append("script/pipe_line/") from data_manupulation import data_manupulation import pandas as pd import numpy as np import argparse from condition_manager import condition_manager from utils import safe_mkdir from utils import dict2r1df import os fro...
from ase import Atoms from gpaw import GPAW, PW """ A simple script to run an H2 calculation with GPAW using a PW basis and writing outputs to a specific file called out.txt """ # set up the H2 molecule h2 = Atoms('H2', [(0, 0, 0), (0, 0, 0.74)]) h2.center(vacuum=2.5) # define the calculator h2.calc = GPAW(xc='PBE',...
# Copyright 2014 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. PYTHON_VERSION_COMPATIBILITY = "PY3" DEPS = [ 'depot_tools/bot_update', 'depot_tools/gclient', 'depot_tools/git', 'depot_tools/tryserver', 'recipe...
from argparse import ArgumentParser from multiprocessing import Pool from termcolor import colored from rfc3987 import parse import itertools import requests import sys import re #import urllib3 #urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def print_banner(): print('''\nCloudScraper i...
from email.policy import default from .find_classrooms import find_classrooms from collections import defaultdict from pprint import pprint from logging import root import datetime import json MAX_TIME = 20 def _is_room_free(lessons, starting_time, ending_time): until = MAX_TIME if len(lessons) == 0: ...
""" ASGI config for videoProject project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Written by Lucas Sinclair. MIT Licensed. Contact at www.sinclair.bio """ # Built-in modules # # Internal modules # from fasta import FASTA from plumbing.databases import convert_to_sql from plumbing.databases.sqlite_database import SQLiteDatabase from plumbing.commo...
"""Provide the 'autogenerate' feature which can produce migration operations automatically.""" import contextlib from sqlalchemy import inspect from . import compare from . import render from .. import util from ..operations import ops def compare_metadata(context, metadata): """Compare a database schema to th...
# encoding: utf-8 from bs4 import BeautifulSoup import pytest import six from ckan.lib.helpers import url_for import ckan.tests.helpers as helpers import ckan.model as model from ckan.tests import factories @pytest.mark.usefixtures("clean_db", "with_request_context") class TestGroupController(object): def test_...
# -*- encoding: utf-8 -*- ''' Current module: pyrunner.ext.idleshell.TextEditDelegator Rough version history: v1.0 Original version to use ******************************************************************** @AUTHOR: Administrator-Bruce Luo(罗科峰) MAIL: lkf20031988@163.com RCS: rock4.c...
""" Django settings for supermarket_deals_29891 project. Generated by 'django-admin startproject' using Django 2.2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ "...
import heapq from typing import List class Solution: # Time complexity: O(n * log n) # Space complexity: O(1) def lastStoneWeight(self, stones: List[int]) -> int: for i in range(len(stones)): stones[i] = -stones[i] heapq.heapify(stones) while len(stones) > 1: ...
# -*- coding: utf-8 -*- import demjson class FlowLauncherAPI: @classmethod def change_query(cls, query, requery: bool = False): """ change flow launcher query """ print(demjson.encode({ "method": "Flow.Launcher.ChangeQuery", "parameters": [query, reque...
import argparse import json import os import sys from datetime import datetime from posixpath import join, exists from bgesdk.client import API from bgesdk.error import APIError from bgesdk.management.command import BaseCommand from bgesdk.management.constants import ( TAB_CHOICES, TITLE_NAME, API_TABLE, DEFAULT_...
from broker.providers.decoder import DecoderProvider from fvhiot.parsers.dlmbx import decode_hex class DlmbxDecoder(DecoderProvider): description = 'Decode Digital matter MBX payload' def decode_payload(self, hex_payload, port, **kwargs): data = decode_hex(hex_payload, port) # TODO: remove dl_...
import warnings from json import loads as json_loads from os import fsync from sys import exc_info from json_tricks.utils import is_py3, dict_default, gzip_compress, gzip_decompress, JsonTricksDeprecation from .utils import str_type, NoNumpyException # keep 'unused' imports from .comment import strip_comments # keep...
from openql import openql as ql import os import argparse def circuit(config_file, new_scheduler='yes', scheduler='ASAP', uniform_sched= 'no', sched_commute = 'yes', mapper='base', moves='no', maptiebreak='random', initial_placement='no', output_dir_name='test_output', optimize='no', measurement=True, log_level='LOG_W...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import codecs from setuptools import setup def read(fname): file_path = os.path.join(os.path.dirname(__file__), fname) return codecs.open(file_path, encoding='utf-8').read() setup( name='custom-interface', version='0.0.1', author='Rafael',...
import argparse import warnings import logging import os from imp import reload from google.protobuf import text_format from onnx import defs import tensorflow as tf from onnx_tf.common import get_output_node_names from onnx_tf.common.handler_helper import get_all_frontend_handlers from onnx_tf.common.handler_helper ...
# Copyright 2016-2022 Swiss National Supercomputing Centre (CSCS/ETH Zurich) # ReFrame Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: BSD-3-Clause import os import pytest import random import sys import time import reframe import reframe.core.fields as fields import refra...
#!/usr/bin/env python # -*- coding: utf-8 -*- # netpbmfile.py # Copyright (c) 2011-2013, Christoph Gohlke # Copyright (c) 2011-2013, The Regents of the University of California # Produced at the Laboratory for Fluorescence Dynamics. # All rights reserved. # # Redistribution and use in source and binary forms, with or ...
import numpy as np import vedo import vedo.colors as colors import vedo.utils as utils import vtk from vtk.util.numpy_support import numpy_to_vtk __doc__ = ("Submodule to work with common format images." + vedo.docs._defs) __all__ = ["Picture"] ################################################# def _get_img(obj, flip...
import copy import numpy as np import cv2 from sklearn.metrics import confusion_matrix def similarity(intersection, union): if union > 0: similarity = np.array(intersection/float(union)).item() elif intersection == 0 and union == 0: similarity = 1.0 else: similarity = 0.0 retur...
# coding=utf-8 from OTLMOW.OTLModel.BaseClasses.AttributeInfo import AttributeInfo from OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut from OTLMOW.OTLModel.Datatypes.BooleanField import BooleanField from OTLMOW.OTLModel.Datatypes.ComplexField import ComplexField from OTLMOW.OTLModel.Datatypes.DtcAdres imp...
import sys import pytest import yaml from prefect.run_configs import KubernetesRun def test_no_args(): config = KubernetesRun() assert config.job_template_path is None assert config.job_template is None assert config.image is None assert config.env is None assert config.cpu_limit is None ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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 from ... import _utilities, _tables from...
# -*- coding: utf-8 -*- import random, sys from psychopy import core, event, gui, visual, logging #window win = visual.Window(size = (1200,800), color = 'black', units = 'pix') win.setRecordFrameIntervals(True) win._refreshThreshold=1/85.0+0.004 #i've got 85Hz monitor and want to allow 4ms tolerance #set the log modul...
import random class Default(object): @staticmethod def default(**kwargs): return kwargs.get('value', None) @staticmethod def random(**kwargs): arr = kwargs.get('array', None) if arr is None: raise Exception('default: array is None') array_len = len(arr) ...
from .default import DefaultAttackEval from .invoke_limit_eval import InvokeLimitedAttackEval
#!/usr/bin/env python #=============================================================================== # Copyright 2020 Intel 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 # # ...
#!/usr/bin/env python2 # Copyright (c) 2015 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BilliecoinTestFramework from test_framework.util import * class Si...
import shutil from pathlib import Path from guessit import guessit class MediaWatcherMover(object): """ Where the magic happens. Either scan a given list of folders or lookup a specific file. """ def __init__(self, config, logger): self.config = config self.logger = logger d...
from common.core import AbstractPlugin from common.core import classReplacements from functools import reduce import timeit URLUtils = classReplacements.get_class('URLUtils') class TimeMePlugin(AbstractPlugin): def should_run(self): return isinstance(self.item_options.get('timeme'), dict) def chec...
from mkdocs.config import base, config_options, Config if __name__ == '__main__': config_scheme = ( ('doxygen-source', config_options.Type(str, default='')), ('api-path', config_options.Type(str, default='api')), ('target', config_options.Type(str, default='mkdocs')), ('full-doc', config_options.Type(bool, d...
#!/usr/bin/env python # Copyright 2016 Vijayaditya Peddinti. # 2016 Vimal Manohar # Apache 2.0. """ This script is similar to steps/nnet3/train_dnn.py but trains a raw neural network instead of an acoustic model. """ from __future__ import print_function import argparse import logging import pprint i...
""" WSGI config for nitjcompiler project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_...
""" After fine-tuning, all of our model weights, up until the last conv. layer, are contained within a single layer model object, making it difficult for Keras to load in these layer weights by name for any subsequent fine-tuning. Here, the model is loaded, the interior model is extracted, and its weights are saved. U...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="metarace", version="2.0.1", author="Nathan Fraser", author_email="ndf@metarace.com.au", url="https://github.com/ndf-zz/metarace", description="Cycle race abstractions", long_descri...
from . import empty from .utils import (identifiers, positive_integers, unique_objects)
import sklearn.metrics as sk_metrics import numpy as np from tqdm import tqdm from .average_meter import AverageMeter from .base_evaluator import BaseEvaluator from .sksurv.metrics import concordance_index_censored from sklearn.linear_model import LinearRegression class RegressionEvaluator(BaseEvaluator): """Clas...
# -*- coding: utf-8 -*- # from helpers import Phash def plot(): from matplotlib import pyplot as plt import numpy as np fig, ax = plt.subplots() with plt.style.context(("ggplot")): t = np.linspace(0, 2 * np.pi, 101) s = np.sin(t) ax.plot(t, s, "k-") ax.fill_between(t, ...
# -*- coding: utf-8 -*- import io import os import click from click.testing import CliRunner from pytest import fixture, mark from storyscript.App import App from storyscript.Cli import Cli from storyscript.Project import Project from storyscript.Version import version from storyscript.exceptions.CompilerError impor...
#: W601 if a.has_key("b"): print a #: W602 raise DummyError, "Message" #: W602 raise ValueError, "hello %s %s" % (1, 2) #: Okay raise type_, val, tb raise Exception, Exception("f"), t #: W603 if x <> 0: x = 0 #: W604 val = `1 + 2` #: W605 regex = '\.png$' #: W605 regex = ''' \.png$ ''' #: Okay regex = r'\.png$'...
from __future__ import unicode_literals from django_evolution.mutations import MoveToDjangoMigrations MUTATIONS = [ MoveToDjangoMigrations(), ]
"""base code""" import os import subprocess from pyngrok import ngrok try: COLAB_ENV = True from google.colab import drive # type:ignore except ImportError: COLAB_ENV = False PIPE = subprocess.PIPE EXTENSIONS = [ "ms-python.python", "jithurjacob.nbpreviewer", "njpwerner.autodocstring", ...
#Assigned Ports: 11995-11999 #WHATSAT to Hands import asyncio async def main(): reader, writer = await asyncio.open_connection('127.0.0.1', 11995) #writer.write("IAMAT kiwi.cs.ucla.edu +34.068930-118.445127 1520023934.918963997".encode()) writer.write("WHATSAT kiwi.cs.ucla.edu 10 5".encode()) writer.write_eof()...
import math from .core import get_catboost_bin_module, CatBoost, CatBoostError from .utils import _import_matplotlib _catboost = get_catboost_bin_module() FeatureExplanation = _catboost.FeatureExplanation def _check_model(model): if not isinstance(model, CatBoost): raise CatBoostError("Model should be...
# ----------------------------------------------------- # test_eep.py: Unit tests for eep.py. # ----------------------------------------------------- # Make sure we can import i2p import sys; sys.path += ['../../'] import traceback, sys from i2p import eep def verify_html(s): """Raise an error if s does not end w...