text stringlengths 957 885k |
|---|
<filename>SBDDDOTParser.py
import itertools
import os
import re
import shutil
import time
from datetime import datetime
import pexpect as pexpect
from networkx import DiGraph, disjoint_union, set_node_attributes, Graph
from pexpect import EOF, TIMEOUT
import config
from BDDParser import BDDParser
from Benchmark impor... |
<gh_stars>1-10
import librosa
import numpy as np
import matplotlib.pyplot as plt
import acoustid
import chromaprint
from fuzzywuzzy import fuzz
from rednoise_fun import rednoise, wave2stft, stft2power, get_mean_bandwidths, get_var_bandwidths, stft2wave, savewave, get_date, matchvol, get_pitch,get_pitch2, get_pitch_mea... |
import argparse
import getpass
import os
import sys
import crypto as Crypto
import keyfmt as KeyFormatting
import messaging as Messaging
import parsing as Parsing
'''Checking if encryption/decryption directories exist'''
frozen = getattr(sys,'frozen', None)
def check_decrypt_dir():
'''Checking ... |
import json
from model_mommy import mommy
from django.test.client import Client
from mock import *
from django.contrib.auth.models import User, Group
from survey.models.users import UserProfile
from survey.tests.base_test import BaseTest
from survey.forms.interviewer import InterviewerForm,\
USSDAccessForm, ODKAcce... |
"""
DB Model for Users table
and relevant junction tables
"""
import datetime
from flask_bcrypt import check_password_hash, generate_password_hash
from flask_jwt_extended import (create_access_token, create_refresh_token, decode_token, get_jwt_identity, get_raw_jwt,
jwt_refresh_token_re... |
<gh_stars>0
import unittest
from resappserver.graph import *
def dummy_edge(data):
pass
def increment_a_edge(data):
data['a'] += 1
def increment_b_edge(data):
data['b'] += 1
def decrement_a_edge(data):
data['a'] -= 1
def dummy_predicate(data):
return True
def nonzero_predicate(data):
retu... |
"""Collection of tests around log handling."""
import logging
import pytest
from cookiecutter.log import configure_logger
def create_log_records():
"""Test function, create log entries in expected stage of test."""
cookiecutter_logger = logging.getLogger('cookiecutter')
foo_logger = logging.getLogger('c... |
<filename>nova/scheduler/filters/vcpu_model_filter.py
#
# Copyright (c) 2013-2017 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
"""Scheduler filter "VCpuModelFilter", host_passes() returns True when the host
CPU model is newer than or equal to the guest CPU model as specified in the
instance type.... |
<gh_stars>1-10
#!/usr/bin/env python
#
# system imports
#
import cPickle, Image, glob
from scipy.misc import fromimage
import numpy as np
#
# user defined imports
#
from DefinitionsAndUtils import *
from ImageProcessing import thresholdNDArray
from GraphAndHistogramUtilities import timeToIdx, toProb... |
<filename>Train/eval_functions.py
import sys
import os
import keras
import tensorflow as tf
from keras.losses import kullback_leibler_divergence, categorical_crossentropy
from keras.models import load_model, Model
from argparse import ArgumentParser
from keras import backend as K
from Losses import * #needed!
from Met... |
<gh_stars>0
from os import getenv
from traceback import TracebackException
import discord
from discord.ext import commands
from mogirin import (
TicketAlreadyCollected,
TicketCollector,
TicketNumberNotFound,
find_ticket_number,
)
MOGIRI_CHANNEL_ID = int(getenv("MOGIRI_CHANNEL_ID"))
ATTENDEE_ROLE_ID =... |
#!/usr/bin/env python3
# Creates a csv file named se_corpus-yyyy-mm-dd.csv in working directory
import csv
import requests
import re
import sys
REPO_BASE_URL = "https://api.github.com/users/standardebooks/repos?per_page=100&page="
RAW_FILE_URL_STEM = "https://raw.github.com/"
PATH_TO_CONTENT_OPF = "/master/src/epub... |
<filename>mapie/classification.py
from __future__ import annotations
from typing import Optional, Union, Tuple, Iterable
import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import BaseCrossValidator
from sklearn.pip... |
#!/usr/bin/env
"""
CTD2NCheader.py
When run independantly, this program will allow the creation of a header text file for
all ctd casts in a directory. It relys mostly on the ship logs and not on the meta information
within the ctd files.
Using Anaconda packaged Python
"""
import os, datetime
#user defined
... |
<gh_stars>1-10
import time
import sys
import numpy as np
import scipy.stats
import librosa
from matplotlib import pyplot as plt
from tqdm.notebook import tqdm
import gc
from face_rhythm.util import helpers
def prepare_freqs(config_filepath):
config = helpers.load_config(config_filepath)
for session in confi... |
# from https://github.com/Moonrise55/Mbot/blob/f4e19df1df9fa4ef1a7730e63aa8009894aa304c/utils/paginator.py#L8
import discord
import asyncio
# set up pagination of results
class Pages:
"""
(self, ctx, *, solutions, weights=None, embedTemp, endflag=None)
solutions, weights: lists
"""
def __init... |
from __future__ import absolute_import, unicode_literals
import logging
from .common import *
# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Raises ImproperlyConfigured exception if DJANGO_... |
<gh_stars>0
from time import sleep
from bitcointx.core import coins_to_satoshi, satoshi_to_coins
from bitcointx.wallet import CCoinAddress as ExternalAddress
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from serial import SerialException
from bitcoin_coin_selection.selection_type... |
<filename>libs/envs/modules/sprites.py
import os
import pygame
class pusherSprite(pygame.sprite.Sprite):
def __init__(self, col, row, cfg, id):
pygame.sprite.Sprite.__init__(self)
if id == 1:
self.image_path = os.path.join(cfg.IMAGESDIR, 'player.png')
else:
self.ima... |
<filename>regression_tests/parsers/c_parser/exprs/expression.py
"""
A base class of all expressions.
"""
from abc import ABCMeta
from abc import abstractmethod
from clang import cindex
from regression_tests.parsers.c_parser.utils import first_child_node
from regression_tests.parsers.c_parser.utils import has_tok... |
from typing import *
import random
import enum
from enum import Enum
# Please see https://namu.wiki/w/%ED%99%94%ED%88%AC/%ED%8C%A8
# Following cards are defined in the same order as appeared in the above link
# For the rules and terminologies: please see https://www.pagat.com/fishing/gostop.html
# card constants
cl... |
<gh_stars>0
"""Gibbs sampling kernel"""
import collections
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability.python.mcmc.internal import util as mcmc_util
from tensorflow_probability.python.experimental import unnest
from tensorflow_probability.python.internal import prefer_static... |
# import onnx
# import torch.onnx
# from models import cropper
# from models import build_model
#
#
# device = torch.device('cpu')
#
#
# def static_onnx_converter(model_path, onnx_file):
# # load checkpoint
# # checkpoint = torch.load(model_path, map_location=device)
# # # config for model architecture
# ... |
<filename>jftools/ipynbimport.py
# coding: utf-8
## Importing IPython Notebooks as Modules
# It is a common problem that people want to import code from IPython Notebooks.
# This is made difficult by the fact that Notebooks are not plain Python files,
# and thus cannot be imported by the regular Python machinery.
#
# ... |
#!/usr/bin/env python
#coding:utf-8
from django.db import models
# Create your models here
from django.contrib.auth.models import AbstractUser
###---------- users------------------###
'''
class userType(models.Model):
name = models.CharField('用户类型',max_length=200,default='user')
create_time = models.DateTi... |
<filename>certgen.py
#!/usr/bin/env python3
# MIT License
# Copyright (c) 2020 <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 ... |
<gh_stars>0
import requests
import json
from retriever_library import fixtures_stats_csv_generator
import time
import pandas as pd
import numpy as np
in_file_path = "serieA-fixtures/all-fixtures-"
for season in range(2010,2020):
fixtures_stats_csv_generator(input_file_json=in_file_path + str(season) + ".json",
... |
<gh_stars>0
"""Jumper_model.py: Create the agent of model of the one legged jumping tensegrity robot and provide an easy interface to be used with RL algorithms"""
__author__ = "<NAME>"
__credits__ = ["<NAME>", "<NAME>", "Prof. <NAME>", "<NAME>"]
__version__ = "1.0.0"
__email__ = "<EMAIL> / <EMAIL>"
__status__ = "Devel... |
<filename>lagom/core/policies/base_gaussian_policy.py
from .base_policy import BasePolicy
import torch
from torch.distributions import Normal
class BaseGaussianPolicy(BasePolicy):
"""
Base class of Gaussian policy (independent) for continuous action space.
Action can be sampled from a Norma... |
import regex as re
import requests
from time import sleep
from digi.xbee.devices import XBeeDevice, RemoteXBeeDevice, XBee64BitAddress
from digi.xbee.exception import TimeoutException
from datetime import datetime
class MSG_TYPES:
ACKN = 0
SYNC = 1
UPDA = 2
SYNACK = 3
class UpdatePayload:
lightI... |
<filename>testcases/basic_func_tests/tc_008_storage_check.py<gh_stars>0
import sys
import os
from robot.libraries.BuiltIn import BuiltIn
from robot.api import logger
from decorators_for_robot_functionalities import *
from test_constants import *
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '../... |
try:
from auth import auth
except:
with open("auth.py","w") as a:
a.write("auth = ('<username>','<password>')")
print("Add login info to auth.py!")
quit()
import trainInfomation
import pygame
import datetime
import threading
import time
def firstLetterVowelDetect(string):
... |
"""
flask_security.datastore
~~~~~~~~~~~~~~~~~~~~~~~~
This module contains an user datastore classes.
:copyright: (c) 2012 by <NAME>.
:copyright: (c) 2019-2020 by <NAME> (jwag).
:license: MIT, see LICENSE for more details.
"""
import json
import uuid
from .utils import config_value
class Da... |
# std
from __future__ import annotations
from abc import ABC, abstractclassmethod
from typing import Callable, Text, Tuple, Union, List, Optional
# 3rd party
import numpy as np
from math import degrees, atan2
from blessed import Terminal
# local
from .exceptions import (BorderOutOfBounds, CellOutOfBounds, ElementNotP... |
<reponame>xmrsmoothx/Python-world-gen
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 25 21:04:55 2021
@author: Bri
"""
import random
from src_tools import *
from src_events import *
import string
class Magic:
def __init__(self,c):
self.tt = "magic"
# Choose a type of magic spell. T... |
import time
import attr
import pytest
from saltfactories.daemons.container import Container
from saltfactories.utils import random_string
from saltfactories.utils.ports import get_unused_localhost_port
docker = pytest.importorskip("docker")
@attr.s(kw_only=True, slots=True)
class MySQLImage:
name = attr.ib()
... |
<reponame>sjklipp/automol
""" vector functions
"""
import numbers
import numpy
import transformations as tf
def unit_norm(xyz):
""" Normalize a vector (xyz) to 1.0.
:param xyz: vector
:type xyz: tuple, list, or numpy nd.array
:rtype: float
"""
norm = numpy.linalg.norm(xyz)
uxy... |
import pymongo
import requests
import json
'''
This module polls Mate3 solar controller devices
'''
def targetVoltage(
batt: float
) -> tuple[float, float]:
'''
Caclulates target voltage, accounts for night mode
'''
if batt <= 18:
target = 12.65
low = 11.89
elif 1... |
# pyOCD debugger
# Copyright (c) 2020 Arm Limited
# SPDX-License-Identifier: Apache-2.0
#
# 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
#
# ... |
from bearlibterminal import terminal
from loguru import logger
from utilities import configUtilities, armourManagement, common, externalfileutilities, input_handlers, itemsHelp, \
jewelleryManagement, spellHelp
from static.data import constants
def display_spell_info_popup(menu_selection, gameworld, player_entity... |
# Copyright 2021 Sony Semiconductors Israel, 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 b... |
<reponame>marcelo-bn/Banco-de-Dados
from flask import Flask, flash, redirect, url_for, request, session, render_template, jsonify
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import Navbar, View, Subgroup
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func, des... |
# Copyright 2017 <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 required by applicable law or agreed to in writ... |
"""Bin data for ocean water mass analysis."""
import sys
script_dir = sys.path[0]
import os
import pdb
import argparse
import logging
import numpy as np
import iris
import iris.coord_categorisation
from iris.experimental.equalise_cubes import equalise_attributes
import cmdline_provenance as cmdprov
from statsmodels.s... |
<gh_stars>1-10
# Copyright (c) 2019 American Express Travel Related Services Company, 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
#
# Unl... |
"""
Show the errors in physics tendencies as a function of precision. Show both
relative and absolute errors (haven't decided on mean_diff or rms_diff). For
relative errors, this can be directly compared to the machine epsilon so add
this line also. Also print out errors as a function of machine epsilon to be
shown in ... |
<reponame>piwaniuk/critic
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2017 the Critic contributors, Opera Software ASA
#
# 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://... |
#!/usr/bin/env python3
#
# Copyright (c) 2019, The OpenThread Authors.
# 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
# ... |
from pydub import AudioSegment
import os
import numpy as np
from tqdm import tqdm
from joblib import Parallel, delayed
from python_speech_features import logfbank
import scipy.io.wavfile as wav
import argparse
parser = argparse.ArgumentParser(description='Librispeech preprocess.')
parser.add_argument('root', metav... |
import calendar
from decimal import Decimal
import datetime
import logging
from django.db.models import F, Q
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from corehq.apps.accounting.utils import ensure_domain_instance
from dimagi.utils.decorators.memoized impor... |
<reponame>CourtHans/401-ops-challenges
#!/usr/bin/env python3
# Script: 401 Op Challenge Day 7
# Author: <NAME>
# Date of latest revision: 10/13/20
# Purpose: Menu & execution for encryption (directory, file, string)
# Import libraries
from cryptography.fernet imp... |
#import time
#
#tic = time.time()
#
import rhinoscriptsyntax as rs
import json
import random
import itertools
import copy
from compas.datastructures import Mesh
from compas.datastructures import Network
from compas.utilities import geometric_key
from compas.topology import depth_first_tree
... |
<reponame>archieio/tele2-prof
import math
import re
import time
from colorama import Fore
from app.api import Tele2Api
def input_lots(data_left, display_name, min_amount, max_multiplier,
price_multiplier, lot_type):
lots_to_sell = []
index = 1
while data_left >= min_amount:
user_i... |
<gh_stars>0
################################################################################
# Exploratory Data Analysis
# columns list(sample)
# sample.drop('is_listened', 1)
# yes = sample.loc[sample['is_listened'] == 1]
# no = sample.loc[sample['is_listened'] == 0]
###################################################... |
from vnc_api_test import *
from tcutils.config.vnc_introspect_utils import *
from tcutils.config.svc_mon_introspect_utils import SvcMonInspect
from tcutils.control.cn_introspect_utils import *
from tcutils.agent.vna_introspect_utils import *
from tcutils.collector.opserver_introspect_utils import *
from tcutils.collect... |
<reponame>GillesArcas/Advent_of_Code<gh_stars>0
import re
from collections import defaultdict
EXAMPLES1 = (
('22-exemple0.txt', 39),
('22-exemple1.txt', 590784),
('22-exemple1-short.txt', 590784),
('22-exemple2.txt', 474140),
)
EXAMPLES2 = (
('22-exemple0.txt', 39),
('22-exemple1... |
<gh_stars>10-100
from design_bench.datasets.discrete_dataset import DiscreteDataset
from design_bench.disk_resource import DiskResource, SERVER_URL
"""
chembl-AC50-CHEMBL1741322/chembl-x-0.npy 1190
chembl-ALB-CHEMBL3885882/chembl-x-0.npy 1096
chembl-ALP-CHEMBL3885882/chembl-x-0.npy 1096
chembl-ALT-CHEMBL3885882/chem... |
import openpnm as op
import numpy as np
class BoundaryTest:
def setup_class(self):
self.net = op.network.Cubic(shape=[3, 3, 3])
self.net.add_boundary_pores()
Ps_int = self.net.pores(labels=['top_boundary', 'bottom_boundary'],
mode='not')
Ps_boun = s... |
from assembler import Assembler
from assembler import Form
from fem import DofHandler
from fem import QuadFE
from fem import Basis
from function import Nodal
from gmrf import Covariance
from gmrf import GaussianField
from mesh import Mesh1D
from plot import Plot
from solver import LinearSystem
# Built-in modules
impor... |
<reponame>victoriarspada/woudc-data-registry<gh_stars>1-10
# =================================================================
#
# Terms and Conditions of Use
#
# Unless otherwise noted, computer program source code of this
# distribution # is covered under Crown Copyright, Government of
# Canada, and is distributed un... |
from __future__ import print_function, division, absolute_import
from copy import copy
import numpy as np
import scipy.optimize
import regreg.api as rr
from regreg.tests.decorators import set_seed_for_test
@set_seed_for_test()
def test_l1prox():
'''
this test verifies that the l1 prox in lagrange form can ... |
<reponame>justincredble/Circulation
# -*- coding:utf-8 -*-
from app import db
from app.models import User, Library, Log, Permission
from flask import render_template, url_for, flash, redirect, request, abort
from flask.ext.login import login_required, current_user
from . import library
from .forms import SearchForm, Ed... |
<filename>objects.py
import random
import skills
class Object:
''' color = 1...6 '''
def __init__(self, y, x, c, maxyx):
self.name = c
self.maxyx = maxyx # y,x
self.x = x
self.y = y
self.direction = [0, 0]
self.blocking = False
self.char = c
self... |
# Copyright 2019 The TensorFlow 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 applica... |
<gh_stars>1-10
try:
import tkinter as tk
from tkinter.filedialog import askopenfilename
class Window(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("scicast")
self.path = tk.StringVar()
self.cell_path = tk.StringVar()
self.g... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'HaiFeng'
__mtime__ = '2016/9/17'
"""
from generate.ctp_data_type import *
import os
class Generate:
def __init__(self, dir):
self.ctp_dir = dir
def run(self):
"""主函数"""
fcpp = open(os.path.join(os.path.abspath(self.ctp_dir), 'Thos... |
<reponame>bb13135811/Introducing_Python
# 檔案輸入/輸出
# fileobj = open(filename, mode)
#(open()回傳的檔案物件) (指示檔案類型)
# 使用write()來編寫文字檔案
poem = '''There was a young lady named Bright,
Whose speed was far faster than light;
She started one day
In a relative way,
And returned on the previous night.'''
len(poem)
fout = open... |
"""Performance visualization class"""
import os
from dataclasses import dataclass, field
from typing import Dict, List
import pandas as pd
import seaborn as sns
import scikit_posthocs as sp
from matplotlib.backends.backend_pdf import PdfPages
from matplotlib import pyplot
import matplotlib.pylab as plt
from tqdm import... |
<reponame>mjclarke94/aiida-lammps
from hashlib import md5
from io import StringIO
from aiida.orm import Data
from aiida.plugins.entry_point import get_entry_point_names, load_entry_point
class EmpiricalPotential(Data):
"""
Store the empirical potential data
"""
entry_name = "lammps.potentials"
p... |
"""
Class for the calculation of photon-ALPs conversion in galaxy clusters
History:
- 06/01/12: created
- 07/18/13: cleaned up
"""
__version__=0.02
__author__="<NAME> // <EMAIL>"
import numpy as np
from math import ceil
import eblstud.ebl.tau_from_model as Tau
from eblstud.misc.constants import *
import logging
impo... |
<reponame>ak3ra/torchgeo<filename>tests/test_train.py
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import re
import subprocess
import sys
from pathlib import Path
import pytest
pytestmark = pytest.mark.slow
def test_required_args() -> None:
args = [sys... |
<gh_stars>0
#!/usr/bin/env python3
import json
import os, os.path
import subprocess
import tempfile
from FFprobe_output import *
def blackdetect(src, vfilter='blackdetect=d=1/15:picture_black_ratio_th=0.85:pixel_black_th=0.1', encoding='UTF-8'):
command = ['ffprobe', '-v', 'error', '-of', 'flat', '-show_entries', \... |
<filename>galaxy2galaxy/layers/flows.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
import tensorflow_probability as tfp
import tensorflow_hub as hub
import numpy as np
import collections
import functools
from tensorflow_proba... |
<filename>demo_gl.py
import caffe
import argparse
import os
import cv2
import numpy as np
import time
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import utils
parser = argparse.ArgumentParser()
parse... |
<reponame>WshgL/pyuavcan
# Copyright (c) 2021 UAVCAN Consortium
# This software is distributed under the terms of the MIT License.
# Author: <NAME> <<EMAIL>>
from __future__ import annotations
import sys
import random
from typing import Optional, Union
from pathlib import Path
import logging
import pyuavcan
from ._nod... |
<reponame>crisbodnar/cwn
import torch
import pytest
import itertools
from data.dummy_complexes import (get_house_complex, get_square_complex, get_pyramid_complex,
get_square_dot_complex, get_kite_complex)
from data.complex import ComplexBatch
from data.dummy_complexes import get_testing_complex_list
from data.dat... |
from django.contrib import admin
from .models import (
Brand,
Certificate,
Company,
Corporation,
Country,
Product,
ProductPriceInStore,
Rating,
Store,
MainProductCategory,
ProductCategory,
SubProductCategory,
BigTen,
)
class MainProductCategoryAdmin(admin.ModelAdmi... |
import datetime
import os
import sqlite3
import uuid
from flask import Flask, request, render_template, jsonify
from flask_cors import CORS
from util import Tweet, tweet_factory, datetime_format, send_data
app = Flask(__name__)
CORS(app)
# Configuration
initial_tweets_count = 100
tablet_servers = ['http://localhost:... |
<filename>tapas/utils/hybridqa_utils.py
# coding=utf-8
# Copyright 2019 The Google AI Language Team 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/lice... |
<filename>hard/312-burst-balloons.py
'''
戳气球
有 n 个气球,编号为0 到 n - 1,每个气球上都标有一个数字,这些数字存在数组 nums 中。
现在要求你戳破所有的气球。戳破第 i 个气球,你可以获得 nums[i - 1] * nums[i] * nums[i + 1] 枚硬币。
这里的 i - 1 和 i + 1 代表和 i 相邻的两个气球的序号。如果 i - 1或 i + 1 超出了数组的边界,那么就当它是一个数字为 1 的气球。
求所能获得硬币的最大数量。
示例 1:
输入:nums = [3,1,5,8]
输出:167
解释:
nums = [3,1,5,8] -->... |
'''
Created on 14 feb 2016
@author: ghedinip
'''
from __future__ import absolute_import, division, print_function, unicode_literals
__all__ = ["DateTime", "Date", "Time", "Boolean", "Period", "Address", "Params", "ALL"]
import json
import dateutil.parser
import re
from datetime import time, date, datetime
try:
... |
import torch
import torch.nn.functional as F
from ...utils import box_utils, loss_utils
from .point_head_template import PointHeadTemplate
class VoxelSegHead(PointHeadTemplate):
"""
A simple point-based segmentation head, which are used for PV-RCNN keypoint segmentaion.
Reference Paper: https://arxiv.org... |
""" Tests for datamegh.util.object util. """
import pytest
from datamegh.util.object import (
linearize,
delinearize,
merge,
dict_to_list,
list_to_dict,
without_attr,
with_only,
)
def test_dict_to_list_returns_list_when_valid_arguments_is_dict():
"""
Test a dictionary converted to... |
<filename>mmdet/models/backbones/ssd_vgg.py
import warnings
import torch.nn as nn
from mmcv.cnn import VGG
from mmcv.runner import BaseModule
from ..builder import BACKBONES
from ..necks import ssd_neck
@BACKBONES.register_module()
class SSDVGG(VGG, BaseModule):
"""VGG Backbone network for single-shot-detection... |
<gh_stars>0
# 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, merge, publish,... |
from django.db import models
from django.contrib.auth.models import Group, User
from django.utils import timezone
# Create your models here.
# 個別のビデオを表現するクラス
class Media(models.Model):
name = models.TextField() # ビデオの名前
order = models.IntegerField(default= 0) # 表示順位
vid = models.CharFi... |
#!/usr/bin/python3
import praw
from colorama import Fore
import topSecretInfo
# Variables. Don't forget to change before publishing!!!
clientID = topSecretInfo.clientID
clientSecret = topSecretInfo.clientSecret
username = topSecretInfo.username
password = topSecretInfo.password
subName = topSecretInfo.subName
userAgen... |
<reponame>kjarkko/Heron<filename>application/chats/views.py
from application import app, db, login_required
from application.chats.models import Chat
from application.chats.forms import ChatForm, AddUserForm
from application.chatusers.models import ChatUser
from application.messages.models import Message
from applicati... |
<filename>histogram.py<gh_stars>1-10
import copy
import rangelist
from globalconstants import VERTLINE
from plainenglish import Labels
from indexclass import Index
from generalutilities import abridge, show_list
import nformat
from indexutilities import index_reduce
from rangelist import split_up_range
lab... |
# pylint: disable=C0330,W1401
from urllib.parse import urljoin
from requests import Request
import requests
from .server import Settings
from .utils import purge_document
class Client:
"""Allows to easily perform read and write operations against a remote
RESTful web service which is powered by the Eve_ RES... |
level3_labels = {
"n/a": "No data",
111: "Cultivated Terrestrial Vegetation",
112: "Natural Terrestrial Vegetation",
123: "Cultivated Aquatic Vegetation",
124: "Natural Aquatic Vegetation",
215: "Artificial Surface",
216: "Natural Bare Surface",
220: "Water"
}
level4_labels = {
"n/a... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial, reduce
from models.attention import PAM_Module, CAM_Module
impor... |
import torch
import numpy as np
import torch.nn.functional as F
SMOOTH = 1e-6
classes = ["car", "motorcycle", "bus", "bicycle", "truck", "pedestrian", "other_vehicle", "animal", "emergency_vehicle"]
def iou_pytorch(pred, target, n_classes = 9, print_table = True):
"""
PyTorch IoU implementation
... |
<filename>mockredis/tests/test_script.py
from unittest import TestCase, skipUnless
from hashlib import sha1
from mockredis.exceptions import RedisError
from mockredis.redis import MockRedis
from mockredis.tests.test_constants import (
LIST1, LIST2,
VAL1, VAL2, VAL3, VAL4,
LPOP_SCRIPT
)
def has_lua():
... |
<reponame>deltapsifi/Ganitansh
import random
from math import *
import time
import sympy as sym
from PIL import Image
import pyttsx3 # have to install this and pypiwin32
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from sympy import *
from IPython.display import display, Math, Latex
f... |
# -*- coding: utf-8 -*-
"""Untitled4.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1jf4Y6d9_9hy0bUGm0I-xlzdKOJO0YVag
"""
import numpy as np
import matplotlib.pyplot as plt
def perpendicular(x_val, y_val):
"""
This function gives the inter... |
"""Tests for Groebner bases. """
from sympy.polys.distributedpolys import (
sdp_from_dict,
)
from sympy.polys.groebnertools import (
sdp_groebner, sig, sig_key, sig_cmp,
lbp, lbp_cmp, lbp_key, critical_pair,
cp_cmp, cp_key, is_rewritable_or_comparable,
Sign, Polyn, Num, s_poly, f5_reduce,
_bas... |
import sys
import math
import random
import xml.etree.ElementTree as ET
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import treelib
from pandas.core.frame import DataFrame
from scipy.spatial import distance_matrix
from sklearn.manifold import MDS
from treelib.node import Node
from treelib.tre... |
<filename>view_commands.py
import sublime
import sublime_plugin
import os
import serial_constants
class SerialMonitorWriteCommand(sublime_plugin.TextCommand):
"""
Writes text (or a file) to the serial output view the command is run on
"""
def run(self, edit, **args):
"""
Ru... |
<reponame>levilucio/SyVOLT<gh_stars>1-10
from core.himesis import Himesis, HimesisPreConditionPatternLHS
import uuid
class HUnitDaughter2Woman_CompleteLHS(HimesisPreConditionPatternLHS):
def __init__(self):
"""
Creates the himesis graph representing the AToM3 model HUnitDaughter2Woman_CompleteLHS
"""
# Flag t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.