content stringlengths 5 1.05M |
|---|
import torch
import time
import torch.nn.functional as F
k = 3
B, C_in, W, H, U, V = 32, 4, 5, 6, 7, 8
C_out = 2
weight = torch.rand(C_out, C_in, k, k, k, k)
x = torch.rand(B, C_in, W, H, U, V)
start = time.perf_counter()
x_pad = F.pad(x, [k//2]*8)
W2, H2, U2, V2 = W + k - 1, H + k - 1, U + k - 1, V + k - 1
x_unfold... |
import logging
import time
import bisect
class PriceLookupBoundsError(Exception):
def __init__(self,requested_timestamp,nearest_timestamp,nearest_price):
super(PriceLookupBoundsError, self).__init__("Requested price lookup at time %s is out of bounds of the available data" % (requested_timestamp))
self.request... |
# Copyright 2017 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 默认是密送模式(BBC)
# 需要改为正常模式,把 send 时,bcc 改为 to
from concurrent import futures
import yagmail
from config.mail_server_config import MAIL_CONFIG, PORT, SECRET_KEY
import grpc
import sys
import re
sys.path.append("proto")
import proto.mail_pb2 as mail_pb2
import proto.mail_p... |
def indices(n, d):
return sorted([list(i) for i in helper(n, d) if len(i)==n and sum(i)==d], reverse=True)
def helper(n, d, arr=[], res=set()):
if n==0:
if d==0:
res.add(tuple(arr))
return
for i in range(d+1):
if i<=d:
helper(n-1, d-i, arr+[i], res)
retur... |
# coding: utf-8
from enum import Enum
from six import string_types, iteritems
from bitmovin_api_sdk.common.poscheck import poscheck_model
from bitmovin_api_sdk.models.retry_hint import RetryHint
import pprint
import six
class ErrorDetails(object):
@poscheck_model
def __init__(self,
code=None... |
"""
Copyright BOOSTRY Co., Ltd.
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,
software distr... |
from typing import Dict, List, Union, cast
from asgiref.sync import async_to_sync
from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ImproperlyConfigured
from django.db.mode... |
#!/usr/bin/python
import base64
import sys
for arg in sys.argv[1:]:
mime = ""
if arg.endswith(".gif"):
mime = "image/gif"
elif arg.endswith(".png"):
mime = "image/png"
elif arg.endswith(".jpg") or arg.endswith(".jpeg"):
mime = "image/jpeg"
else:
mime = "text/plain"
content = open(arg).rea... |
# Customer attrition, also known as customer churn, customer turnover, or customer defection, is the loss of clients or customers.
#predictive analytics use churn prediction models that predict customer churn by assessing their propensity of risk to churn.
# import warnings filter
from warnings import simplefi... |
import torch
import torch.nn as nn
from abc import ABC, abstractmethod
from MARS.common.nn import GraphEncoder, MLP
class Editor(ABC, nn.Module):
def __init__(self, config):
super().__init__()
self.device = config['device']
self.encoders = nn.ModuleDict()
for name in ['act', 'del',... |
import numpy
def manhatten_dist(x1, y1, x2, y2):
return abs(x2 - x1) + abs(y2 - y1)
points = []
with open("input.txt") as f:
for line in f.readlines():
stripped = line.strip().split(",")
points.append({"x": int(stripped[0]), "y": int(stripped[1])})
max_x = max(p['x'] for p in points) + 1
ma... |
import click
from ocrd.decorators import ocrd_cli_options, ocrd_cli_wrap_processor
from .decode import FSTCorrection
@click.command()
@ocrd_cli_options
def ocrd_cor_asv_fst(*args, **kwargs):
return ocrd_cli_wrap_processor(FSTCorrection, *args, **kwargs)
|
#!/usr/bin/python 3
#Wi-Fi Hotspot Enabler
import os
os.system("cls")
print("\n\n\n\n")
cmd= "0"
while cmd != "3":
print("type 1 to start program")
print("type 2 to stop program")
print("type 3 to end program")
cmd = input("Please enter your Choice....")
if cmd == "1":
ssid = input("Please... |
"""
Entradas
dato a-->int-->A
dato b-->int-->B
dato c-->int-->C
dato d-->int-->D
Salidas
numero N-->int-->N
"""
A=int(input("digite el valor del dato A "))
B=int(input("digite el valor del dato B "))
C=int(input("digite el valor del dato C "))
D=int(input("digite el valor del dato D "))
N=int(str(A)+str(B)+str(C)+str(D... |
"""Testing EnrichedEventFacet objects of cbc_sdk.endpoint_standard"""
import pytest
import logging
from cbc_sdk.endpoint_standard import EnrichedEventFacet
from cbc_sdk.rest_api import CBCloudAPI
from cbc_sdk.base import FacetQuery
from cbc_sdk.errors import ApiError, TimeoutError
from tests.unit.fixtures.CBCSDKMock i... |
## 1. Programming And Data Science ##
print(1288)
print(639)
print(1288 + 639)
## 2. Arithmetic Operators ##
nums = [749, 371, 828, 503, 1379]
print(sum(nums)/len(nums))
## 3. Variables ##
albuquerque = 749
anaheim = 371
anchorage = 828
arlington = 503
atlanta = 1379
## 4. Data Types ##
atlanta_string = "Atlanta... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------
# Archivo: xiaomi_my_band.py
# Capitulo: 3 Patrón Publica-Subscribe
# Autor(es): Perla Velasco & Yonathan Mtz.
# Version: 1.0.1 Mayo 2017
# Descripción:
#
# Ésta clase define el rol de un publicad... |
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from .views import CreateView, ListView, RetrieveView, DestroyView, UpdateView, NeedMentor
from .admin import admin
urlpatterns = {
url(r'^request_mentorship/$', CreateView.as_view(), name="create"),
url(r'^... |
#!/usr/bin/env python3
#
# Minecraft Online to offline UUID converter
# Copyright (c) 2021 Jan Blaesi
#
# 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... |
import plotly.plotly as py
import plotly.graph_objs as go
import plotly
import numpy as np
import plotly.io as pio
insNameLst = ['']
insName = '14_14_ECCENTRIC_RANDOMCLUSTERED_SVLCV_LVLCV_thre0.1MPDAins.dat'
insName = '11_8_RANDOMCLUSTERED_CENTRAL_SVSCV_LVSCV_thre0.1MPDAins.dat'
insName = '20_20_CLUSTERED_RANDOM_QU... |
"""
This is a /resources/account.py file.
This file define content an access to \
multiple HTTP Account methods by defining methods on our resource.
"""
from flask_restful import Resource, reqparse
from models.account import AccountModel
from models.mall import MallModel
class Account(Resource):
"""
... |
import setuptools
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setuptools.setup(
name='c0banAPI',
packages=['c0banAPI'],
version='1.5',
license='MIT',
description='c0banAPI wi... |
import logging
from types import SimpleNamespace
from ruamel.yaml.compat import StringIO
from yamlpath import Processor, YAMLPath
from yamlpath.common import Parsers
from yamlpath.exceptions import YAMLPathException
from yamlpath.wrappers import ConsolePrinter
from bumpsemver.exceptions import BumpVersionException, V... |
from pocket_change.auth import PocketChangeUser
from flask import g
@PocketChangeUser.authenticator
def jira_auth(user):
if g.jira.verify_credentials(user.name, user.password):
# If the user already exists in the database,
# update their password to match what authenticated
# in Jira ... |
# coding:utf-8
from django.conf.urls import include, url
from django.contrib import admin
from django.http import HttpResponse
from django.conf import settings
from django.conf.urls.static import static
def homepage(request):
response = HttpResponse('login success')
response.set_cookie(key=settings.SESSION_CO... |
# Generated by Django 3.0.8 on 2020-07-11 10:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('auctions', '0002_bids_listings'),
]
operations = [
migrations.RenameModel(
old_name='Bids',
new_name='Bid',
),
... |
from copy import deepcopy
class Node():
def __init__(self, content, encapsulate=False):
self.parent = None
self.children = []
self.descendants = 0
if encapsulate:
self.content = "root"
n = Node(content)
self.children = [n]
n.parent = ... |
from unittest.mock import MagicMock
import numpy as np
import pytest
import tensorflow as tf
from tensorflow import keras
from chitra.trainer import Dataset, InterpretModel, Trainer, create_cnn
dataset = Dataset("./")
cnn = create_cnn("mobilenetv2", num_classes=1000, keras_applications=False)
trainer = Trainer(datas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayMarketingCampaignCashCreateModel(object):
def __init__(self):
self._coupon_name = None
self._end_time = None
self._merchant_link = None
self._prize_msg = Non... |
#! /usr/bin/env python
import dlib
import numpy as np
PREDICTOR_PATH = 'FaceSwap/models/shape_predictor_68_face_landmarks.dat'
predictor = dlib.shape_predictor(PREDICTOR_PATH)
## Face and points detection
#def face_points_detection(img, bbox:dlib.rectangle):
def face_points_detection(img, bbox):
# Get the landmark... |
# TODO : count_height 함수 작성
# 1. 재귀함수를 돌면서 height를 더해 나가면서 저장
# 2. 딕셔너리를 통해 키 : 노드, 벨류 : 높이를 저장
# 3. 함수의 입력 : 노드의 개수 n, 간선 집합 edges
def count_minimum_height():
pass
import collections
edges = [[1, 3], [2, 3], [3, 4], [3, 5], [4, 6], [6, 10], [5, 7], [5, 8], [8, 9]]
# ! 꼭 노드를 없애면서 문제를 풀어야할까?
# ! 노드를 탐색하면서 다음 노드... |
from string import *
from BioSeq import Translate
import sys, os
def Main()
input = open('dna_gag','r')
output = open('dna_gag_bereinigt','a')
input2 = open('protein_gag','r')
output2 = open('protein_gag_bereinigt','a')
dnaseq = input.readlines()
protseq = input2.readlines()
dnalen = len(dnaseq)
protlen = len(... |
# --------------------------------------------------------
# Deformable Convolutional Networks
# Copyright (c) 2017 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Modified by Haozhi Qi, Yuwen Xiong
# --------------------------------------------------------
import mxnet as mx
import numpy as np
... |
from sys import maxsize
class Contact:
def __init__(self, user_firstname=None, user_middlename=None, user_lastname=None, user_nickname=None, photo_path=None,
user_title=None, company_name=None, address=None, home_phone=None, mobile_phone=None,
work_phone=None, fax_phone=None, all... |
# -*- coding: utf-8 -*-
# Django:
from django import forms
from django.forms import ModelForm
from django.forms import TextInput
from django.forms import Textarea
# Modelos:
from .models import AnexoArchivo
from .models import AnexoImagen
from .models import AnexoTexto
class AnexoTextoForm(ModelForm):
class Me... |
import parallelpcap
import os
import re
import h5py
import datetime
import tensorflow as tf
from common import natural_keys
def load_features(data_dir):
"""
Loads the embedding space from the saved
Word2Vec model.
Parameters
----------
data_dir : str
Path to the token vectors and Wor... |
#!/usr/bin/env python
"""
Classes encapsulating decypher tool.
James E Johnson - University of Minnesota
"""
import pkg_resources;
import logging, os, string, sys, tempfile, glob, shutil, types, urllib
import shlex, subprocess
from optparse import OptionParser, OptionGroup
from stat import *
log = logging.getLogger(... |
from tkinter import *
from tkinter import messagebox
def clickButton():
messagebox.showinfo('요기제목', '요기내용')
window = Tk() # root = Tk()
label1 = Label(window, text="파이썬 공부중~~")
label2 = Label(window, text="파이썬 공부중~~", font=("궁서체", 30), fg="blue")
label3 = Label(window, text="파이썬 공부중~~", bg="red", width=20, heig... |
#Instale y importe slugify para hacer el sug
from slugify import slugify
#La clase PaginaWeb con sus atributos y su metodo str
class PaginaWeb():
def __init__(self,url,ruta,formato,contenido,titulo,slug,metatags:list):
self.url = url
self.ruta = ruta
self.formato = formato
self.contenido ... |
# 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... |
import glob
import random
from skimage import io, transform
from torch.utils import data
from torchvision.transforms import ToTensor
from torchvision.transforms.functional import resize
import warnings
class PolyUDataset(data.Dataset):
DATASET_BASE_DIR = '../../data/PolyU-Real-World-Noisy-Images-Dataset/'
DATA... |
# Customize an ipython environment for KBase
#
# sychan 7/12/2013
#
# System
import getpass
import logging
import sys
# IPython
from IPython.core.magic import (Magics, magics_class, line_magic,
cell_magic, line_cell_magic)
# KBase
import biokbase.auth
from biokbase.narrative.common.url... |
# 231. Power of Two
# Given an integer, write a function to determine if it is a power of two.
# Credits:
# Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
... |
#!/usr/bin/env python
# MIPLearn: Extensible Framework for Learning-Enhanced Mixed-Integer Optimization
# Copyright (C) 2020, UChicago Argonne, LLC. All rights reserved.
# Released under the modified BSD license. See COPYING.md for more details.
"""Benchmark script
Usage:
benchmark.py train <challenge>
ben... |
# -*- coding: utf-8 -*-
"""
reStructuredText parser for rich
Initial few lines gotten from: https://github.com/willmcgugan/rich/discussions/1263#discussioncomment-808898
There are a lot of improvements are added by me
"""
from io import StringIO
from html.parser import HTMLParser
from typing import Optional, Union
#... |
from django.shortcuts import render
from principal.models import *
# Create your views here.
def index(request):
# View code here...
return render(
request,
'principal/index.html',
{
"ciudad_inicio":Ciudad.objects.all().first(),
"ciudades":Ciudad.objects.all()
}
) |
import os
from flask import Flask
from dotenv import load_dotenv
from .models import DB, init_db
from .routes import airbnb_routes
load_dotenv()
DB_FILEPATH = os.path.join(os.path.dirname(__file__), 'db.sqlite3')
DB_URI = f'sqlite:////{DB_FILEPATH}' # using absolute filepath
def create_app():
app = Flask(__na... |
from django.shortcuts import render
from .models import Badge
from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions
from .serializers import BadgeSerializer
from .permissions import IsAdminOrReadOnly
class BadgesViewSet(ModelViewSet):
"""Users badges viewset"""
queryset = Bad... |
# -*- coding: utf-8 -*-
# @Author : monleylu
# @Time : 2018/7/12 3:00 PM
from TestCaseResult import TestCaseResult, TypeEnum
import time
class UiTestCaseResult(TestCaseResult):
'''
UI自动化测试结果
'''
def __init__(self, success=False, msg=None, data=None, testcaseid=0, testcasename="defaultTestCaseName... |
import multiprocessing as mp
import time
from ucp._libs import ucx_api
from ucp._libs.arr import Array
mp = mp.get_context("spawn")
def blocking_handler(request, exception, finished):
assert exception is None
finished[0] = True
def blocking_send(worker, ep, msg, tag=0):
msg = Array(msg)
finished =... |
import os
import sys
import pytest
from montreal_forced_aligner.command_line.mfa import parser
from montreal_forced_aligner.command_line.transcribe import run_transcribe_corpus
def test_transcribe(
basic_corpus_dir,
sick_dict_path,
english_acoustic_model,
generated_dir,
transcription_acoustic_mo... |
from selenium import webdriver
browser = webdriver.Chrome("C:\\Users\\Odysseus\\Downloads\\chromedriver.exe")
browser.get('http://localhost:8000')
assert 'Django' in browser.title
browser.quit |
/home/runner/.cache/pip/pool/54/20/8b/49a8c068563eb99d8ad1b77d7d944eeed1eb128a4ba310f6bc1fb30b80 |
"""
MIT License
Copyright (c) 2020 Silas Hayes-Williams
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, p... |
#!/usr/bin/env python
# coding: utf-8
# In[297]:
import pandas as pd
import numpy as np
import wikipediaapi
wiki_wiki = wikipediaapi.Wikipedia('en')
import urllib.request as urllib2
import time
from datetime import datetime
import json
from urllib.parse import urlencode, quote_plus
import matplotlib.pyplot as plt
im... |
# Copyright (c) 2019 NVIDIA Corporation
import os
import subprocess
import sys
import time
from shutil import copyfile
from nemo.utils import logging
from nemo.utils.decorators import deprecated
# logging = nemo.logging
@deprecated(
version=0.11,
explanation=(
"Please use nemo.logging instead by usin... |
#!/usr/bin/env python
import pandas as pd
import numpy as np
import re
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.model_selection import KFold, LeaveOneOut, GridSearchCV
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import r2_score
from sequencing_tools.viz_tools import... |
from starlette.testclient import TestClient
def test_route(client: TestClient) -> None:
"""Test `rsserpent_plugin_jam.route`."""
response = client.get("/jam")
assert response.status_code == 200
assert response.headers["Content-Type"] == "application/xml"
assert response.text.count("Example Title")... |
import numpy as np
import pandas as pd
from pprint import pprint
dataset = pd.read_csv('/content/drive/MyDrive/zoo.csv',
names=['hair','feathers','eggs','milk',
'airbone','aquatic','predator','toothed','backbone',
... |
from moabim.lib import Location
DARKSKY_API_KEY = 'xxx'
#DigitalOcean Spaces Keys go here
ACCESS_ID = ''
SECRET_KEY = ''
IMAGE_LOCATIONS = [
Location(resource_url='url goes here',
lat='40.573315',
lon='-120.549843',
overlay_weather=True,
overlay_title=True,
... |
from django.apps import apps
from django.core.management import BaseCommand
from conf import settings
from dataservices.models import Country
from .helpers import flatten_ordered_dict, from_url_get_xml
class Command(BaseCommand):
help = 'Import data from world bank'
loader_info = {
'consumerpricein... |
import pytest
import torch
from torch.autograd import gradcheck, gradgradcheck
class TestFusedBiasLeakyReLU(object):
@classmethod
def setup_class(cls):
if not torch.cuda.is_available():
return
cls.input_tensor = torch.randn((2, 2, 2, 2), requires_grad=True).cuda()
cls.bias... |
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import PySimpleGUI as sg
import matplotlib
matplotlib.use('TkAgg')
"""
Demonstrates one way of embedding Matplotlib figures into a PySimpleGUI window.
Basic steps are:
* Create a Canvas Element
* Layout... |
# -*- coding: utf-8 -*-
"""
Interpolated Model
------------------
Model interpolated from some surrogate model
"""
import numpy as np
import os
from scipy import interpolate
from sklearn.gaussian_process import GaussianProcessRegressor
from .model import model_base
class interpolated(model_base):
def __init__(sel... |
import os
from libraries import disparity
FRAMES_DIR = './example_frames'
SPLIT_FRAMES_DIR = './splitted'
DISPARITY_MAPS_DIR = './disparity_maps3'
frames = os.listdir(FRAMES_DIR)
for frame in frames:
print(frame)
left_file = os.path.join(SPLIT_FRAMES_DIR, f'l_{frame}')
right_file = os.path.join(SPLIT_FRA... |
import logging
from bson.objectid import ObjectId
from pymongo import ReturnDocument
from core.config import (
DOCTYPE_USER as DOCUMENT_TYPE,
ERROR_MONGODB_DELETE,
ERROR_MONGODB_UPDATE,
)
from core.security import get_password_hash
from db.mongo import get_collection
from models.user import (
BaseModel... |
import os
import argparse
if __name__=="__main__":
# args
parser=argparse.ArgumentParser()
parser.add_argument('--no_cuda',action='store_true',default=True,help='Disables CUDA training.')
parser.add_argument('--dataset',type=str,default='data',help='Dataset name.')
parser.add_argument('--mpn',type=... |
from . import Adapter
import serial
import time
import RPi.GPIO as GPIO
SERIAL_HANDLE_FILE = "/dev/ttyAMA0"
class RPiAdapter(Adapter):
def __init__(self, reset_pin):
"""
Initializes a serial port connection from a Raspberry Pi.
:param reset_pin: Pin that the reset port of the externa... |
import re
from functools import cached_property
from pathlib import Path
from typing import List, Optional, Sequence, Union
import albumentations
import cv2
import numpy as np
import tifffile
from ..base import Dataset
from ..types import BundledPath
from ..utils import bundle_list, stack_channels_to_rgb
class BBBC... |
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Copyright 2013 California Institute of Technology. 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 th... |
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 CEA
# Pierre Raybaut
# Licensed under the terms of the CECILL License
# (see guiqwt/__init__.py for details)
"""Curve fitting tools"""
from __future__ import print_function
SHOW = True # Show test in GUI-based test launcher
import numpy as np
from guiqwt.widgets.fi... |
"""
Production Django settings for chp_api project.
"""
from .base import *
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = int(os.environ.get("DEBUG", default=0))
ALLOWED_HOSTS = o... |
#!/usr/bin/env python
import transaction
import ZODB, ZODB.FileStorage
from ZODB.PersistentMapping import PersistentMapping
from ZODB.PersistentList import PersistentList
from optparse import OptionParser
import os
import sys
import re
import codecs
def depth_first_deep_copy(src, dst, key = None) :
if key is None... |
import os
import logging
import logging.handlers
from flask import Flask
from flask_bootstrap import Bootstrap
UPLOAD_FOLDER = os.getcwd() + '/flaskr/uploads'
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
# enable Bootstrap
Boo... |
"""
Setup a python virtual environment with pip and install the dependencies from lib/
"""
import venv
from pathlib import Path
import subprocess
import os
print("Installing virtual environment...")
venv.create("venv", with_pip=True) # create venv in venv/ dir
# find python bin path
bin_dir = Path(Path(__file__).pa... |
# coding=utf-8
"""
Use [Elasticsearch] cluster (https://www.elastic.co/products/elasticsearch)
using bulk / msearch / update API.
Require python Elastic client 'elasticsearch' (Pypi)
### Setup
Elasticsearch templates (will be pushed by tantale) :
* STATUS INDEX : status.template
* LOGS INDEX : status_logs.temp... |
from django.urls import include, path, re_path
from .views import (MessageCreateAPIView)
urlpatterns = [
path('create/message', MessageCreateAPIView.as_view()),
] |
from .sampler import *
from .twogaussian import *
from .polyfit import * |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import random
import copy
import uuid
import scipy.stats as stat
from math import log, gamma, exp, factorial, pi, sqrt, erf, atan
from scipy.special import gammainc
from scipy.interpolate import interp1d
import os,sys
def Exponential_rate(t,rat... |
import torch
import torch.nn as nn
def grad(outputs, inputs):
""" compute the derivative of outputs associated with inputs
Params
======
outputs: (N, 1) tensor
inputs: (N, D) tensor
"""
return torch.autograd.grad(outputs, inputs,
grad_outputs=torch.ones_like(... |
__MAJOR__ = 0
__MINOR__ = 2
__MICRO__ = 0
__VERSION__ = (__MAJOR__, __MINOR__, __MICRO__)
__version__ = '.'.join(str(n) for n in __VERSION__)
__github_url__ = 'http://github.com/JWKennington/apsjournals'
from apsjournals.journals import PRL, PRM, PRA, PRB, PRC, PRD, PRE, PRX, PRAB, PRApplied, PRFluids, PRMaterials, P... |
#!/usr/bin/env python3
class Node:
def __init__(self, data: int):
self.data = data
self.next_node = None
class LinkedList:
def __init__(self, data: list):
self.head = None
for item in data:
if self.head == None:
self.head = Node(item)
e... |
import unittest
from paraview import simple
from paraview import servermanager
class TestSimpleModule(unittest.TestCase):
def setUp(self):
self.pxm = servermanager.ProxyManager()
def test_RenameSource(self):
source = simple.Sphere(guiName='oldName')
simple.SetActiveSource(source)
... |
from rlberry.agents.ppo import PPOAgent
from rlberry.envs.benchmarks.ball_exploration import PBall2D
from rlberry.seeding import seeding
from rlberry.stats import AgentStats, plot_episode_rewards, compare_policies
seeding.set_global_seed(1223)
env = PBall2D()
n_episodes = 400
horizon = 100
ppo_params = {}
ppo_param... |
import re
def regexp_flags(regexp_modifier=None):
flags = 0
set_unicode = True
for c in regexp_modifier:
if c == 'b':
# Treat strings as binary octets rather than UTF-8 characters.
set_unicode = False
elif c == 'c':
# Forces the match to be case sensitive... |
# Copyright (c) 2021 PaddlePaddle 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 applic... |
import pandas
import numpy
import matplotlib.pyplot as plt
from Program.Common import *
import matplotlib.dates as mdates
import mpl_finance
import matplotlib.ticker as ticker
from CommonDef.DefStr import *
from numpy import NaN
from Statistics_TechIndicators.CalcTechIndictors import *
from pandas.tests.frame.test_va... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__author__ = 'ontheway'
#iVMS-4200 v2.0 log file include
'''
海康威视IVMS系列2.0 日志文件包含getshell
'''
import re
def assign(service, arg):
if service == "DVRDVS-Webs":
return True, arg
def audit(arg):
url = arg
exp1 = "\"" + url + "/<?... |
# 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, software
# distributed under the... |
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
smaller = ListNode(0)
smaller_star... |
# Spider: A Spider in the game. The most basic unit.
# DO NOT MODIFY THIS FILE
# Never try to directly create an instance of this class, or modify its member variables.
# Instead, you should only be reading its variables and calling its functions.
from games.spiders.game_object import GameObject
# <<-- Creer-Merge: ... |
# -*- coding: utf-8 -*-
"""
Create a socket file in the Linux system
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2019 by rgb-24bit.
:license: MIT, see LICENSE for more details.
"""
import argparse
import os
import socket
DESCRIPTION = 'Create a socket file in the Linux system'
VERSION ... |
#!/usr/bin/env python
import os
import sys
from setuptools import setup
# version of dbs-client, should match current DBS release tag
package_version = "3.7.8"
# Requirements file for pip dependencies
requirements = "requirements.txt"
def parse_requirements(requirements_file):
"""
Create a list for the... |
import numpy as np
from matplotlib import pyplot as plt
from numpy import ndarray
from scipy.linalg import svd
def explained_var(Σ: ndarray) -> ndarray:
ΣΣ: ndarray = Σ * Σ
return ΣΣ / ΣΣ.sum()
def plot_explained_variance(ρ: ndarray, threshold = 0.9, save_to_file: str = ""):
plot_range = range(1, len(ρ) + 1)
f = ... |
import asyncio
import msgpack
import logging
from msgpackio.rpc import REQUEST, NOTIFY, RESPONSE
from msgpackio.exceptions import RemoteException, NoMethod
log = logging.getLogger(__name__)
class Bindings:
def __init__(self, obj, kwargs):
self.obj = obj
self.dict = kwargs
def get(self, item... |
r"""Functions for creating quizzes for Blackboard, to be uploaded as text files.
AUTHORS:
- Emmanuel Briand (2021): initial version
The function ``write_bbtextpool`` writes a text file than can be uploaded in Blackboard Learn (ORIGINAL course view) as indicated in Blackboard\'s help pages on "`Upload Questions
<http... |
from django.conf.urls import patterns, url
from sfa_score.views import IndexTemplateView, ManageTemplateView
from sfa_score.models import Agegroup, Grade, Discipline, Pupil, Score
urlpatterns = patterns('sfa_score.views',
#url(r'^$', direct_to_template, {'template': 'sfa_score/index.html', 'extra_context': {'grou... |
import hashlib
def hash_txn(txn):
string_attrs = ['isoformat', 'description', 'original_description',
'transaction_type', 'category', 'account_name']
float_attrs = ['amount']
m = hashlib.sha256()
for attr in string_attrs:
value = getattr(txn, attr, None)
if value:
... |
import os
import numpy as np
import proto.explanation_pb2 as expl_pb
reward_block_spec = {}
reward_block_spec['all'] = [0,0]
reward_block_spec['damageToWeakEnemyGroup'] = [0,1]
reward_block_spec['destoryToWeakEnemyGroup'] = [0,2]
reward_block_spec['damageToStrongEnemyGroup'] = [1,0]
reward_block_spec['destoryToStrong... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.