text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. 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/LICENS... |
import os
import json
import numpy as np
from ... import logger
from .train.train import ModelTrainer
from .ensemble.ensemble import ModelEnsembler
from ..setup.setup import Session
from ..compare.compare import Comparison
class Score(object):
def __init__(self, score=None, meta=None):
self.score = score... |
#!/usr/bin/env python-real
# -*- coding: utf-8 -*-
"""
Run script: multivariate functional shape data analysis (MFSDA).
Author: Chao Huang (chaohuang.stat@gmail.com)
Last update: 2017-08-14
"""
import sys,os
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)),os.path.join('Resources','Libraries')... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Base class for RPC testing
import logging
import optparse
import os
import sys
import shutil
import te... |
"""
"""
from __future__ import division
import numpy as np
from scipy.special import digamma
from .counts import get_counts
def entropy_0(data, length=1):
"""
Estimate the entropy of length `length` subsequences in `data`.
Parameters
----------
data : iterable
An iterable of samples.
... |
import logging
from flask import request, Response
from flask_restplus import Resource, reqparse
from structlog import wrap_logger
from frontstage_api import auth, surveys_api
from frontstage_api.controllers import case_controller, collection_instrument_controller
logger = wrap_logger(logging.getLogger(__name__))
... |
# merge.py
def merge_increasing(lst: list, L: list, R: list):
"""
`merege_increasing` merges two sorted sub-lists into their original list input in
increasing order. It takes three lists, original, right-hand sub-list, and
left-hand sub-list. The function returns None.
"""
i = j = k = 0 #ini... |
from django.db import models
from zazi.core.utils import generate_id
from zazi.core.base import BaseModel
class MpesaLoanProduct(BaseModel):
mpesa_api_account = models.ForeignKey(
'mpesa.MpesaAPIAccount',
models.CASCADE,
related_name='loan_products')
loan_product = models.ForeignKe... |
# Copyright (c) 2012 - 2015 EMC Corporation.
# 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
#
# Unle... |
#!/usr/bin/python
import os, sys
from jinja2 import Template
if len(sys.argv) != 4:
print("Allowed paremeters are 3, the source, destination and environment variable prefix parameters and you are passing %d args" % (len(sys.argv) - 1))
sys.exit(1)
template_file = sys.argv[1]
config_file = sys.argv[2]
env_pre... |
import os
import shlex
import subprocess
import sys
import pytest
pytestmark = pytest.mark.formatting
FILE_ENDING = os.path.join("tests", "test_formatting.py")
POSIX = sys.platform != "win32"
@pytest.mark.skipif(sys.version_info < (3, 6), reason="Black requires Python 3.6+")
def test_source_code_black_formatting(... |
# Copyright 2015 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... |
# FARIS : Factual Arrangement and Representation of Ideas in Sentences
# FAris : Farabi & Aristotle
# Faris : A knight (in Arabic)
# --------------------------------------------------------------------
# Copyright (C) 2015, 2021 Abdelkrime Aries (kariminfo0@gmail.com)
#
# Autors:
# - 2021 Abdelkrime Aries (kar... |
"""
This encapsulates the logic for displaying filters in the Django admin.
Filters are specified in models with the "list_filter" option.
Each filter subclass knows how to display a filter for a field that passes a
certain test -- e.g. being a DateField or ForeignKey.
"""
import datetime
from django.contrib.admin.op... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Very simple script to replace a template with another one.
It also converts the old MediaWiki boilerplate format to the new template format.
Syntax: python template.py [-remove] [xml[:filename]] oldTemplate [newTemplate]
Specify the template on the command line. The prog... |
from unittest import TestCase
from unittest.case import skipIf
import os.path as osp
from datumaro.components.dataset import Dataset
from datumaro.components.extractor_tfds import (
TFDS_EXTRACTOR_AVAILABLE, make_tfds_extractor,
)
from datumaro.util.test_utils import TestDir, compare_datasets, mock_tfds_data
from ... |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
"""
This file defines classes for job handlers specific for Fedmsg events
"""
import logging
from datetime import datetime
from typing import Optional
from ogr.abstract import GitProject
from packit.config import (
JobConfig,
JobT... |
from django.db import models
from django.contrib import admin
class SingletonModel(models.Model):
"""This is the abstract ancestor for all models
that should have a strictly single record in the database"""
class Meta:
abstract = True
def save(self, *args, **kwargs):
self.__class__.o... |
from urllib.parse import urljoin
import requests
from ansible.plugins.action import ActionBase
NS = "lilatomic_api_http"
class ConnectionInfo(object):
def __init__(self, base):
self.base = base
class ActionModule(ActionBase):
def run(self, tmp=None, task_vars=None):
super().run(tmp=tmp, task_vars=task_vars)... |
# stdlib
import ast
from collections import OrderedDict
import copy
import os
from pathlib import Path
import sys
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
# third party
import torch
# syft absolute
import syft ... |
"""Determines if a triangle is equilater based on three input side lengths."""
def main() -> None:
"""Takes user input of three side lengths and displays if triangle is equilateral or not."""
length_one: int = int(input('Enter the first side: '))
length_two: int = int(input('Enter the second side: '))... |
import math
# sed 's/,/|/g' 2QZ_6QZ_pubcat.txt > 2QZ_6QZ_pubcat.txt.nocomma
fin = open('2QZ_6QZ_pubcat.txt.nocomma', 'r')
fout = open('2QZ_6QZ_pubcat.csv', 'w')
for line in fin:
tag = line.split()
name = tag[0]
ra_j2000 = tag[1] + ":" + tag[2] + ":" + tag[3]
dec_j2000 = tag[4] + ":" + tag[5] + ":... |
'''
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/AssetManagement/export_ImageCollection.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a ta... |
from ramda import *
from ramda.private.asserts import *
def to_pairs_test():
assert_equal(to_pairs({"a": 1, "b": 2, "c": 3}), [["a", 1], ["b", 2], ["c", 3]])
|
import abc
import xml.etree.ElementTree as ET
from typing import Type
from humanfriendly import parse_size, format_size
from pystatus.plugin import IPlugin, IInstance
class StorAvailPlugin(IPlugin):
def __init__(self, name: str, version: str,
author: str, inst: Type[IInstance]):
super()._... |
from app.models import Period
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length
class PeriodForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(min=1, max=150)])
submit = SubmitField('Submit') |
import pylearn2
import pylearn2.datasets as ds
import numpy as np
from hmmlearn import hmm
import os
import pickle
def build_dataset(model,num_samples,sample_length,label_index,num_classes):
all_data = []
all_labels = []
for i in range(num_samples):
data,labels = model.sample(sample_length)
... |
# !/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Extracts native methods from a Java file and generates the JNI bindings.
If you change this, please run and update the tests.""... |
from linkedList import linkedList
from random import random
from math import log
class tableMethodExt(object):
I"""Implementation of the extended table method. """
def __init__(self, base = 10, spaceMultiplier = 2.0):
super(tableMethodExt, self).__init__()
# base value used to split the table... |
from olympia.stats.models import ThemeUpdateCount, UpdateCount
def migrate_theme_update_count(lwt, static_theme, **kw):
"""Create UpdateCount instances from ThemeUpdateCount instances.
By default all instances for the specified lwt (lightweight theme) are
copied. Any additional **kw are passed to the fil... |
#!/usr/local/bin/python2.6 -tt
# Copyright 2019-present Facebook, 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 b... |
#
# PySNMP MIB module CPQSTSYS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CPQSTSYS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:27:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
"""
:copyright: © 2019 by the Lin team.
:license: MIT, see LICENSE for more details.
"""
from lin.exception import NotFound, ParameterException
from lin.interface import InfoCrud as Base
from sqlalchemy import Column, String, Integer
from app.libs.error_code import BookNotFound
class Book(Base):
id = Col... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2019/1/29 9:26 PM
# @Author : w8ay
# @File : app_icon.py
from django import template
from Server.settings import WAPP_ICON
register = template.Library()
@register.filter
def app_icon(product):
html = '''<span class="badge badge-diy badge-pill">{}</s... |
import altair as alt
import pandas as pd
from .visitor import visit
@visit.register(alt.FoldTransform)
def visit_fold(transform: alt.FoldTransform, df: pd.DataFrame) -> pd.DataFrame:
transform = transform.to_dict()
fold = transform["fold"]
var_name, value_name = transform.get("as", ("key", "value"))
v... |
import platform
import textwrap
import pytest
from . import test_projects, utils
# TODO: specify these at runtime according to manylinux_image
project_with_manylinux_symbols = test_projects.new_c_project(
spam_c_top_level_add=textwrap.dedent(
r"""
#include <malloc.h>
#include <stdlib.h>
... |
"""
Compute shader with buffers
"""
import random
import math
from array import array
import arcade
from arcade.gl import BufferDescription
COMPUTE_SHADER = """
#version 430
layout(local_size_x=%COMPUTE_SIZE_X%, local_size_y=%COMPUTE_SIZE_Y%) in;
uniform vec2 screen_size;
uniform vec2 force;
uniform float frame_tim... |
class UserNotFound(BaseException):
"""Thrown if a user passed is not in database"""
pass
|
# Download the Python helper library from twilio.com/docs/python/install
import os
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
# To set up environmental variables, see http://twil.io/secure
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from afl_utils import afl_sync
from afl_utils.afl_sync import AflRsync
import os
import shutil
import unittest
class AflSyncTestCase(unittest.TestCase):
def setUp(self):
# Use to set up test environment prior to test case
# invocation
os.makedirs('testdata/rsync_tmp_store', exist_ok=True)... |
import smart_imports
smart_imports.all()
class LogicStorageTestsCommon(utils_testcase.TestCase):
def setUp(self):
super(LogicStorageTestsCommon, self).setUp()
self.p1, self.p2, self.p3 = logic.create_test_map()
self.storage = logic_storage.LogicStorage()
def test_initialize(self)... |
import os
import logging
from serif.model.base_model import BaseModel
import time
import pickle
logger = logging.getLogger(__name__)
class LearnItRelationPatternCounter(BaseModel):
def __init__(self, task, **kwargs):
super(LearnItRelationPatternCounter, self).__init__(**kwargs)
self.task = task
... |
#!/usr/bin/env python
############################################################################
# tools/ide_exporter.py
#
# Copyright (C) 2016 Kha Vo. All rights reserved.
# Author: Kha Vo <canhkha@gmail.com>
#
# Based on convert_make2file_list.py and add_source_in_iar.py
# Author: avyhovanec@yahoo.com
#
# ... |
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2018-2020 CNRS
# 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 limita... |
# https://www.hackerrank.com/challenges/30-testing/problem
def minimum_index(seq):
if len(seq) == 0:
raise ValueError("Cannot get the minimum value index from an empty sequence")
min_idx = 0
for i in range(1, len(seq)):
if seq[i] < seq[min_idx]:
min_idx = i
return min_idx
... |
from redgrease import GB, execute, hashtag
def count_hashtags(_):
ht = hashtag()
execute("HINCRBY", "hashtag", ht, 1)
gb = GB()
gb.foreach(count_hashtags)
gb.run()
|
# Copyright 2020 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless require... |
__author__ = 'moshebasanchig'
from setuptools import setup, find_packages
from pip.req import parse_requirements
import pip
VERSION = '0.1.7'
requirements = [str(ir.req) for ir in parse_requirements('requirements.txt', session=pip.download.PipSession())]
setup(
name='Hydro',
version=VERSION,
packages=f... |
# Copyright 2019-present MongoDB, 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 wr... |
import setuptools
setuptools.setup(
name='neuronsdataset',
version='1.0',
description='Neurons Dataset Dataloader',
author='CASIA-DRL',
author_email='',
packages=setuptools.find_packages(),
) |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
# vim: et:ts=4:sw=4:fenc=utf-8
import json
import os
import time
import math
def get_machine_dependent_params(settings, isa):
if os.path.isfile(settings.machine_dependent_params_file) and not settings.newSU:
with open(settings.machine_dependent_params_file, "r") as params_file:
params = json.... |
# error if not grade for a student
# OPTION 2: change the policy
def get_stats(class_list):
new_stats = []
for item in class_list:
new_stats.append([item[0], item[1], avg(item[1])])
return new_stats
def avg(grades):
try:
return sum(grades)/len(grades)
except ZeroDivisionError:
... |
"""
import torch
import torch.nn as nn
from copy import copy
from abc import ABC, abstractmethod
from collections import OrderedDict
from collections import namedtuple
import numpy as np
def phase_dencode(phase_bit_string):
n = int(np.sqrt(2 * len(phase_bit_string) - 7/4) - 1/2)
genome = []
for i in range(... |
# flake8: noqa
"""
Module which contains most imports and data unit tests
might need, to reduce the amount of boilerplate.
"""
from trimesh.base import Trimesh
from trimesh.constants import tol, tol_path
from collections import deque
from copy import deepcopy
import collections
import trimesh
from distutils.spawn impor... |
import os
import pickle
import re
import subprocess
import time
from itertools import compress
import numpy as np
from cv2 import cv2
from keras.applications.vgg16 import VGG16
from keras.models import Model, load_model
from keras.layers import Dense, Flatten, Dropout, BatchNormalization
from keras.utils import to_cate... |
import multiprocessing
import pandas as pd
def lofo_to_df(lofo_scores, feature_list):
importance_df = pd.DataFrame()
importance_df["feature"] = feature_list
importance_df["importance_mean"] = lofo_scores.mean(axis=1)
importance_df["importance_std"] = lofo_scores.std(axis=1)
for val_score in range... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 27 13:15:22 2018
Used to generate QQ plots of rg split sumstats.
@author: nbaya
"""
import hail as hl
import pandas as pd
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
splitA = hl.import_table('/Users/nbaya/Docume... |
from ._app_layout import AppLayout
from ._search_display import SearchDisplay
from ._function_parameters_display import FunctionParametersDisplay
from ._function_documentation import FunctionDocumentation
from ._access_management import AccessManagement
from ._summary_page import SummaryPage
__all__ = ['SearchDisplay'... |
from sklearn import linear_model
if __name__ == '__main__':
"""ridge regression"""
reg = linear_model.Ridge(alpha=0.5)
reg.fit([[0, 0], [0, 0], [1, 1]], [0, .1, 1])
print(reg.coef_)
""" Generalized Cross-Validation"""
reg = linear_model.RidgeCV(alphas=[0.1, 1.0, 10.0])
reg.fit([[0, 0], [0, ... |
"""
Copyright (c) 2020 COTOBA DESIGN, 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, distri... |
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'suxx'
__mtime__ = '2019/1/23'
"""
import unittest, sys
sys.path.append("../")
import read_conf
from function.func import *
from function.ela_log import MyLog
log = MyLog.get_log()
logger = log.get_logger()
a = read_conf.ReadConfig()
b = read_conf.ReadData()
i... |
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def static_fullpath(request, path):
protocol = 'https://' if request.is_secure() else 'http://'
host = request.get_host()
static_url = settings.STATIC_URL
return protocol + host + static_ur... |
from copy import deepcopy
import factory.random
import pytest
from api.factories import DeliveryLogFactory
from common.tests.mock_data import QURIIRI_SMS_RESPONSE
from django.contrib.auth.models import AnonymousUser
from freezegun import freeze_time
from rest_framework.authtoken.models import Token
from rest_framework... |
# 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 agreed to in writing, ... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: welcome_view.py
Description : 欢迎页视图跳转
Author : charl
date: 2018/11/9
-------------------------------------------------
Change Activity: 2018/11/9:
-----------------------------------------------... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import spack.paths
class UrlListTest(Package):
"""Mock package with url_list."""
homepage =... |
from tkinter import *
import math,random
#Fall sem heldur utan um þríhyrninga liðinn
def thry():
for a in root.winfo_children():
a.destroy()
#Fall sem reiknar rúmmál þríhyrnings
def rummal():
for a in root.winfo_children():
a.destroy()
#Fall sem framkvæmir r... |
from sys import stdin, stdout
res = [-1] * 1001
for n in range(1, 1001):
sf = sum(i + (n//i if i*i != n else 0) for i in range(1, int(n**0.5)+1) if n % i == 0)
if sf < 1001:
res[sf] = max(res[sf], n)
for cse, n in enumerate(stdin.read().split()):
if int(n):
stdout.write('Case {}: {}\n'.format(cse+1, res... |
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
''' plot tsdiffana parameters '''
from __future__ import absolute_import
import numpy as np
import nipy
from .timediff import time_slice_diffs
from nipy.externals.six import string_types
def plot_tsdiff... |
# -*- coding: utf-8 -*-
# File: training.py
import copy
import pprint
import re
from abc import ABCMeta, abstractmethod
from contextlib import contextmanager
import six
import tensorflow as tf
from six.moves import range, zip
from ..compat import tfv1
from ..tfutils.common import get_tf_version_tuple
from ..tfutils.g... |
import cpm_kernels.torch as ct
import cpm_kernels.kernels as ck
import torch
import unittest
import random
class TestArith(unittest.TestCase):
def test_global_scale(self):
with torch.cuda.device(3):
for shape in [
(3, 5, 6),
(17, 32, 128),
(32, 10... |
# Generated by Django 3.2.11 on 2022-03-17 22:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AmogusApp', '0005_auto_20220318_0156'),
]
operations = [
migrations.AlterField(
model_name='room',
name='contractAd... |
from __future__ import absolute_import, division, print_function
import datetime
import numpy as np
from pandas import DataFrame, Series
from datashape import to_numpy
from ..expr import Reduction, Field, Projection, Broadcast, Selection, ndim
from ..expr import Distinct, Sort, Head, Label, ReLabel, Expr, Slice
from... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class RegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
class UserU... |
__all__ = [
'log',
'init_log',
]
import os
import sys
import yaml
import logging
import logging.handlers
import multiprocessing
def listener_configurer(config_path):
formatter = logging.Formatter(
'%(asctime)s %(processName)-11s tid-%(thread)-16d %(levelname)8s: %(message)s (%(funcName)s)'
)... |
from __future__ import unicode_literals, print_function
import requests
from requests.adapters import HTTPAdapter
GROUPS = (
('fictional-character', 'https://wdq.wmflabs.org/api?q=claim[31:95074]'),
('philosophers', 'https://wdq.wmflabs.org/api?q=claim[106:4964182]'),
('warriors', 'https://wdq.wmflabs.org/... |
from dataclasses import dataclass, field
from typing import Optional, Union
from bindings.gmd.measure_type import MeasureType
from bindings.gmd.nil_reason_enumeration_value import NilReasonEnumerationValue
__NAMESPACE__ = "http://www.opengis.net/gml"
@dataclass
class Quantity(MeasureType):
"""
An XML attribu... |
# -*- coding: utf-8 -*-
""" For databases """
import sqlite3
""" For files """
from os import path, mkdir, remove
""" For download music """
import requests
from mutagen.easyid3 import EasyID3
""" For encode/decode db4 """
from Scripts.settings import encode_text, decode_text, sql_request
def erro... |
for i in range(11):
print i
|
load(":inner_dep.bzl", "inner_rule_impl", "prep_work")
prep_work()
my_rule_impl = inner_rule_impl
|
import MDAnalysis as mda
from MDAnalysis.analysis.dihedrals import Dihedral
import math
def calcOsp(u, startRes, endRes, outfile):
b = startRes - 1 # GROMACS offset residue number by 1. Hence need to substract 1
e = endRes - 1
phiAtoms = [res.phi_selection() for res in u.residues[b+1:e]]
psiA... |
import io
import os
import pathlib
import warnings
from collections import OrderedDict
from copy import deepcopy
import gym
import numpy as np
import pytest
import torch as th
from stable_baselines3 import A2C, DDPG, DQN, PPO, SAC, TD3
from stable_baselines3.common.base_class import BaseAlgorithm
from stable_baseline... |
import math
import time # import time to use for performance analysis
import numpy as np # import numpy for array space
import matplotlib.pyplot as plt # import matplotlib for graphing functions
from scipy.integrate import odeint # import scipy to use the ordinary diffe... |
'''https://leetcode.com/problems/valid-anagram/'''
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s)==sorted(t) |
import sys
from colorama import init, AnsiToWin32, Fore, Back, Style
def FormatEssentialDeviceInfo(device, includeBatteryInfo):
"""
Formats given device information into one array for printing.\n
It contains device info as follows:\n
[Device manufacturer + market name], [OS version], [CPU SoC], [GPU r... |
from fnmatch import fnmatch
from lxml.etree import Element
from Framework import Transform_Wrapper, Load_File, Load_Files, Plugin_Log
from .Support import Standardize_Match_Rules
from .Support import XML_Multiply_Int_Attribute
from .Support import XML_Multiply_Float_Attribute
__all__ = [
'Increase_AI_Script_Waits... |
from django.contrib.auth.forms import UserCreationForm
from django.views.generic.edit import CreateView
from django.urls import reverse
# Create your views here.
class RegisterView(CreateView):
template_name = 'user/register.html'
form_class = UserCreationForm
def get_success_url(self):
return reverse('user:logi... |
from .deform_conv import (ModulatedDeformConv,
)
__all__ = [
'ModulatedDeformConv',
]
|
from itertools import product
import numpy as np
import pandas as pd
import torch
from trains import Task
from models.detection.SSD.priorbox_optimization import PriorOptimizationInput, ImageSizeTuple
from models.detection.SSD.priorbox_optimization.bbox_clustering import get_box_pairwise_iou
def collect_ground_truth... |
from setuptools import setup
package_name = 'examples_tf2_py'
setup(
name=package_name,
version='0.14.1',
packages=[package_name],
data_files=[
('share/ament_index/resource_index/packages',
['resource/' + package_name]),
('share/' + package_name, ['package.xml']),
(... |
#
# Copyright (c) 2008-2015 Citrix Systems, 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 l... |
# Array; Dynamic Programming
# Say you have an array for which the ith element is the price of a given stock on day i.
#
# If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
#
# Note that you cannot sell a stoc... |
"""
config setup for fmri-handbook
"""
import os
import git
import yaml
from box import Box
from pathlib import Path
def get_config(nbfile=None, configfile=None, basedir=None, required_dirs=None):
"""
load config for project from yaml file
Arguments:
nbfile: name of notebook file (i.e. __file__), us... |
import random as random
#import sys
#sys.path.append("../../current_code/")
from carryover import noOffspringFnc
from carryover import gene2bin
from carryover import offspringGenotypeFnc
from carryover import dispFnc
from carryover import compnSimpleFnc
def timestep(parameters, ecosystem, landscape):
# reproduct... |
from unittest import TestCase
from unittest.mock import patch
from ruuvitag_sensor.ruuvi import RuuviTagSensor
from ruuvitag_sensor.ruuvitag import RuuviTag
# pylint: disable=W0613
class TestRuuviTagSensor(TestCase):
def get_data(self, mac, bt_device):
# https://ruu.vi/#AjwYAMFc
data = '043E2A02... |
# coding:utf-8
import os
import gc
import numpy as np
import pandas as pd
from keras.layers import *
from keras.models import Model
from keras.utils import Sequence
from keras.optimizers import Adam
from matplotlib import pyplot as plt
from keras.initializers import he_normal
from sklearn.model_selection import KFold
... |
# -*- coding: utf-8; -*-
#
# @file contenttype.py
# @brief Rest handlers.
# @author Frédéric SCHERMA (INRA UMR1095)
# @date 2016-09-01
# @copyright Copyright (c) 2016 INRA/CIRAD
# @license MIT (see LICENSE file)
# @details
from django.contrib.contenttypes.models import ContentType
from django.core.cache import cache
... |
# -*- coding: utf-8 -*-
from application import exception
from application.model.service import Service
from application.util import background_task
from application.util.database import session_scope
from application.views.base_api import BaseNeedLoginAPI, ApiResult
class ServicePasswordAPI(BaseNeedLoginAPI):
me... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.