text stringlengths 3.07k 12.6k |
|---|
# Jump!
# by KidsCanCode 2014
# A Doodle Jump style game in Pygame
# For educational purposes only
import pygame
import sys
import random
# define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
LIGHTBLUE = (0, 155, 155)
BGCOLOR = LIGHTBLUE
# basic consta... |
"""A module containing classes that specify the components of a Factor Graph."""
from dataclasses import asdict, dataclass
from typing import Mapping, Tuple, Union
import jax
import jax.numpy as jnp
import numpy as np
from pgmax import utils
@dataclass(frozen=True, eq=False)
class Variable:
"""Base class for v... |
#!/usr/bin/python3
#
# Read 0.1° occurrence density counts from a CSV. Split by country/gbifRegion etc, and further
# by about/publishedBy, and futher by snapshot.
#
# For each of these create a matrix of 3600×1800 pixels, with the value equal to the density.
#
# Write this as a GeoTIFF.
#
import csv
import numpy as... |
"""
This file is used to define the model used for training. For example, in this template, we define ResNet50.
One may use existing models from torchvision as well (e.g., torchvision.models.resnet50)
"""
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
class BasicBlock(nn.Mo... |
import collections
import copy
import numpy
from typing import Dict, List
import warnings
from .constants import Messages
from .datatypes import Measurement
from .datatypes import TimeSeries
from .datatypes import Sensitivity
from .constants import Constants
SINGLE_ID = Constants.single_id
class OwnDic... |
"""Use Caesar shift to encode or decode your messages!"""
import os
import discord
from .utils.dataIO import fileIO, dataIO
from discord.ext import commands
from __main__ import send_cmd_help
from .utils import checks
__author__ = "FwiedWice"
__version__ = "V1.0.0"
class Code:
def __init__(self, chars):
... |
# -*- coding: utf-8 -*-
"""
identity.views
~~~~~~~~~~~~~~~~~~~
Default views of Flask-Identity
:author: solardiax <<EMAIL>>
:copyright: (c) 2020 by DreamEx Works.
:license: GPL-3.0, see LICENSE for more details.
"""
from flask import request, after_this_request, jsonify, url_for, Blueprin... |
"""Provide constants used by the myenergi API."""
from enum import Enum
DIRECTOR_URL = "https://director.myenergi.net"
API_HEADERS = {'user-agent': 'python/0.0.1'}
class MyEnergiEndpoint(Enum):
"""Supported endpoints for the Myenergi API."""
DEVICES = "cgi-jstatus-*"
HARVI = "cgi-jstatus-H"
ZAPPI =... |
import os
from dotenv import load_dotenv
from algosdk import mnemonic, error
from algofi_amm.v0.asset import Asset
from algofi_amm.utils import get_params, get_payment_txn, send_and_wait
from algofi_amm.v0.client import AlgofiAMMTestnetClient, AlgofiAMMMainnetClient
from algofi_amm.v0.config import PoolType, PoolStatu... |
import os
import simpy
import numpy as np
from pathlib import Path
from RideSimulator.Grid import Grid
from RideSimulator.Trip import Trip
lat_points, lon_points, trip_distances, trips_per_min = None, None, None, None
def read_data(directory="data", lon_file="lon_points", lat_file="lat_points", distance_file="trip_d... |
from flask import abort, flash, redirect, render_template, url_for, request, jsonify
from flask_login import current_user, login_required
from flask_rq import get_queue
from sqlalchemy import *
import datetime
from . import reserve
from .. import db
from ..models import *
from .forms import *
import sys
import json
de... |
import os
import copy
from parser import Parser
import json
from stanfordcorenlp import StanfordCoreNLP
import argparse
from tqdm import tqdm
def get_data_paths(ace2005_path):
test_files, dev_files, train_files = [], [], []
with open('./data_list.csv', mode='r') as csv_file:
rows = csv_file.readlines... |
from itertools import cycle
def permute(input_list, permutation_order):
if input_list is None:
raise ValueError('input_list cannot be None')
if permutation_order is None:
raise ValueError('permutation_order cannot be None')
if len(input_list) == len(permutation_order):
return [inpu... |
#!/usr/bin/env python3
from .tx import tx_copy
from .script.compiler import compile_script
from .script.operations import OP_CODESEPARATOR
from .binhex import b, x
from .hashing import double_sha
from .outpoint import serialize_outpoint
from .txoutput import serialize_txoutput, make_txoutput
from .script.serialization... |
import time
import json
import base64
from io import BytesIO
import torch.nn.functional as F
from torch.autograd import Variable
from flask import Flask, request, jsonify
from model.locator import Crowd_locator
import misc.transforms as own_transforms
from misc.utils import *
from collections import OrderedDict
impor... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from base.base_net import BaseNet
class Custom_LeNet(BaseNet):
def __init__(self, img_size, rep_dim=128):
super().__init__()
self.img_size = img_size
self.rep_dim = rep_dim
self.pool = nn.MaxPool2d(2, 2)
... |
import re
import math
import datetime as dt
from typing import List, Dict, Union, Optional, cast
from enum import Enum
from pandas import DataFrame, Timestamp, Timedelta, to_datetime
from jinja2 import Template, Environment, FileSystemLoader
from kipper.mailing_list import get_most_recent_mention_by_type
from kipper... |
import time
import pyautogui
from requests.exceptions import RequestException
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from ... |
# Copyright 2017 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
#
# https://aws.amazon.com/apache-2-0/
#
# or in the "license" file accompa... |
#
# Copyright (C) 2021 Google, Inc.
#
# 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, merge, publish, dist... |
import random
import time
import kahootDefs as kDefs
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
totalKahootBots = input('Kahoot Bots To Summon\n> ')
try:
totalKahootBots = int(totalKahootBots)
print()
except:
print('Error, Unsupported Input. Default (3)\... |
import flask
from flask import request, jsonify, render_template, flash, redirect, url_for, redirect, session, send_file, Markup
import datetime
import uuid
from werkzeug.security import check_password_hash
print("System online: " + str(datetime.datetime.now()))
# Config
from config.database import *
from config.mes... |
"""Helper functions/classes for unit tests."""
from __future__ import division
import copy
from contextlib import contextmanager
from queue import Queue
import socket
from threading import Thread
from time import sleep
from typing import Dict, Generator, List, Pattern, Union
from flashfocus.client import ClientMonito... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 15 23:39:04 2020
@author: zemeister
"""
# %%
# VARIABLES <==> O'ZGARUVCHILAR
"""
int, float, string, boolean
"""
# ism = qiymat # ozgaruvchi qiymatini belgilashimiz shart emas
int1 = 10 # int # 4byte
int2 = 11
string1 = "<NAME>" # string # ... |
#vim: ts=4:sw=4:et
import sys, csv
# MEP Fields
# ==========
# Time
# Calculated Engine Load (OBD) (%)
# Commanded Air/Fuel Ratio (OBD) (AFR)
# Engine coolant Temperature (C)
# Absolute Engine Load (OBD) (%)
# Air Conditioning Compressor Cycling Switch
# Air/Fuel S1 Current (OBD) (mA)
# Intake Air Temperature (OBD) (C... |
import typing
from types import MappingProxyType
from cryptography.hazmat.backends import default_backend as defb
from cryptography.hazmat.primitives import hashes as h
from ... import base, exc
HASHES = MappingProxyType(
{
"sha1": h.SHA1,
"sha224": h.SHA224,
"sha256": h.SHA256,
"... |
#!/usr/bin/env python
import rospy
import tf
import numpy as np
from math import *
from std_msgs.msg import Float64
from geometry_msgs.msg import TwistStamped, Twist
from geometry_msgs.msg import PoseStamped
from mavros_msgs.msg import PositionTarget, HomePosition
from nav_msgs.msg import Odometry
import utm
rospy.... |
import torch
import torchvision
import os.path as osp
from torch import nn
from .zhang_unet import ZhangUNet
from .hexunet import HexUNet
from spherical_distortion.util import distributed as distr_util
def build_model(cfg, num_classes):
distr_util.dprint('Initializing network')
in_ch = 4 if cfg.USE_DEPTH els... |
# -*- coding: utf-8 -*-
"""Contains methods for accessing KDV-elements used in regObs.
In regObs, xKDV elements contain the link between an element ID and its name and description.
This is also the contents of drop down choices in regObs. It is useful to have a local copy of
these tables.
"""
import requests
import o... |
# Standard Library
import argparse
import random
import time
import uuid
# Third Party
import mxnet as mx
import numpy as np
from mxnet import autograd, gluon, init
from mxnet.gluon import nn
from mxnet.gluon.data.vision import datasets, transforms
# First Party
from smdebug.mxnet import Hook, SaveConfig, modes
def... |
#!/usr/bin/env python3
from collections import namedtuple
import json
import re
from bs4 import BeautifulSoup
import requests
import js2py
# HTML parser
# See bs4 documentation: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser
# Default is "lxml"
HTML_PARSER = "lxml"
# Precompile regex
RE_... |
# Copyright (c) 2019 Viosoft 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
#!/usr/bin/python
from matplotlib import gridspec, cm, dates
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
## COLORS
# N colors distributed evenly across a color map
# see https://matplotlib.org/examples/color/colormaps_reference.html for color maps
def make_N_colors(cmap_name, N):
cm... |
# TODO(colin): fix these lint errors (http://pep8.readthedocs.io/en/release-1.7.x/intro.html#error-codes)
# pep8-disable:E128
"""Tests for compile_topic_icons.py"""
from __future__ import absolute_import
import cStringIO
import json
import os
import shutil
import PIL.Image
from shared.testutil import testsize
from ... |
import os
from datetime import datetime
from typing import Literal, Optional, Tuple
import aiohttp
import kopf
OPTA_DOMAIN = "api.app.runx.dev"
OPTA_TOKEN = os.environ.get("OPTA_TOKEN", "MISSING")
def is_valid_opta_pod(labels):
return labels.get("opta.dev/environment-name") is not None and labels.get("opta.dev... |
import inspect
from typing import Any, Callable, Dict, List, Iterator
from uuid import uuid4
__alive_filters__ = {}
__strategies_decorator__ = ["recursion", "iteration", "exception", "generation"]
__strategies_obj__ = ["recursion", "iteration", "exception"]
from outlier_detector.exceptions import OutlierException
fro... |
import os
import click
from shutil import copyfile
from mlapp.integrations.sm.cli_help import cli_sm_help
from mlapp.mlapp_cli.common.cli_utilities import create_directory, create_file
from mlapp.mlapp_cli.common.files import dockerignore_file, default_config_file
from mlapp.utils.general import get_project_root
from m... |
import datetime
import requests
from marshmallow import Schema, fields, post_load, ValidationError, validate
from flask import jsonify, abort, request, session, make_response, current_app
from src import db
from src.models import User, DgfObject, Comment
from src.api import bp
from src.api.auth import login_required
... |
import numpy as np
from scipy import sparse
# There are several functions in this file named after notation used in the following paper:
# http://mpc.zib.de/index.php/MPC/article/viewFile/40/20
# (Alternating direction augmented Lagrangian methods
# for semidefinite programming)
def plainA(constraints, dimension):
... |
import random
import copy
import sys
from Data_Structures.DLX import DLX
# helper function to check if a string can be converted to int
def valid_integer(string):
try:
int(string)
return True
except ValueError:
return False
# function to check sudoku rules for an input
def check_valid_... |
import re
# from abc import ABC
from pathlib import Path
import xml.etree.ElementTree as ET
import shutil
import yaml
from sklearn.model_selection import train_test_split
def mkdir(out_dir, overwrite=False):
out_dir = Path(out_dir)
is_exist = out_dir.exists()
if is_exist and overwrite:
shutil.rmtr... |
"""
A tracker class for controlling the Tello and some sample code for showing how
it works. you can test it using your webcam or a video file to make sure it works.
it computes a vector of the ball's direction from the center of the
screen. The axes are shown below (assuming a frame width and height of 600x400):
+y ... |
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
# *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. 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... |
from typing import Iterable, List, Tuple, Set, Dict, Union
from collections import defaultdict
from hashlib import blake2b
import numpy as np
from rdkit.Chem import AllChem
from rdkit.Chem.rdchem import Mol
from rdkit import RDLogger
RDLogger.DisableLog("rdApp.*")
class NoReactionError(Exception):
"""Raised when... |
# homeenvdash mini
import datetime
import time
from pathlib import Path
import board
import digitalio
import pandas
import plotly.express as px
from adafruit_bme280 import basic as adafruit_bme280
from dash import Dash, callback, html, dcc, Input, Output
import dash_bootstrap_components as dbc
# 保存するCSVファイル名
SENSOR_V... |
#!/usr/bin/env python3
# plot_violin.py
#
# Clean the temp from the loader and plot is as violin plots.
#
# Note that this script is fairly fragile since it assumes that all of the
# replicates have been completed, CSV files generated with the MATLAB script
# and annual data files are in the correct path.
import csv
... |
import argparse
import numpy as np
import sys
import os
import os.path as osp
import time
import random
import torch
import torch.nn as nn
from torch.utils import data
import torch.optim as optim
import torch.nn.functional as F
import utils.joint_transforms as joint_transforms
import utils.transforms as extended_tran... |
import abc
from copy import copy
from dataclasses import dataclass, field
import functools
import multiprocessing
from multiprocessing import synchronize
import threading
import time
import typing as tp
import stopit
from pypeln import utils as pypeln_utils
from . import utils
from .queue import IterableQueue, Outpu... |
#
# Collective Knowledge
#
# See CK LICENSE.txt for licensing details.
# See CK COPYRIGHT.txt for copyright details.
#
# Developer: <NAME>
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be updated by CK (temporal data)
ck=None # Will be updated by CK (initialized CK kernel)
# Loca... |
#Pyjsdl - Copyright (C) 2021 <NAME> <https://gatc.ca/>
#Released under the MIT License <https://opensource.org/licenses/MIT>
from pyjsdl.pyjsarray import BitSet
from pyjsdl.color import Color
# __pragma__ ('skip')
import sys
if sys.version_info < (3,):
from pyjsdl.util import _range as range
# __pragma__ ('noskip... |
#!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Check RPC argument consistency."""
from collections import defaultdict
import glob
import os
import re... |
#!/usr/bin/python
#
# Classes to store, read, and write annotations
#
import os
import json
from collections import namedtuple
# get current date and time
import datetime
import locale
# A point in a polygon
Point = namedtuple('Point', ['x', 'y'])
from abc import ABCMeta, abstractmethod
# Type of an object
class... |
from flask_restful import Resource, reqparse, marshal, fields
from models import db, Sensors, Schedules, RelayLogger, Monitoring
schedules_fields = {
'start_time': fields.String,
'stop_time': fields.String,
'relay': fields.String,
'id': fields.String
}
class SensorsAPI(Resource):
def __init__(se... |
from pyparsing import (Forward, Group, Keyword, Literal, Optional,
ParseException, ParserElement, QuotedString, Regex,
Suppress, Word, infixNotation, opAssoc, printables)
ParserElement.enablePackrat()
class UnaryOperation:
"""takes one operand,e.g. not"""
def __... |
import numpy as np
import os
import sys
import getopt
import code # For development: code.interact(local=locals())
import time
day_per_year = 365.0
class pft_bc_type:
def __init__(self):
# Initialize a dictionary of parameters for any pft
self.pft_bc_dic = {}
def DailyCFromUnitGPPAR(leaf_area... |
from jager_function.global_variable import *
import jager_function.data as data
from prettytable import PrettyTable
from jager_function.commands import clear_channel, get_random_item
async def get_table_r6(bot):
list_messages = await data.get_all_memory(bot)
auth = api.Auth(jager_email, jager_password)
l... |
# 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 agreed to in... |
from flask import Flask, redirect, url_for, render_template, request, session, flash
from datetime import timedelta
from json_interpreter import *
from api_caller import *
app = Flask(__name__)
app.secret_key = "supersecretkeyrighthere"
app.permanent_session_lifetime = timedelta(hours=1) # enable if session is perman... |
from remedian import remedian
from eg import eg
from random import random as r
import time
@eg
def _remedian1():
"basic usage"
z=remedian()
for i in range(1000):
z + i
if not i % 100:
print(i, z.median())
@eg
def _remedian2():
"test2: store increasing amount of numbers with different... |
"""Test main handlers"""
import time
from urllib.parse import quote, urlparse
import jwt
import pytest
from bs4 import BeautifulSoup
from binderhub import __version__ as binder_version
from .utils import async_requests
@pytest.mark.parametrize(
"old_url, new_url",
[
(
"/repo/binderhub-... |
from __future__ import print_function
import argparse
import os
import random
import chainer
import numpy as np
from chainer import training, Variable
from chainer.training import extensions
from dataset import H5pyDataset
from model import DCGAN_G, DCGAN_D, init_bn, init_conv
from sampler import sampler
from update... |
#!/usr/bin/env python3
"""
Clean up (making tar) a single simulation directory after successful cybershake submissions
"""
import os
import glob
import shutil
import tarfile
import argparse
from qcore import utils
SUBMISSION_DIR_NAME = "submission_temp"
SUBMISSION_TAR = "submission.tar"
SUBMISSION_FILES = [
"fli... |
from __future__ import absolute_import, division
import textwrap
from pprint import PrettyPrinter
from _plotly_utils.utils import *
# Pretty printing
def _list_repr_elided(v, threshold=200, edgeitems=3, indent=0, width=80):
"""
Return a string representation for of a list where list is elided if
it has ... |
#!/usr/bin/env python
# -*- coding: utf-8
# Copyright 2017-2019 The FIAAS 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
#
# U... |
# -*- coding: utf-8 -*-
#
# Copyright 2021 Nitrokey Developers
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
# http://opensource.org/licenses/MIT>, at your option. This file may not be
# copied, modified, or distribute... |
from typing import Dict, List, Sequence, TypeVar, Union
from turf.bbox import bbox
from turf.explode import explode
from turf.nearest_point import nearest_point
from turf.helpers import (
all_geometry_types,
FeatureCollection,
MultiPolygon,
Point,
Polygon,
)
from turf.helpers import feature, featu... |
"""Executing a bash script."""
# Copyright (c) 2017 <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,... |
from collections import defaultdict
from django.apps import apps
from django.db import models
from django.utils.translation import gettext_lazy as _
class ContentTypeManager(models.Manager):
use_in_migrations = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Cac... |
"""Installation file for ansys-mapdl-reader"""
import platform
import re
import subprocess
import struct
import os
import sys
from io import open as io_open
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext as _build_ext
try:
import numpy as np
except ImportError:
rais... |
import pickle
from werkzeug.contrib.cache import (BaseCache, NullCache, SimpleCache, MemcachedCache,
GAEMemcachedCache, FileSystemCache)
from ._compat import range_type
class SASLMemcachedCache(MemcachedCache):
def __init__(self, servers=None, default_timeout=300, key_prefix=N... |
from __future__ import absolute_import, unicode_literals
import collections
from django import forms
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core.exceptions import ValidationError
from django.forms.utils import ErrorList
from django.template.loader import render_to_string
# ... |
# Copyright (C) 2017,2019,2021 <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 writ... |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... |
import datetime
from flask import Flask
from flask import Response
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from peewee import *
# flask-peewee bindings
from flask_peewee.admin import Admin
from flask_... |
# -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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-... |
import numpy as np
import h5py
import time
import logging
from utilities import calculate_scalar, scale
import config
class DataGenerator(object):
def __init__(self, hdf5_path, batch_size, holdout_fold, seed=1234):
"""
Inputs:
hdf5_path: str
batch_size: int
holdout_... |
from pathlib import Path
import pytest
from pytest import approx
import themisasi as ta
from datetime import datetime, timedelta, date
#
R = Path(__file__).parent
datfn = R / "thg_l1_asf_gako_2011010617_v01.cdf"
cal1fn = R / "themis_skymap_gako_20110305-+_vXX.sav"
cal2fn = R / "thg_l2_asc_gako_19700101_v01.cdf"
asse... |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 3 13:06:11 2021
@author: Oliver
"""
import numpy as np
from scipy.integrate import quad
import matplotlib.pyplot as plt
"""__________________REFERENCE SOLUTION________________"""
"""DONE"""
def integrand(x):
return x**2+4*x-12
ans, err = quad(integra... |
import math
import torch
from torch import nn
from torch.utils.checkpoint import checkpoint
from utils import directory
from transformers import BertModel
import parameters as p
class ClinicalBertWrapper(nn.Module):
def __init__(self):
super(ClinicalBertWrapper, self).__init__()
config = BertModel.... |
"""
`django_basin3d.viewsets`
*************************
.. currentmodule:: django_basin3d.viewsets
:platform: Unix, Mac
:synopsis: BASIN-3D ViewSets
:module author: <NAME> <<EMAIL>>
:module author: <NAME> <<EMAIL>>
.. contents:: Contents
:local:
:backlinks: top
Below is the inheritance diagram for BASIN-3D ... |
from functools import partial
from .config import BOROUGHS
from .error import GeosupportError
from .function_info import (
FUNCTIONS, AUXILIARY_SEGMENT_LENGTH, WORK_AREA_LAYOUTS
)
def list_of(length, callback, v):
output = []
i = 0
# While the next entry isn't blank
while v[i:i+length].strip() != ... |
# freda (todo) :
import os, time, sys, math
import subprocess, shutil
from os.path import *
import numpy as np
from inspect import isclass
from pytz import timezone
from datetime import datetime
import inspect
import torch
def datestr():
pacific = timezone('US/Pacific')
now = datetime.now(pacific)
return... |
from typing import Callable, Optional
import torch
from torch import nn
import constants
from rl_multi_agent import MultiAgent
from rl_multi_agent.experiments.experiment import ExperimentConfig
from rl_multi_agent.furnmove_episode_samplers import FurnMoveEpisodeSampler
from rl_multi_agent.furnmove_episodes import Fur... |
import sys
# import libraries
import pandas as pd
import numpy as np
from sqlalchemy import create_engine
import pickle
import re
import nltk
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
from nltk.tokenize import word_tokenize
nltk.downloa... |
# -*- coding: utf-8 -*-
"""
@author:XuMing(<EMAIL>)
@description: sentiment classification
"""
# 本notebook参考了https://github.com/bentrevett/pytorch-sentiment-analysis
#
# 在这份notebook中,我们会用PyTorch模型和TorchText再来做情感分析(检测一段文字的情感是正面的还是负面的)。我们会使用[IMDb 数据集](http://ai.stanford.edu/~amaas/data/sentiment/),即电影评论。
#
# 模型从简单到复杂,我们... |
#!/usr/bin/env python3
import os
import re
import sys
# Another parser, whose aim has been lost, as many other ones :-)
demangle_cache = {}
def to_int(value):
"""Parse a string and convert it into a value"""
if not value:
return 0
if isinstance(value, int):
return value
mo = re.match... |
from transformers import BertModel
import torch
import math
import os
import torch.nn as nn
import torch.nn.functional as F
from modules.scale_mix import ScalarMix
class GELU(nn.Module):
def __init__(self):
super(GELU, self).__init__()
def forward(self, x):
return 0.5 * x * (1.0 + torch.tanh(... |
from pyb import UART
import time
import register
class NextionCommand:
class Page:
Buffer = str()
Backup = str()
Repeat = False
Headline = "page "
Zero = "0"
FfV16 = "FfV16"
FVM19 = "FVM19"
f19 = "f19"
f20 = "f20"
M16 = "M16"
D... |
import codecs
import os
import unicodedata
from common.dictionary import cedict_definition, add_dict_entry
hsk_word_level = {} # {"A" : 1, "ABC" : 1 }
hsk_char_level = {} # {"A" : 1, "B" : 1 , "C" : 1}
hsk_words = {} # {1 : set("A", "ABC"), ...}
hsk_chars = {}
hsk_words_2010 = {} # {1 : set("A", "ABC"), ...}
hsk_... |
'''gff2bed.py - convert from gff/gtf to bed
=========================================
:Tags: Genomics Intervals GFF BED Conversion
Purpose
--------
This script converts GFF or GTF formatted files to BED formatted
files.
Documentation
--------------
Users can select the field from the GTF file to be used in the nam... |
from __future__ import print_function, division
from glob import glob
from random import random
from numpy import array
from geojson import load
from shapely.geometry import Polygon
import numpy as np
import os
def average_precision(truth_fp, test_fp):
IoU = lambda p1, p2: p1.intersection(p2).area / p1.union(p2).a... |
#!/usr/bin/python
###
#
# Transformation functions for the pinhole camera model.
# Author: <NAME> <<EMAIL>>
#
###
import math
import numpy as np
from mmath import *
### Transform from world coordinates to pixel coordinates
# 3d world coordinates (in mm) -> 3d camera coordinates (in mm)
def wor... |
import ase.db
import warnings
import numpy
import matplotlib.pyplot as plt
from ase.data import covalent_radii
from scipy.stats import linregress
import os, os.path
from scipy.constants import pi, epsilon_0
db_file = "../../data/gpaw_data/c2db.db"
if not os.path.exists(db_file):
raise FileExistsError(("Please down... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Ansible module to manage PaloAltoNetworks Firewall
# (c) 2016, techbizdev <<EMAIL>>
#
# This file is part of Ansible
#
# Ansible 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 Softwar... |
# coding: utf8
# pragma: no cover
from __future__ import unicode_literals, division, absolute_import, print_function
import sys
from itertools import groupby
from functools import partial
import re
from purl import URL
from sqlalchemy.orm import joinedload
from sqlalchemy import Index
from clld.scripts.util import (
... |
# -*- coding: utf-8 -*-
"""Unit-tests for pyfun/utilities.py"""
from __future__ import division
import unittest
import numpy as np
from chebpy.core.settings import DefaultPrefs
from chebpy.core.chebtech import Chebtech2
from chebpy.core.algorithms import bary, clenshaw, coeffmult
from tests.utilities import (testf... |
"""
This module handles the command store interactive mode.
"""
import os
import subprocess
from typing import List, Optional
import remember.command_store_lib as command_store
from remember.command_store_lib import BColors, SqlCommandStore
from remember.sql_store import Command
class InteractiveCommandExecutor(obje... |
# -------------------------------------------------------------------------
# Copyright (c) 2018 AT&T Intellectual Property
# Copyright (C) 2020 Wipro Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtai... |
from typing import Iterable, List
import numpy as np
from ortools.algorithms.pywrapknapsack_solver import KnapsackSolver
import scipy.ndimage as nd
from loguru import logger
def f1_score(pred: np.ndarray, test: np.ndarray) -> float:
"""Compute F1-score on binary classification task.
:param pred: Predicted b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.