text
stringlengths
3.07k
22.1k
import time from tkinter import * from selenium import common from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException from selenium.webdriver import DesiredCapabilities from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC fro...
"""Functions for computing sparsifiers of graphs.""" import math import networkx as nx from networkx.utils import not_implemented_for, py_random_state __all__ = ['spanner'] @py_random_state(3) @not_implemented_for('directed') @not_implemented_for('multigraph') def spanner(G, stretch, weight=None, seed=None): """...
import numpy as np # linear algebra import torch from torch.autograd import Variable from skimage import io from torch.nn import functional as F import skimage.morphology as mph import sys import os import pickle output = sys.argv[1] md = sys.argv[2] # Set random seeds cuda = torch.cuda.is_available() device = torch...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # Email: <EMAIL> # DateTime: 2018-11-22 16:24:44 __author__ = "chenwx" import random import time import socket import base64 import requests import json import hashlib import threading import os import logging import yaml from pathlib import Path streams = [None, None] link_...
#!/usr/bin/python import argparse import numpy as np import arrow import PIL from tensorrtserver.api import ServerStatusContext, ProtocolType, InferContext import tensorrtserver.api.model_config_pb2 as model_config from bistiming import Stopwatch from eyewitness.detection_utils import DetectionResult from eyewitness.im...
""" Tests for tab functions (just primitive). """ import json from cms.djangoapps.contentstore.tests.utils import CourseTestCase from cms.djangoapps.contentstore.utils import reverse_course_url from cms.djangoapps.contentstore.views import tabs from xmodule.modulestore.django import modulestore from xmodule.modulest...
# -*- coding: utf-8 -*- import magento import json from .api import Core from trytond.model import ModelView, fields from trytond.pool import PoolMeta, Pool from trytond.transaction import Transaction from trytond.pyson import PYSONEncoder, Eval from trytond.wizard import ( Wizard, StateView, Button, StateAction, ...
#! /usr/bin/env python3 """ import sys sys.path.remove('/opt/ros/melodic/lib/python2.7/dist-packages') """ import abc import cv2 import yaml import pickle import time import rospy import VisionExtensions import numpy as np import os from collections import deque from cv_bridge import CvBridge from sensor_msgs.msg impo...
# pylint: disable=missing-docstring # pylint: disable=protected-access import unittest import numpy as np import tensorflow as tf import tf_encrypted as tfe from tf_encrypted.protocol.pond import PondMaskedTensor from tf_encrypted.protocol.pond import PondPublicTensor from tf_encrypted.tensor import fixed100 from tf...
# -*- coding: utf-8 -*- # Copyright 2015 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 requir...
from selenium import webdriver from selenium.webdriver.support.ui import Select import time import requests import base64 import json from PIL import Image # Customization js = json.load(open("config.json",mode="r",encoding="utf-8")) print(js) username = js["username"] password = js["password"] mode = js[...
import argparse import hashlib import itertools import multiprocessing import os import subprocess import sys import time import traceback from collections import OrderedDict, deque def count_lines(f): i = 0 if not os.path.exists(f): return i with open(f) as r: for _ in r: i +...
""" units.py This module defins the various units supported by the `quantities` package. The 'UNITS' global holds all the defined units. This is a dictionary mapping the kind of units (ie, "weight", "length", etc) to a list of the known units of that kind. For each unit, the list item will be a ...
from typing import Optional, List, Dict, Any, Callable, Iterable from enum import Enum import tempfile import srsly import warnings from pathlib import Path from ...errors import Warnings, Errors from ...language import Language from ...scorer import Scorer from ...tokens import Doc from ...training import validate_ex...
"""Additional utility functions.""" import tensorflow as tf import tensorflow_probability as tfp from tensorflow.contrib import gan as tfgan from typing import List def assert_is_image(data): data.shape.assert_has_rank(4) data.shape[1:].assert_is_fully_defined() def image_grid_summary(incoming, grid_size=4,...
# Copyright (c) 2014, Fundacion Dr. <NAME> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and...
import numpy, os, time import numpy, os, time import h5py from .log import log_and_raise_error, log_warning, log_info, log_debug from .h5writer import AbstractH5Writer, logger mpi4py = None MPI = None from distutils.version import StrictVersion def _import_mpi4py(): global MPI global mpi4py try: ...
# Copyright 2010 Fluidinfo 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, ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. from typing import Any, Dict, Optional, Union import augly.image.utils as imutils import numpy as np from PIL import Image """ This file contains 'intensity' functions for each of our augmentations. Intensity functions give a float representa...
from numba import jit import time from project_code.misc_functions import sub_matrix, combine_sets from project_code.classes import Result_IF, Result_IF_generators import numpy as np import logging def compute_IFs(branches, setI, setT, setR, LODF, PATL, PTDF): t0 = time.clock() results = [] sizeI = len(...
import os import glob import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages') import cv2 from keras.preprocessing import image from keras.models import Model from keras.optimizers import Adam from keras.callbacks import EarlyStop...
#!/usr/bin/env python # imports import copy # class class character_race: def __init__(self, name, size, speed, weaponsprof, armorprof, toolsprof, raceprof, language, stre, stremod, stremodified, stremodifier, dex, dexmod, dexmodified, dexmodifier, con, conmod...
#!/usr/bin/env python import argparse, sys import math import os import sys from openbabel import openbabel as ob from meeko import obutils #def index_before_deleting_hydrogens(index, del_atoms): # """0-indexed""" # offset = 0 # for d in del_atoms: # if d <= (index + offset): # offset += 1 ...
import time from ..save import * from ..seed import * from .base_cb import * import shutil import json class AutoResumeCb(Callback): """auto save and resume for all callbacks and model, with multiple checkpoints Args: n_save_cycle: -1 to ignore, default: n_ep_itr resume: using save mode, witho...
""" Cycle Species """ #***************************************************************************** # Copyright (C) 2008 <NAME> <<EMAIL>>, # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundatio...
# pylint: disable=missing-function-docstring, missing-module-docstring/ from pyccel.decorators import types, pure __all__ = [ 'homogenous_tuple_int', 'homogenous_tuple_bool', 'homogenous_tuple_float', 'homogenous_tuple_string', 'homogenous_tuple_math', 'inhomogenous_tupl...
"""This module defines functionality related to generating the CSV output file.""" import math from enum import Enum from pathlib import Path from typing import Union from tester.core import cfg from tester.core.log import console_log from tester.core.metrics import SequenceMetrics def csv_validate_config(): fo...
# -*- coding: utf-8 -*- """ Created on Thu Nov 05 16:44:30 2015 @brief: Common functions @author: okada $Id: subcode.py 199 2017-07-10 04:27:19Z aokada $ $Rev: 199 $ """ # ファイルがあるかチェック def path_check(path, config): if config != None and config.has_option("MAIN", "path_check"): if config.getboolean(...
import hashlib import urllib from collections import defaultdict from datetime import datetime from babel.dates import format_date from babel.dates import format_datetime from babel.dates import format_time from babel.numbers import format_currency from pyramid.decorator import reify from pyramid.i18n import get_local...
import os import random import time import numpy as np import torch import torch.optim as optim from torch.utils.data import DataLoader from crossView import PVA_model, Argoverse from opt import get_args import tqdm from datetime import datetime from utils import mean_IU, mean_precision import wandb def readlines(f...
import torch import torch.nn as nn from torch.nn import init import torch.nn.functional as F import scipy.io as sio import numpy as np import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Define Basic reconstruct block class BasicBlock(torc...
import json from ..utils import verify_str _default_icon = "icon.gif" class ServiceArgError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class ServiceArg(tuple): """ServiceArg(name_str, type_str) -> ServiceArg This class is us...
import nibabel as nib from tqdm import tqdm from scipy.ndimage import label, generate_binary_structure from pathlib import Path import json import numpy as np from ivadomed import postprocessing as imed_postpro from typing import List def run_uncertainty(image_folder): """Compute uncertainty from model prediction...
# Copyright (c) 2019 UAVCAN Consortium # This software is distributed under the terms of the MIT License. # Author: <NAME> <<EMAIL>> from __future__ import annotations import abc import typing import warnings import dataclasses import pyuavcan.util from ._transfer import Transfer, TransferFrom from ._timestamp import ...
from .lib.symengine_wrapper import Symbol, Basic from itertools import combinations, permutations, product, product as cartes import re as _re import string import sys _range = _re.compile('([0-9]*:[0-9]+|[a-zA-Z]?:[a-zA-Z])') def symbols(names, **args): """ Transform strings into instances of :class:`Symbo...
# Copyright 2016 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0 # # or in the "license" file accompa...
#!/user/bin/python3 # -*- coding: utf-8 -*- # compatible with Python 3.4.3 __author__="<NAME>" __copyright__ = "Copyright 2015, The NRA project " __credits__ = ["<NAME>"] __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Testing" import time import bs4 import xlsx...
import numpy as np import math import random import problem def initial(p): return problem.Solution.from_j2k(p, np.arange(p.n)) def shuffle(p): j2k = list(range(p.n)) random.shuffle(j2k) return problem.Solution.from_j2k(p, j2k) def shuffle_best(p, k = 1000): best = None for i in range(k): ...
# Copyright 2019 - The Android Open Source Project # # 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 ...
# -*- coding: utf-8 -*- # # Copyright (c) 2009 by xt <<EMAIL>> # Borrowed parts from pagetitle.py by xororand # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, o...
""" Preprocess dataset/review.json """ from collections import defaultdict, namedtuple, Counter import json from tqdm import tqdm import itertools import pandas as pd import numpy as np from pycorenlp import StanfordCoreNLP import random import time import multiprocessing as mp N_CPU = 12 random.seed(0) REVIEW_FILE...
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import torch from typing import Any from torchvision.models.resnet import BasicBlock, Bottleneck, conv1x1 from torchvision....
# Copyright (c) 2015-present, Facebook, Inc. Modified By <NAME>, <NAME>. # All rights reserved. import warnings warnings.filterwarnings('ignore') from models_balance_matrix.gem import GeneralizedMeanPoolingP import sys import os import pdb import argparse import time from collections import OrderedDict, defaultdict fr...
#!/usr/bin/python # # Copyright 2020 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 ag...
""" So here I try to build the StockSimPlay.py for-loop into a function, which should give outputs like gym.openai.com environments does. Then implement the greedy epsilon deep Q learning from RLtutMLadventuries.py to see if anything interesting happens. We still use 1 stock for 1 year. """ #Import packages: import n...
from matplotlib.pyplot import box import numpy as np from loguru import logger from survos2.entity.anno.masks import ellipsoidal_mask _MaskSize = 4 # 4 bits per history label _MaskCopy = 15 # 0000 1111 _MaskPrev = 240 # 1111 0000 def get_order(viewer_order): viewer_order_str = "".join(map(str, view...
#!/usr/bin/env python ################################################################################ # # # UTILITY---TABULATES AN IDEAL GAS LAW FOR STELLAR_CLLAPSE READER # # ...
import unittest import gc import sys from functools import partial from greenlet import greenlet from greenlet import getcurrent try: from contextvars import Context from contextvars import ContextVar from contextvars import copy_context except ImportError: Context = ContextVar = copy_context = None...
# -*- coding: utf-8 -*- from copy import deepcopy from typing import ClassVar from mrsimulator.method import Method from mrsimulator.method import SpectralDimension from mrsimulator.utils.error import ImmutableEventError from mrsimulator.utils.error import NamedMethodError from pydantic import Field from pydantic impo...
"""Checkpoint utilities.""" import os import six import tensorflow as tf import numpy as np from opennmt.utils.vocab import Vocab from opennmt.utils.misc import count_lines def _get_vocabulary_mapping(current_vocab_path, new_vocab_path, mode): """Maps vocabulary new indices to old ones. -1 means that the entry i...
import os import sys from typing import List import click from ruamel.yaml import YAML from great_expectations import DataContext from great_expectations.checkpoint.types.checkpoint_result import CheckpointResult from great_expectations.cli import toolkit from great_expectations.cli.pretty_printing import cli_message...
''' ==================================================================== Copyright (c) 2016 <NAME>. All rights reserved. This software is licensed as described in the file LICENSE.txt, which you should have received as part of this distribution. ==================================================================...
""" Functionality for generating Python code used to evaluate Lagrange polynomials. """ import numpy as np from polynomials_on_simplices.algebra.multiindex import generate_all from polynomials_on_simplices.generic_tools.code_generation_utils import CodeWriter from polynomials_on_simplices.generic_tools.str_utils impo...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache 2.0 License. import socket import ssl import struct import select import contextlib import json import time import os import subprocess import tempfile import base64 import requests import urllib.parse from requests_http_signature i...
from flask import Flask, request, jsonify import xmlrpc.client as xc from tinydb import TinyDB, Query import uuid db = TinyDB('snort_db.json') snort_query = Query() super_server = xc.ServerProxy('http://127.0.0.1:9001/RPC2') app = Flask(__name__) def is_running(service): state = super_server.su...
import boto3 import logging import os import paramiko import time import uuid from datetime import datetime logging.getLogger("paramiko").setLevel(logging.INFO) AMI_ID = "ami-bb1901d8" BUILD_ID = "t2.micro" # KEY_PAIR_NAME = "Default" AVAILABILITY_ZONE = "ap-southeast-2" # Sydney, AU PEM_FILE = "/Users/hugh/.aws/l...
import numpy as np import cv2 import dlib import copy import sys import argparse import math from scipy import interpolate from imutils import face_utils from Code.FeatureTrack import videoDetector from Code.DoubleTrack import videoDoubleDetector def videoToImage(fname,tarname): cap = cv2.VideoCapture(fname) ...
import numpy as np import math import scipy.integrate import time import datetime import threading class Propeller(): def __init__(self, prop_dia, prop_pitch, thrust_unit='N'): self.dia = prop_dia self.pitch = prop_pitch self.thrust_unit = thrust_unit self.speed = 0 #RPM sel...
from typing import Dict, Tuple, Optional, List, Protocol from util import utils class Mappings: """ A comprehensive representation of a set of mappings This encapsulates two distinct concepts: - A source set, which represents raw metadata about the classes, methods, and fields in a class - A set...
#!/usr/bin/env python # # ----------------------------------------------------------------------------- # Copyright (c) 2016 Indiana University # # This file is part of AEGeAn (http://github.com/BrendelGroup/AEGeAn) and is # licensed under the ISC license: see LICENSE. # ----------------------------------------------...
#!/usr/bin/env python """ This application is given the device instance number of a device and its address read the object list, then for each object, read the object name. """ from collections import deque import pandas as pd import numpy as np from sqlalchemy import create_engine import logging from bacpypes.debug...
# Author: <NAME> # Copyright <NAME> 2019 Released under the MIT license # Created on 2018-12-28 __updated__ = "2019-02-23" __version__ = "0.1" from server.apphandler.apphandler import App, AppInstance from paho.mqtt.client import Client as _MqttClient from paho.mqtt.client import connack_string from .subscriptions i...
from enum import Enum from typing import List, Optional DATA_SIZE = 4 class Register(str, Enum): # stores value 0; cannot be modified zero = "$zero" # used for system calls and procedure return values v0 = "$v0" v1 = "$v1" # used for passing arguments to procedures a0 = "$a0" a1 = "$a...
# Copyright (c) 2013, <NAME> and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe import frappe, erpnext from erpnext import get_company_currency, get_default_company from erpnext.accounts.report.utils import get_currency, convert_to_presentation_curr...
from SmallPackage.SmallOS import SmallOS from SmallPackage.SmallTask import SmallTask from SmallPackage.Kernel import Unix from shells import baseShell import pdb, select,sys def update(self): #Retrieve the system state from the datastore. data, status = self.state.getState('update','system') if statu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Imports from __future__ import print_function import sys import os import argparse if sys.version_info.major == 2: from StringIO import StringIO as stringio else: from io import StringIO as stringio from lxml import etree import process_includes # # Globals...
from math import floor from cassandra.query import SimpleStatement from cassandra.concurrent import execute_concurrent from gsrest.db.cassandra import get_session from gsrest.model.entities import Entity, EntityIncomingRelations, \ EntityOutgoingRelations, EntityAddress from gsrest.model.tags import Tag from gsres...
from flask import Flask, jsonify import tweepy import pandas as pd import re import numpy as np import string import pickle import json from keras.models import load_model from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras import layers from keras.models im...
### Figure 4 E and S5D: NN graph and supplementary - Obenhaus et al. import sys, os import os.path import pandas as pd import datajoint as dj import cmasher as cmr from pathlib import Path # Make plots pretty import seaborn as sns sns.set(style='white') # Prevent bug in figure export as pdf: import matplotlib as...
""" This module defines a simple query language for searching Data Cube indexes Literal Values -------------- - Strings - Numerics - Dates - Vague Dates ie. Specify a year, meaning a range covering the entire year Comparisons ----------- - Equals eg. field=<value> - Between eg. - low < field < h...
from pyspark.sql import SparkSession standardNullReplacementMapPerStandardType = { "string": "-", "date": "1900-01-01", "timestamp": "1900-01-01 00:00:00", "double": "0.0", "int": "0", "boolean": "False", } def getSpark(): return SparkSession.builder.appName("Test").getOrCrea...
import typing from guillotina import configure from guillotina.auth.users import SystemUser from guillotina.component import get_utility from guillotina.db.orm.interfaces import IBaseObject from guillotina.interfaces import Allow from guillotina.interfaces import AllowSingle from guillotina.interfaces import Deny from...
# The MIT License (MIT) # # Copyright (c) 2016 <NAME> # # 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, including without limitation the rights # to use, copy, modify, me...
import argparse import json import os import subprocess from os import makedirs, remove from os.path import abspath, join, exists, dirname from jinja2 import Template CMDS = ["list", "add", "del", "gen"] VHOSTM_CONFIG = ".vhostm.conf" DEFAULT_NGINX_TEMPLATE = """ upstream {{domain}} { server {{address}}:{{port}...
# Patchwise Road Segmentation for Aerial Images with CNN # <NAME>, <NAME>, <NAME> # Group 5: Google Maps Team # Department of Computer Science, ETH Zurich, Switzerland # Computational Intelligence Lab # This script is used for postprocessing (model ensemble, CRFs) import os import shutil import argparse import glob i...
import ast import typing import _ast from .types import types from .core import visitor @visitor def expr(self, tree: _ast.Expr): return self.node( tmp='expr', parts={'value': self.visit(tree.value)} ) def set_var(self, var, _type='any'): """ returns True if var is new, otherwise retu...
from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.urls import reverse_lazy from django.core.mail import send_mail, EmailMultiAlternatives from rest_framework import status from rest_framework.v...
# -*- coding: utf-8 -*- """ Created on Fri Dec 18 22:59:59 2020 @author: Christian In this model, the nonlinear material propreties for a siesmic damper are chosen to match a set of test data. The test data is stored in two files The example makes use of OpenSeesPy for the damper analysis, and the hysteresis packag...
#!/usr/bin/env python # Copyright (c) 2018, DIANA-HEP # 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 the above copyright notice, this # list ...
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
import os import subprocess from configparser import ConfigParser from shutil import rmtree from textwrap import dedent from .utils import absolute_path, yes_or_no class TropsEnv: def __init__(self, args, other_args): if other_args: msg = f"""\ Unsupported argments: { ', '....
import os import time import numpy as np from collections import OrderedDict import sys import decimal import sys import result_utils as ut from result_conf import * import shutil def initialize_result(allsub,tvector): result_matrix = [] overall = len(allsub) + 1 #each element has several model: trap...
################################### # Doorbell with face recognition # ################################### # # Author: <NAME> # https://www.github.com/Erientes/ ######################### # MODULES # ######################### from src._button import Button from src._led import LED import json import RPi...
import threading import time import requests import json from datetime import datetime from bson.objectid import ObjectId from facebook import Facebook, FacebookError from app.processes import BaseCollector from app.models import DB # TODO - Daemon shutdown issues class CollectionListener(object): """ Class...
import logging from abc import abstractmethod from pathlib import Path from typing import List, Union, Callable import torch.utils.data.dataloader from torch.utils.data.dataset import Subset, ConcatDataset from flair.data import ( Sentence, Token, Tokenizer, FlairDataset ) from flair.tokenization impo...
#================================================================================================= # Function: CreateCloudWatchAlarmEC2Instances # Purpose: Lambda funtion used to provision cloudwatch alarms for EC2 instance CPU Utilization # Author : <NAME> (<EMAIL>) # This function has the ability to provision CloudW...
# this script creates a single header + source file combination out of the DuckDB sources import os, re, sys, pickle amal_dir = os.path.join('src', 'amalgamation') header_file = os.path.join(amal_dir, "duckdb.hpp") source_file = os.path.join(amal_dir, "duckdb.cpp") src_dir = 'src' include_dir = os.path.join('src', 'in...
from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth import logout from django.contrib.auth.models import User import time from datetime import timedelta import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import matplotlib.dates as mdate impo...
import asyncio import copy import json import re import textwrap from itertools import zip_longest from shutil import get_terminal_size import colorama from colorama import Style, Fore, Back from lxml import html from dualisbot import webnav from dualisbot.config import get_config_val # Result extraction and printin...
import os import numpy as np import keras from keras.models import Sequential from keras.layers import Dense from keras.layers import Flatten from keras.layers import LSTM from keras.layers.embeddings import Embedding from keras.layers import Bidirectional from keras.preprocessing import sequence from keras.layers impo...
# Monster game from sys import exit, stdout, argv from random import random import math DIFFICULTY = 0.2 HIGHSCORES_FILE = 'monsters_highscores.txt' NUM_HIGHSCORES = 10 # THE CORE GAME LOGIC yard = [0, 0, 0, 4] score = 0 level = 1 # creates a new monster def new_monster(): return math.floor(random() * (score + D...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ FBNet model basic building blocks """ import logging import numbers import torch.nn as nn from torch.nn.quantized.modules import FloatFunctional import mobile_cv.arch.layers.misc as layers_misc import mobile_cv.arch.ut...
from typing import Union, Sequence import astro_dynamo.model import astro_dynamo.snap import astro_dynamo.targets import matplotlib.figure import matplotlib.pyplot as plt import numpy as np import torch from matplotlib.axes import SubplotBase from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable from mp...
import math import unittest # Given a string and a non-negative int n, return a larger string # that is n copies of the original string. # Example: string_times("hey", 3) should return "heyheyhey" def string_times(string, n): return string * n # Write a function which returns True if a year is a leap year. # A ...
#!/usr/bin/env python # # Copyright 2018 GoPro Inc. # # 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...
import requests from urllib.parse import urlencode import base64 import json import datetime import os from textblob import Blobber from textblob.sentiments import NaiveBayesAnalyzer import re class API(object): """ Create an API object that will handle connection, search request, and response. We use OAu...
# Copyright 2015 Observable Networks # # 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 ...
# Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Copyright 2021 AI Redefined Inc. <<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 required by applicable law or agreed ...
from colossalai.context.parallel_mode import ParallelMode import torch import torch.nn as nn import inspect from .layers import Embedding, BertLayer, BertDualHead, PreProcessor, VocabEmbedding from .layers.init_method import init_normal, output_init_normal from colossalai.core import global_context as gpc from colossal...