content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
import sys
from shutil import rmtree
from os.path import abspath, dirname, join
import django
from django.conf import settings
sys.path.insert(0, abspath(dirname(__file__)))
if not settings.configured:
media_root = join(abspath(dirname(__file__)), 'test_files')
rmtree(media_root, igno... |
import lightgbm as lgbm
from sklearn.model_selection import StratifiedKFold
import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score
def load_data():
real_df = pd.read_csv(
"feat/real.txt",
delimiter=" ",
header=None,
names=["a", "b", "c", "d", "e", "f"],
... |
class BudgetFiscalYear():
'''Class to describe the federal fiscal year'''
__base = None
__bfy = None
__efy = None
__today = None
__date = None
__startdate = None
__enddate = None
__expiration = None
__weekends = 0
__workdays = 0
__year = None
__month = None
__day ... |
# import os
# import shutil
# from django.test import TestCase
# from django_dicom.data_import.local_import import LocalImport
# from django_dicom.models.image import Image
# from tests.fixtures import TEST_FILES_PATH, TEST_IMAGE_PATH, TEST_ZIP_PATH
# TESTS_DIR = os.path.normpath("./tests")
# TEMP_FILES = os.path.jo... |
import os
import joblib
import pandas as pd
import numpy as np
from dataclasses import dataclass
from sklearn.preprocessing import RobustScaler
from sklearn.feature_selection import VarianceThreshold
from rdkit import Chem
from rdkit.Chem import MACCSkeys
from rdkit.Chem import MolFromSmarts
from mordred import Calc... |
import torch.nn as nn
import functools
import torch
import functools
import torch.nn.functional as F
from torch.autograd import Variable
import math
import torchvision
class Bottleneck(nn.Module):
# expansion = 4
def __init__(self, inplanes, outplanes, stride=1, downsample=None):
super(... |
# -*- coding: utf-8 -*-
#
# Copyright 2015 Benjamin Kiessling
#
# 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 ... |
hello = 'hello world'
print(hello) |
# -*- coding: utf-8 -*-
nota1 = float(input('Digite a primeira nota: '))
nota2 = float(input('Digite a segunda nota: '))
media = (nota1 + nota2) / 2
print('A média foi de {:.2f}!'.format(media)) |
import unittest
import sys
undertest = __import__(sys.argv[-1].split(".py")[0])
maioridade_penal = getattr(undertest, 'maioridade_penal', None)
class PublicTests(unittest.TestCase):
def test_basico_1(self):
assert maioridade_penal("Jansen Italo Ana","14 21 60") == "Italo Ana"
if __name__ == '__m... |
#!/usr/bin/python3
import json
def stringToInt(origin_string):
result = 0
temp_string = origin_string.strip()
for c in temp_string:
if c >= '0' and c <= '9':
result = result * 10 + (ord(c) - ord('0'))
else:
return -1
return result
def getString(hint, default_value... |
import sys
import zipfile
import shutil
import commands
import os
import hashlib
import re
import traceback
import json
from lib.dexparser import Dexparser
from lib.CreateReport import HTMLReport
from lib.Certification import CERTParser
import lib.dynamic as dynamic
dexList = [] #dexfile list
#program usage
def usag... |
#!/usr/bin/env python
import setuptools
setuptools.setup(
author='Bryan Stitt',
author_email='bryan@stitthappens.com',
description='Mark shows unwatched on a schedule.',
long_description=__doc__,
entry_points={
'console_scripts': [
'plex-schedule = plex_schedule.cli:cli',
... |
"""A class using all the slightly different ways a function could be defined
and called. Used for testing appmap instrumentation.
"""
# pylint: disable=missing-function-docstring
from functools import lru_cache, wraps
import time
import appmap
class ClassMethodMixin:
@classmethod
def class_method(cls):
... |
# Copyright 2014 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
from unittest import TestCase
from gui_components import parser
from math import tan
class ParserTestCase(TestCase):
def test_ctan(self):
self.assertEqual(parser.ctan(0.5), 1 / tan(0.5))
def test__check_res(self):
self.assertEqual(parser._check_res('2*x+3', 1), (True, 5))
self.assertE... |
import random
whi1 = True
while whi1 is True:
try:
print("Selamat Datang Di Game Batu, Gunting, Kertas!")
pilihanAwal = int(input("Apakah Kau Ingin Langsung Bermain?\n1. Mulai Permainan\n2. Tentang Game\n3. Keluar\nPilihan: "))
whi2 = True
while whi2 is True:
if pil... |
# Generated by Django 2.0.13 on 2020-10-10 16:05
import ddcz.models.magic
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('ddcz', '0024_skills_name'),
]
operations = [
migrations.AlterField(
model_name='commonarticle',
na... |
# Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory
# 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/... |
from .calibration import Calibration
from .capture import Capture
from .configuration import Configuration, default_configuration
from .device import Device
from .image import Image
from .imu_sample import ImuSample
from .transformation import Transformation |
# some comment
""" doc string """
import math
import sys
class the_class():
# some comment
""" doc string """
import os
import sys
class second_class():
some_statement
import os
import sys
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Pizza Project - main.py - started on 8 November 2021
# Written by Garret Stand licensed under a MIT license for academic use.
# This file contains shell formatting and other output modification/redirections functions for the program. It is a non-executable library.
# Please ... |
#!/usr/bin/env python
# encoding: utf-8
# 把str编码由ascii改为utf8(或gb18030)
import random
import sys
import time
import requests
from bs4 import BeautifulSoup
file_name = 'book_list.txt'
file_content = '' # 最终要写到文件里的内容
file_content += '生成时间:' + time.asctime()
headers = [
{'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Li... |
import numpy as np
from scipy.ndimage import map_coordinates
import open3d
from PIL import Image
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
import functools
from multiprocessing import Pool
from utils_eval import np_coor2xy, np_coory2v
def xyz_2_coorxy(xs, ys, zs, H, W):
us... |
import pytest
from openeye import oechem
from openff.recharge.aromaticity import AromaticityModel, AromaticityModels
from openff.recharge.utilities.openeye import smiles_to_molecule
@pytest.mark.parametrize(
"smiles",
[
"c1ccccc1", # benzene
"c1ccc2ccccc2c1", # napthelene
"c1ccc2c(c... |
import pygame, math, os, time
from .Torpedo import Torpedo
from .Explosion import Explosion
FRICTION_COEFF = 1 - 0.015
class Spaceship(pygame.sprite.Sprite):
def __init__(self, colour, img_path, bearing, torpedo_group, explosion_group):
super().__init__()
self.torpedo_group = torpedo_group
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
from datetime import datetime
class SyncModel:
""" Implements common methods used by the models for syncing data into database.
currently following models use this: Companies, Contacts, Departments, Events,
Invoices, Projects, Users."""
def ... |
class InvalidBrowserException(Exception):
pass
class InvalidURLException(Exception):
pass
|
import os
import time
import json
import string
import random
import itertools
from datetime import datetime
import numpy as np
import pandas as pd
from numba import jit
from sklearn.metrics import mean_squared_error
from contextlib import contextmanager, redirect_stdout
import matplotlib.pyplot as plt
N_TRAIN = 20216... |
"""
Configurations for Reserved Virtual Machines simulations:
"""
###################################
### Don't touch this line - import
import numpy
###################################
################################################
### General configurations, for all simualtions
START_TIME = 0 # Seconds - NOT IMP... |
#!/usr/bin/python
#
## @file
#
# Collection of classes that control the establish the basic operation of dave
# as it issues various types of commands to HAL and Kilroy
#
# Jeff 3/14
#
# Hazen 09/14
#
from xml.etree import ElementTree
from PyQt4 import QtCore
import sc_library.tcpMessage as tcpMessage... |
"""
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
import asyncio
import loggi... |
# Not used
# Author : Satish Palaniappan
__author__ = "Satish Palaniappan"
import os, sys, inspect
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
from twokenize import *
import re
Code = r"\\[... |
import json
import cv2.aruco as aruco
import numpy as np
with open("config.json", "r") as json_file:
data = json.load(json_file)
arucoDictionary = aruco.Dictionary_get(data["arucoDictionary"])
timeStep = data["timeStep"]
isLogEnabled = bool(data["logEnabled"])
markerWidth = data["markerWidth"]
... |
import unittest
import younit
# @unittest.skip("skipped")
class CommonTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
async def async_setUp(self):
pass
async def async_tearDown(self):
pass
def setUp(self):
pass
def tearDown(self):
... |
# -*- coding: utf-8 -*-
import os
import pathlib
from .Decorators import Decorators
from ...Exceptions import AsyncyError
def safe_path(story, path):
"""
safe_path resolves a path completely (../../a/../b) completely
and returns an absolute path which can be used safely by prepending
the story's tmp ... |
# Generated by Django 3.1.2 on 2020-10-30 18:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('catalog', '0002_auto_20201030_1417'),
]
operations = [
migrations.RemoveField(
model_name='book... |
import logging
from application.utils import globals
from application.utils.helpers import Singleton
from pymongo import MongoClient, ASCENDING, DESCENDING
@Singleton
class Connection:
_client = None
db = None
def __init__(self):
try:
self._client = MongoClient(globals.configuration.m... |
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... |
# Generated by Django 2.2.5 on 2019-11-21 01:48
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Search',
fields=[
('id', mo... |
import os
import sys
import tempfile
import mimetypes
import webbrowser
# Import the email modules we'll need
from email import policy
from email.parser import BytesParser
# An imaginary module that would make this work and be safe.
from imaginary import magic_html_parser
# In a real program you'd get the filename f... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
My first warp!
Using scikit-image piecewise affine transformation,
based on manual node assignment with stable corners.
A midpoint morph (halfway between the key frames) is generated.
http://scikit-image.org/docs/dev/auto_examples/plot_piecewise_affine.html
"""
####... |
# Copyright (c) 2006-2013 Regents of the University of Minnesota.
# For licensing terms, see the file LICENSE.
import os
import sys
import re
import traceback
# This is the global namespace.
# 2011.04.19: g.log is the only member of the global namespace. I think there
# were bigger plans for g.py, but i... |
# -*- coding: utf-8 -*-
""" contest forms: HTTP form processing for contest pages
:copyright: Copyright (c) 2014 Bivio Software, Inc. All Rights Reserved.
:license: Apache, see LICENSE for more details.
"""
import decimal
import re
import sys
import flask
import flask_mail
import flask_wtf
import paypalrest... |
import sqlite3
import os
import urllib.request
from urllib.error import *
DATABASE_PATH = 'database/card_image_database.db'
def create_card_image_database(print_function):
print_function('Creating Database.')
if os.path.exists(DATABASE_PATH):
try:
os.remove(DATABASE_PATH)
except O... |
/home/runner/.cache/pip/pool/37/a3/2b/4c0a8aea5f52564ead5b0791d74f0f33c3a5eea3657f257e9c770b86c6 |
'''
Largest Palindrome of two N-digit numbers given
N = 1, 2, 3, 4
'''
def largePali4digit():
answer = 0
for i in range(9999, 1000, -1):
for j in range(i, 1000, -1):
k = i * j
s = str(k)
if s == s[::-1] and k > answer:
return i, j
def largePali3dig... |
import os
import tempfile
from os import makedirs
from os.path import join, exists
from sys import platform
def get_home_folder():
from pathlib import Path
home_folder = f"{Path.home()}"
return home_folder
def get_temp_folder():
temp_folder = None
if platform == "linux" or platform == "linux2... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def addTwoNumbers(list1, list2, node, digit):
n = digit
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from chai import Chai
from arrow import arrow, locales
class ModuleTests(Chai):
def test_get_locale(self):
mock_locales = self.mock(locales, "_locales")
mock_locale_cls = self.mock()
mock_locale = self.mock()
self.... |
# -*- coding: utf-8 -*-
# Copyright (C) H.R. Oosterhuis 2021.
# Distributed under the MIT License (see the accompanying README.md and LICENSE files).
import numpy as np
import os.path
import gc
import json
FOLDDATA_WRITE_VERSION = 4
def _add_zero_to_vector(vector):
return np.concatenate([np.zeros(1, dtype=vector.d... |
from django.test import TestCase
from django.urls import reverse
from .models import Post
# Create your tests here.
class PostModelTest(TestCase):
def setUp(self):
Post.objects.create(title='Mavzu', text='yangilik matni')
def test_text_content(self):
post = Post.objects.get(id=1)
expe... |
from django.shortcuts import render, redirect, get_object_or_404
from .models import BlogPost as blog
from .models import Comment
from .forms import CreateCommentForm, UpdateCommentForm
# Create your views here.
def post_view(request):
qs=blog.objects.all()
context = {
'qs' : qs,
}
return render(request, 'blog/m... |
from pyflink.common import ExecutionMode, RestartStrategies
from pyflink.common.serialization import JsonRowDeserializationSchema
from pyflink.common.typeinfo import Types
from pyflink.dataset import ExecutionEnvironment
from pyflink.datastream import StreamExecutionEnvironment, CheckpointingMode, ExternalizedCheckpoin... |
import sys
import os
from bs4 import BeautifulSoup
import markdown
"""
将 Markdown 转换为 HTML
"""
class MarkdownToHtml:
headTag = '<head><meta charset="utf-8" /></head>'
def __init__(self,cssFilePath = None):
if cssFilePath != None:
self.genStyle(cssFilePath)
def genStyle(self,cssFile... |
import math
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.transforms as mtransforms
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
def setup_axes(diff=False):
fig = plt.figure()
axes = []
if diff:
gs = gridspec.GridSpec(2, 1, height_rati... |
from rest_framework import serializers
from polyclinics.models import Poly
class PolySerializer(serializers.ModelSerializer):
class Meta:
model = Poly
fields = '__all__'
|
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''BuddyPress REST API Privilege Escalation to RCE''',
"description": '''The BuddyPress WordPress plugin was affected by an REST API Privilege Escalation to RCE''',
"severity": "high",
"re... |
#!/usr/bin/env python
# Copyright (C) 2017 Google 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 la... |
import time
# only required to run python3 examples/cvt_arm.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from torch.utils.data import Dataset
import os
import math
import numpy as np
device = torch.device('cuda' if torch.cuda.is... |
import os
import requests
from datetime import datetime, timedelta
import gitlab
class Gitlab():
def __init__(self, api_url, **kwargs):
self.gitlab = gitlab.Gitlab(api_url, **kwargs)
def is_gitlab(self):
if os.environ.get('CI', 'false') == 'true':
return True
else:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---------------------------------------
# Project: PKUYouth Webserver v2
# File: __init__.py
# Created Date: 2020-07-28
# Author: Xinghong Zhong
# ---------------------------------------
# Copyright (c) 2020 PKUYouth
import time
import datetime
import calendar
from func... |
import os
import re
import sys
import codecs
from setuptools import setup, find_packages, Command
from setuptools.command.test import test as TestCommand
here = os.path.abspath(os.path.dirname(__file__))
setup_requires = ['pytest', 'tox']
install_requires = ['six', 'tox', 'atomos']
tests_require = ['six', 'pytest-c... |
# Unsere Funktion nimmt eine Liste als Parameter
def find_nouns(list_of_words):
nouns = list()
# Das erste Wort ist wahrscheinlich großgeschrieben, fällt aber aus unserer Definition raus
for i in range(1, len(list_of_words)):
current_word = list_of_words[i]
if current_word[0].isupper():
#... |
from app import app
from flask import Blueprint, render_template
@app.errorhandler(404)
def not_found_error():
return render_template('errors/404.html'), 404
@app.errorhandler(500)
def internal_error(error):
return render_template('errors/500.html'), 500
|
import glob
import numpy as np
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description="Produce report from result files")
parser.add_argument('--path', type=str, default="",
help="Path to the result files (* will be appended)")
args = parser.parse_args()... |
# This sample tests the case where a protocol class derives from
# another protocol class.
from typing import Generic, TypeVar, Protocol
Arg = TypeVar("Arg", contravariant=True)
Value = TypeVar("Value")
class Base1(Protocol[Value]):
def method1(self, default: Value) -> Value:
...
class Base2(Base1[Valu... |
import collections
from supriya import CalculationRate
from supriya.synthdefs import WidthFirstUGen
class ClearBuf(WidthFirstUGen):
"""
::
>>> clear_buf = supriya.ugens.ClearBuf.ir(
... buffer_id=23,
... )
>>> clear_buf
ClearBuf.ir()
"""
### CLASS V... |
from collections import OrderedDict
from itertools import takewhile
from dht.utils import last
class Cluster(object):
def __init__(self, members):
self.hash = hash
self.members = OrderedDict(((self.hash(node), node) for node in members))
def __len__(self):
return sum((len(node) for n... |
from typing import Optional
from pydantic import BaseSettings, Json
from ._version import version as __version__ # NOQA
class Settings(BaseSettings):
auth_token_url: str = "https://solarperformanceinsight.us.auth0.com/oauth/token"
auth_jwk_url: str = (
"https://solarperformanceinsight.us.auth0.com/.w... |
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from backend.api.models import MiembroSprint, Usuario, Rol
from backend.api.serializers import UsuarioSerializer
class UsuarioViewSet(viewsets.ViewSet):
"""
UsuarioViewSet View... |
from thenewboston.accounts.manage import create_account
from thenewboston.verify_keys.verify_key import encode_verify_key
def random_encoded_account_number():
signing_key, account_number = create_account()
return encode_verify_key(verify_key=account_number)
|
# -*- coding: utf-8 -*-
import streamlit as st
import numpy as np
import pandas as pd
import altair as alt
from io import BytesIO
def to_excel(df):
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, index=True, sheet_name='杜子期血常规数据统计')
workbook = writer.book
... |
import asyncio
import logging
import logging.handlers
import time
from contextlib import suppress
from typing import Optional, Union
from ..thread_pool import run_in_new_thread
def _thread_flusher(
handler: logging.handlers.MemoryHandler,
flush_interval: Union[float, int],
loop: asyncio.AbstractEventLoop... |
#
# Copyright (c) 2006-2013, Prometheus Research, LLC
#
"""
:mod:`htsql.ctl.regress`
========================
This module implements the `regress` routine.
"""
from .error import ScriptError
from .routine import Argument, Routine
from .option import (InputOption, TrainOption, PurgeOption,
Forc... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
import gym
import shutil
import tempfile
import ray
from ray.rllib.a3c import DEFAULT_CONFIG
from ray.rllib.a3c.a3c_evaluator import A3CEvaluator
from ray.rllib.dqn.dqn_evaluator import adjust_... |
# -*- coding: utf-8 -*-
"""
Management of Redis server
==========================
.. versionadded:: 2014.7.0
:depends: - redis Python module
:configuration: See :py:mod:`salt.modules.redis` for setup instructions.
.. code-block:: yaml
key_in_redis:
redis.string:
- value: string data
The redis s... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('canyon.png')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
values = []
for i in range(256):
n = np.where(gray_img == i, 1., 0.).sum()
values.append(n)
plt.bar(range(256), height=values, width=1.)
plt.xlabel('intensity')
plt.yl... |
"""
Profile ../profile-datasets-py/div83/023.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/023.py"
self["Q"] = numpy.array([ 2.79844200e+00, 3.21561000e+00, 4.08284300e+00,
4.76402700e+00, 4.58551900e+00, 4.69499800e+00,
5.2297... |
"""
Outpost URL Configuration
"""
import django
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.static import serve
from django.views.i18n import JavaScriptCatalog
from rest_framework.authtoken import views as authtoken
js_info_dict = {
... |
import argparse
from flatdb import flatdb_app
from flatdb.app import define_urls
def get_options():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', action='store_true', default=False)
parser.add_argument('-p', '--port', type=int, default=7532)
parser.add_argument('-b', '--data... |
'''
the following import is only necessary because eip is not in this directory
'''
import sys
sys.path.append('..')
'''
The simplest example of reading a tag from a PLC
NOTE: You only need to call .Close() after you are done exchanging
data with the PLC. If you were going to read in a loop or read
more tags, you w... |
from __future__ import unicode_literals
import frappe
from frappe.model.utils.rename_field import rename_field
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
try:
rename_field("Pricing Rule", "price_or_discount", "rate_or_discount")
rename_field("Pricing Rule", "price", "rate")
except... |
import logging
import os
import requests
import pickle
import json
from configparser import ConfigParser
logger = logging.getLogger(__name__)
project_dir = os.path.abspath(os.path.dirname(__file__)) + '/'
config = ConfigParser()
config.read(project_dir + '/config.cfg')
def get_or_download_file(filename, k, value, c... |
from collections import namedtuple
Point = namedtuple('point', 'x, y')
mouse_pos = Point(100, 200)
print("X Position of Mouse:", mouse_pos.x) |
import json
from graphql_relay import to_global_id
from tracker.api.services.auth import (
generate_auth_token,
)
from tracker.api.status_codes import StatusEnum
async def test_create_role_mutation(
client,
setup_project_list_test_retrun_auth_token
):
pm_auth_token = setup_project_list_test_retrun_a... |
import pandas as pd
from .taxa_tree import NCBITaxaTree
from ..constants import MICROBE_DIR
MICROBE_DIR_COLS = [
'gram_stain',
'microbiome_location',
'antimicrobial_susceptibility',
'optimal_temperature',
'extreme_environment',
'biofilm_forming',
'optimal_ph',
'animal_pathogen',
's... |
import json
import os
from django.apps import apps
DJANGO_TAILWIND_APP_DIR = os.path.dirname(__file__)
def get_app_path(app_name):
app_label = app_name.split(".")[-1]
return apps.get_app_config(app_label).path
def get_tailwind_src_path(app_name):
return os.path.join(get_app_path(app_name), "static_src... |
from model_defs import *
from utils import *
from tensorflow.models.rnn.rnn_cell import *
###################################
# Building blocks #
###################################
# takes features and outputs potentials
def potentials_layer(in_layer, mask, config, params, reuse=False, name='Potentia... |
import networkx as nx
import numpy as np
import torch
from gym_ds3.envs.core.node import Node
from gym_ds3.envs.utils.helper_dict import OrderedSet
class JobDAG(object):
def __init__(self, job):
self.job = job
self.jobID = self.job.task_list[0].jobID
self.commvol = self.job.comm_vol
... |
from typing import List
import torch
from torch.nn import ParameterList, Parameter
from allennlp.common.checks import ConfigurationError
class ScalarMix(torch.nn.Module):
"""
Computes a parameterised scalar mixture of N tensors, `mixture = gamma * sum(s_k * tensor_k)`
where `s = softmax(w)`, with `w` an... |
import bpy,bmesh
import time,copy,mathutils,math
from mathutils import noise
Context={
"lasttick":0,
"running":False,
"store":{},
"starttime":-1
}
def timeNow():
t=time.time()
return t
def calcFrameTime():
fps = max(1.0, float(bpy.context.scene.render.fps))
return 1.0/f... |
# -*- coding: utf-8 -*-
import os
from .. import StorageTests, get_server_mixin
dav_server = os.environ.get('DAV_SERVER', 'skip')
ServerMixin = get_server_mixin(dav_server)
class DAVStorageTests(ServerMixin, StorageTests):
dav_server = dav_server
|
from __future__ import absolute_import, division, print_function
import os
import time
import numpy as np
import seaborn as sns
import tensorflow as tf
import tensorflow_probability as tfp
from matplotlib import pyplot as plt
from tensorflow import keras
from odin import visual as vs
from odin.bay import kl_divergen... |
"""Script to convert MultiWOZ 2.2 from SGD format to MultiWOZ format."""
import glob
import json
import os
from absl import app
from absl import flags
from absl import logging
FLAGS = flags.FLAGS
flags.DEFINE_string("multiwoz21_data_dir", None,
"Path of the MultiWOZ 2.1 dataset.")
flags.DEFINE_st... |
#SENSOR_DATA_TRANSFER
import socket
import serial
host = "192.168.137.54"
port = 50007
import time
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
aD=serial.Serial('/dev/ttyACM0',9600)
while True:
while ... |
import time
from typing import Any, Union
from copy import deepcopy
import biorbd_casadi as biorbd
import numpy as np
from scipy import interpolate as sci_interp
from scipy.integrate import solve_ivp
from casadi import vertcat, DM, Function
from matplotlib import pyplot as plt
from ..dynamics.ode_solver import OdeSol... |
from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
import views
urlpatterns = patterns('',
(r'^$', views.home),
# would like to avoid hardcoding mibbinator here
(r'^(o/\.|\.?)(?P<oid>[0-9.]*)$', redirect_to, { 'url': '/mibbinator/o/%(oid)s' }),
(r'^o/(?P<oid>[0-... |
# coding=utf-8
# Copyright 2021 The OneFlow 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 require... |
# Generated by Django 3.1 on 2020-10-19 16:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0013_auto_20201020_0122'),
]
operations = [
migrations.AlterField(
model_name='restaurant',
name='business_num... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.