content stringlengths 5 1.05M |
|---|
from builtins import print
import numpy as np
import pandas as pd
import matplotlib
import random
matplotlib.use('agg')
import matplotlib.pyplot as plt
matplotlib.rcParams['font.family'] = 'sans-serif'
matplotlib.rcParams['font.sans-serif'] = 'Arial'
import os
from sklearn.metrics import accuracy_score
from sklearn... |
import math
import gmpy2
# How many you want to find
MAX_COUNT = 500
K_COUNT = 3.7 # d = 1000 yields ~264
#for parallel C++
K_COST = 4.14 * 1e-11 # d = 5000 takes ~400s
K_FILTER_COST = 1.0 * 1e-9 # d = 5000, sieve = 30M takes 10.3s
def optimal_sieve(d, expected_cost):
non_trivial_a_b = d * 2... |
import logging
from django.test import TestCase
from rest_framework.request import Request
from django_drf_filepond.uploaders import FilepondStandardFileUploader
from rest_framework.exceptions import ParseError
from django.core.files.uploadedfile import InMemoryUploadedFile
from django_drf_filepond.utils import _get_... |
import torch
from utils.rnns import (mean_pooling,
max_pooling,
gather_last)
import torch.nn as nn
from torch.nn import LSTM, LSTMCell, Linear, Parameter
class MeanPoolingLayer(torch.nn.Module):
def __init__(self):
super(MeanPoolingLayer, self).__init__()
def ... |
# © its-leo-bitch
from bot import bot
from bot.utils import langs, lang_names
from pyrogram import types, errors
from piston import Piston
import asyncio
import time
piston = Piston()
execute = {}
NEXT_OFFSET = 25
@bot.on_inline_query()
async def inline_exec(client, query):
string = query.query
offset = in... |
import pyrebase
import json
class DataBase:
def __init__(self):
config = json.load(open("config.json"))
firebase = pyrebase.initialize_app(config["database"])
auth = firebase.auth()
login = config["login"]
self.user = auth.sign_in_with_email_and_password(login["us... |
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
s, e = 0, len(nums) - 1
while True:
if target <= nums[s]:
return s
if target == nums[e]:
return e
if target > nums[e]:
... |
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.optim as optim
import torch.distributions
from torch.autograd import Variable
from collections import namedtuple
import random
from gym import wrappers
import os
import pickle
CUDA = torch.cuda.is_available()
print('CUDA has been... |
# -*- coding: utf-8 -*-
#from django.conf import settings # @Reimport
from django.contrib import messages
from .. import models
from . import import_base
from .. import utils
class Csv_unicode_reader_titre(utils.Csv_unicode_reader):
"""obligatoire : cpt date titre nombre cours"""
@property
def comp... |
import xml.dom.minidom
import typeMapper
class adiosConfig:
def __init__ (self, config_file_name):
self.config_file_name = config_file_name
#This would be a good time to parse the file...
doc = xml.dom.minidom.parse (config_file_name)
nodes = doc.childNodes
if (nodes.len... |
import os
import networkx as nx
import numpy as np
import scipy as scp
from pgmpy.factors.discrete import TabularCPD
from pgmpy.models import BayesianModel
import re
import itertools
from peepo.playground.simple_color_recognition.CeePeeDees import CPD
class Lattices(object):
def __init__(self,utility_pointer):
... |
from .tool.func import *
def main_func_setting_main(db_set):
with get_db_connect() as conn:
curs = conn.cursor()
if admin_check() != 1:
return re_error('/ban')
setting_list = {
0 : ['name', 'Wiki'],
2 : ['frontpage', 'FrontPage'],
4 ... |
from django.test import TestCase
from .models import Pic,Location,Category
import datetime as dt
# Create your tests here.
class Test_Location(TestCase):
def setUp(self):
self.location=Location(name="location")
def test_instance(self):
self.assertTrue(isinstance(self.location,... |
from pyri.parameters import YamlParameterGroup, YamlGroupInfoWithSchema
from pyri.parameters.yaml import _group_info_schema, _load_group_info
import pkg_resources
import os
import pytest
import yaml
@pytest.mark.asyncio
async def test_yaml_parameter_group(tmpdir):
fname1 = os.path.join(tmpdir,"empty_params.yml")
... |
from __future__ import absolute_import, unicode_literals
import codecs
import logging
import os
import re
import urllib
import urlparse
from mopidy import compat
from mopidy.internal import encoding, path
from mopidy.models import Track
M3U_EXTINF_RE = re.compile(r'#EXTINF:(-1|\d+),(.*)')
logger = logging.getLogge... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#############################################################################
## ##
## This file is part of Disass ##
## ... |
import csv
from termcolor import colored
class Room:
"""Organizes and manipulates rooms."""
def __init__(self, config):
self.visits = 0
self.config = None
self.label = None
self.verbose_description = None
self.terse_description = None
self.items = None
... |
# -*- coding: utf-8 -*-
"""Top-level package for predeval."""
__author__ = """Dan Vatterott"""
__email__ = 'dvatterott@gmail.com'
__version__ = '0.0.10'
from .continuous import ContinuousEvaluator
from .categorical import CategoricalEvaluator
from .utilities import evaluate_tests
__all__ = ['ContinuousEvaluator',
... |
from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl
import sys
import cgi
import base64
import tensorflow as tf
import keras
import numpy as np
import imghdr
import io
import hashlib
# simple mitigation to validate model file wasn't tampered
model_hash = "681226449b772fa06ec87c44b9dae724c69530d5d46d... |
import cubic_spline_interpolation
import matplotlib.pyplot as plt
import numpy as np
import sys
filename_measurements = '20160810-0955_measurements_CNN0a.dat'
filename_result = '20160810-0955_result_CNN0a.dat'
filename_measurements = '20160811-1459_measurements_CNN0a.dat'
filename_result = '20160811-1459_res... |
import RPi.GPIO as GPIO
import time
ledPin = 12
blinkDelay = .5
ledOn = True
GPIO.setmode(GPIO.BOARD)
GPIO.setup(ledPin, GPIO.OUT)
try:
while True:
print("led=" + str(ledOn))
GPIO.output(ledPin, ledOn)
ledOn = not ledOn
time.sleep(blinkDelay)
except:
GPIO.cleanup()
print("Th... |
import sys
import require
from fullscreen import maximize_console
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
maximize_console()
if not require.require(['sele... |
infile=open('cloudin.txt','r').readlines()
n,k=map(int,infile[0].split())
list1=[0,int(infile[1])]
for i in range(1,n-1):
list1.append(list1[i]+int(infile[i+1]))
answer=10000000000000
for i in range(n-k):
answer=min(answer,list1[i+k]-list1[i])
outfile=open('cloudout.txt','w')
outfile.write(str(answer))... |
from collections import namedtuple
import glob
import os
from typing import Dict, List, Tuple
import numpy as np
import onnx
import onnx.backend.test.runner as onnx_runner
import onnx.backend.test.loader as test_loader
from onnx import numpy_helper
OnnxTestData = namedtuple('OnnxTestData', ['inputs', 'outputs'])
Onnx... |
instructions = [ 1, 2, 3, "+", "+" ]
stack = []
for instruction in instructions:
if instruction == "+":
x = stack.pop()
y = stack.pop()
stack.append(x + y) # Push the result
else:
stack.append(instruction) # This is just a number
print(stack) |
from flaskext.mysql import MySQL
import datetime
import time
def historialViajesCliente(idCliente, cursor):
query = "SELECT p.nombre, v.Id_viaje, v.Origen, v.Destino, v.FechaYHora, v.Costo FROM Viaje v JOIN Taxi t ON v.Id_taxi = t.Id_taxi JOIN Persona p ON t.Id_taxista = p.id_persona WHERE v.Id_cliente = " + idClien... |
"""
Coadd spectra
"""
from __future__ import absolute_import, division, print_function
import os, sys, time
import numpy as np
import scipy.sparse
import scipy.linalg
import scipy.sparse.linalg
from astropy.table import Column
# for debugging
import astropy.io.fits as pyfits
import multiprocessing
from desiutil.... |
# 4.3.2 ポアソン混合分布における推論:ギブスサンプリング
#%%
# 4.3.2項で利用するライブラリ
import numpy as np
from scipy.stats import poisson, gamma # ポアソン分布, ガンマ分布
import matplotlib.pyplot as plt
#%%
## 観測モデル(ポアソン混合分布)の設定
# 真のパラメータを指定
lambda_truth_k = np.array([10, 25, 40])
# 真の混合比率を指定
pi_truth_k = np.array([0.35, 0.25, 0.4])
# クラスタ数を取得
K = len... |
class UnrecognizedCommandException(Exception):
"""When the text passed doesn't resolve to an unambiguous command"""
pass
class CheaterException(Exception):
"""When someone tries to rate themselves"""
pass
|
import boto.ec2
import argparse
REGION = 'us-east-1'
parser = argparse.ArgumentParser(description='Return the public DNS name for an EC2 instance.')
parser.add_argument('-i', '--instance',
action='store', dest='instance_name')
args = parser.parse_args()
instance_name = args.instance_name
conn = b... |
# file test/localsettings.py.dist
#
# Copyright 2011 Emory University Libraries
#
# 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
#
... |
# Junio 5 del 2018
# Observar las siguientes paginas:
# 1. https://cambridgespark.com/content/tutorials/convolutional-neural-networks-with-keras/index.html
# 2. https://www.youtube.com/watch?v=FmpDIaiMIeA
# (Las dos se complementan, observar cambios)
# (Opcional) 3. https://cambridgespark.com/content/tutorials/deep-lea... |
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n % 2 != 0:
print ("Weird")
if (n % 2 == 0 and 2 <= n and 5 >= n):
print ("Not Weird")
if (n % 2 == 0 and 6 <= n and 20 >= n):
print ("Weird")
if (n % 2 == 0 and n > 20):
... |
# coding: spec
from photons_transport.targets.script import sender_wrapper, ScriptRunner
from photons_app.errors import PhotonsAppError, BadRunWithResults
from photons_app import helpers as hp
from delfick_project.norms import sb
from unittest import mock
import asyncio
import pytest
class Sem:
def __init__(se... |
A_23_01_8 = {0: {'A': 0.036, 'C': 0.017, 'E': 0.012, 'D': 0.004, 'G': 0.014, 'F': 0.053, 'I': 0.045, 'H': -0.031, 'K': -0.027, 'M': 0.014, 'L': 0.028, 'N': -0.002, 'Q': -0.03, 'P': -0.014, 'S': -0.012, 'R': -0.095, 'T': -0.008, 'W': -0.008, 'V': 0.027, 'Y': -0.024}, 1: {'A': 0.206, 'C': 0.032, 'E': 0.034, 'D': 0.003, '... |
#!/usr/bin/env python
import argparse
import os
import json
import yaml
try:
from metal_python.driver import Driver
from metal_python.api import MachineApi, ProjectApi
from metal_python import models
METAL_PYTHON_AVAILABLE = True
except ImportError:
METAL_PYTHON_AVAILABLE = False
ANSIBLE_CI_MANA... |
"""Calculate averaged vertical profiles of PV tracers
"""
import matplotlib.pyplot as plt
import iris.plot as iplt
from iris.analysis import VARIANCE
from irise import files, convert
from myscripts import datadir, plotdir
from myscripts.plot import linestyles, colors
def main():
filename = datadir + 'xjjhq/xjjhq... |
from blockcontainer.celery import app
import feedparser
from bs4 import BeautifulSoup
from .models import Feed
import time
import re
import datetime
# Russian Detector
def russian_detector(text):
return bool(re.search('[а-яА-Я]', text))
@app.task
def updateCoinScribble():
url = "https://coinscribble.com/fee... |
from pathlib import Path
from . import (
utils,
network,
learning,
encoding,
decision,
plotting,
)
ROOT_DIR = Path(__file__).parents[0].parents[0]
|
from yowsup.config.transforms.props import PropsTransform
class SerializeTransform(PropsTransform):
def __init__(self, serialize_map):
"""
{
"keystore": serializer
}
:param serialize_map:
:type serialize_map:
"""
transform_map = {}
rever... |
from django.contrib.auth.decorators import permission_required
from django.core.urlresolvers import reverse_lazy, reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from core.decorat... |
import datetime
from model.db_initializer import DbConnector
from settings import env_variables
import statistics_reader
from website_generator import WebsiteGenerator
week_end_date = datetime.datetime.now().replace(minute=0, second=0, microsecond=0, hour=0) - datetime.timedelta(days=1)
week_end_date = week_end_date ... |
"""
Collection of utility functions.
"""
import os
import logging
from logging.handlers import RotatingFileHandler
import glob
import time
import yaml
import ruamel.yaml
import codecs
from collections import OrderedDict
import nd2reader as nd2
import numpy as np
from skimage import img_as_float
import platform
####... |
from flask_caching.backends.base import BaseCache
from pyrindow.stdlib.lrucache import LruCache as rindowCache
def lrucache(app, config, args, kwargs):
kwargs.update(
dict(
cache_driver=app.config['serviceLocator'].get('flask_caching.cacheDriver'),
)
)
return LRUCache(**kwargs)
... |
from nlp_articles.app.nlp import init_nlp
# test with -s
# pytest /workspaces/fin_news_nlp/nlp_articles/app/tests/test_nlp_dec2021_fix.py -s
def test_parsing_article():
nlp = init_nlp("core/data/exchanges.tsv","core/data/indicies.tsv")
text = '''
The worst-performing tech stocks this week suggest the U.S. ... |
# commnet
print('Hello World!') |
from sklearn.ensemble import RandomForestRegressor
from utils.logger import App_Logger
from utils.model_utils import Model_Utils
from utils.read_params import read_params
from xgboost import XGBRegressor
class Model_Finder:
"""
Description : This class shall be used to find the model with best accuracy and... |
"""Funcionality for representing a physical variable in aospy."""
import numpy as np
class Var(object):
"""An object representing a physical quantity to be computed.
Attributes
----------
name : str
The variable's name
alt_names : tuple of strings
All other names that the variable... |
"""普通に書いたやつ。TLE"""
import numpy as np
import math
N, Q = [int(a) for a in input().split()]
symbol = input()
target = [None]*Q
direction = [None]*Q
num_golems = [1]*N
num_golems_next = [1]*N
for i in range(Q):
line = input().split()
target[i] = line[0]
direction[i] = line[1]
for i in range(Q):
f... |
def join_path(uri, resource_path):
return '{}{}'.format(uri, resource_path) if resource_path else uri
def filter_dict_by_key(d: dict):
return {k: v for k, v in d.items() if v}
|
# coding=utf-8
"""
@Time : 2020/12/26 0:17
@Author : Haojun Gao (github.com/VincentGaoHJ)
@Email : vincentgaohj@gmail.com haojun.gao@u.nus.edu
@Sketch :
"""
import os
import pickle
import numpy as np
import scipy.sparse as sp
from src.NextPOI import next_poi
from src.func.matrix_manipulation import normalize
fro... |
def meters(x):
|
"""
LDAP Authenticator plugin for JupyterHub
"""
# MIT License
#
# Copyright (c) 2018 Ryan Hansohn
#
# 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 li... |
# -*- coding:utf-8 -*-
# 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 "Lice... |
from BaseHTTPServer import *
from cherrypy._cphttpserver import CherryHTTPServer
from contrib.quixote.server.simple_server import HTTPRequestHandler
from threading import Thread,Event
class HTTPServerPlus(CherryHTTPServer, Thread):
def __init__(self, **kwargs):
CherryHTTPServer.__init__(self,**kwargs)... |
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(Fals... |
import sys
import torch
from URSABench.util import get_loss_criterion
if 'hamiltorch' not in sys.modules:
print('You have not imported the hamiltorch module,\nrun: pip install git+https://github.com/AdamCobb/hamiltorch')
# TODO: Add docstrings for classes below.
class _Inference:
""" Base class of inferenc... |
from django.urls import path
from dataworkspace.apps.accounts.utils import login_required
from dataworkspace.apps.your_files.views import (
CreateSchemaView,
CreateTableConfirmDataTypesView,
CreateTableCreatingTableView,
CreateTableFailedView,
CreateTableIngestingView,
CreateTableRenamingTableV... |
import xml.etree.ElementTree as ET
xmlfile = 'output.xml'
root = ET.parse(xmlfile).getroot()
stat = root.find('./statistics/total/stat')
fail_count = int(stat.get('fail'))
if fail_count > 0:
raise AssertionError('{} Robot Test Failures Detected!'.format(fail_count))
|
from yt.testing import \
fake_amr_ds, \
assert_array_equal
import numpy as np
# We use morton indices in this test because they are single floating point
# values that uniquely identify each cell. That's a convenient way to compare
# inclusion in set operations, since there are no duplicates.
def test_boolea... |
# Copyright 2018, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
from pyppl import ProcSet
from bioprocs.common import pStr2File, pFile2Proc, pSort
from bioprocs.tsv import pTsvJoin
from bioprocs.seq import pPromoters, pConsv, pConsvPerm
from bioprocs.bed import pBedGetfasta
from bioprocs.tfbs import pMotifScan
from bioprocs import params
"""
@name:
aTfbsTfP
@description:
Scan mo... |
import argparse, sys
import numpy as np
from PIL import Image
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from transform import random_transform_generator
from dataset import SEMDataset
from modules import *
... |
import socket
socket.setdefaulttimeout(.5)
print('\n'+ '#'*50+'\n Started Executing Script'+ '\n'+ '#'*50)
def port_check(ip,port):
DEVICE_SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result_of_check = DEVICE_SOCKET.connect_ex((ip,port))
if result_of_check == 0:
print(str(ip)+ ' is... |
"""
*Evaluated*
The outcome of evaluating a player against a baseline player.
"""
from dataclsses import dataclass
@dataclass
class Evaluated:
name: str
average_energy: f64
redundancy: f64
energies: Vector[f64]
baseline_rewards :: Union{Nothing, Vector{Float64}}
runtime: float
"""... |
# Generated by Django 2.2.13 on 2020-06-09 14:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cms', '0003_auto_20200507_1739'),
]
operations = [
migrations.AlterModelOptions(
name='contentpage',
options={'verbose_name... |
import os
import cma
import pickle
import time
import numpy as np
from multiprocessing import Pool
from skate_cma.skate_env2 import SkateDartEnv
from skate_cma.PenaltyType import PenaltyType
def f(x):
env = SkateDartEnv(x[0])
x0 = x[2]
q0 = x[3]
dq0 = x[4]
duration0, duration1 = x[5], x[6]
op... |
from argparse import ArgumentParser
import torch
from typing import List, Dict, Tuple
from .fine_tune import get_pretrained_model
def decode(sample: torch.Tensor, id_to_label: Dict[int, str], ignore_index: List[int]) -> List[str]:
return [id_to_label[i.item()] for i in sample if i.item() not in ignore_index]
... |
#--------------------------------------------------------------------------------
# Authors:
# - Yik Lung Pang: y.l.pang@qmul.ac.uk
# - Alessio Xompero: a.xompero@qmul.ac.uk
#
# MIT License
# Copyright (c) 2021 CORSMAL
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this softw... |
for i in range(1, 13):
print("No. {0:2} squared is {1:4} and cubed is {2:4}".format(i, i ** 2, i ** 3))
# it means it will take these many columns
print()
# left aligning
for i in range(1, 13):
print("No. {0:2} squared is {1:<4} and cubed is {2:<4}".format(i, i ** 2, i ** 3))
print()
# center aligning
for i i... |
# -*- coding: utf-8 -*-
__author__ = 'joko'
"""
@author:joko
@time: 16/11/16 上午10:48
"""
import lib.Utils as U
import GetFilePath
@U.l()
def case_yaml_file():
"""
:return: 返回当前设备下的yaml test case列表
"""
ini = U.ConfigIni()
yaml_path = ini.get_ini('test_case', 'case')
return GetFilePath.all_fil... |
__author__="congcong wang"
import pickle
import shutil
import time
from sklearn.metrics.pairwise import cosine_similarity
from sentence_transformers import SentenceTransformer
from tqdm import tqdm
import nltk
import os
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=loggin... |
from .mnist import *
from .cifar import *
from .imagenet import *
def load_dataset(name: str, input_node: str, label_node: str, *args, **kwargs):
name = name.strip().lower()
g = globals()
options = [n[5:] for n in g if n.startswith('load_') and n != 'load_dataset']
if name not in options:
rais... |
from django.conf import settings
from django.conf.urls import url
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from django.views.generic import TemplateView
from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView
from formidab... |
def MatchingLine_IEEE39(num1, num2):
import Excel
value = '0'
data = Excel.read_excel('IEEE39_Parameters.xlsx', 'Line Parameters', 3, 48, 2, 4, 1.0)
if num1 == '01' and num2 == '01' :
value = '1'
if num1 == '02' and num2 == '39' :
value = '2'
if num1 == '39' and num2... |
# app/auth/__init__.py
"""
This init file creates a blueprint for the authentication routes of the application
"""
from flask import Blueprint
auth = Blueprint('auth', __name__)
from . import views
|
#
# Copyright (C) 2009 - 2019 Isotropix SAS. All rights reserved.
#
# The information in this file is provided for the exclusive use of
# the software licensees of Isotropix. Contents of this file may not
# be distributed, copied or duplicated in any form, in whole or in
# part, without the prior written permission of ... |
"""Application factory for accounts app."""
from flask import Flask
from flask_s3 import FlaskS3
from arxiv import vault
from arxiv.base import Base
from arxiv.base.middleware import wrap
from arxiv.users import auth
from accounts.routes import ui
from accounts.services import SessionStore, legacy, users
s3 = Flask... |
import configparser
import requests
# TODO: don't hardcode config file
config = configparser.ConfigParser()
config.read('etc/delaphone.ini')
def routesms_send(destination, message):
url = config['sms']['url']
params = {
"username": config['sms']['username'],
"password": config['sms']['... |
# coding: utf-8
# In[2]:
'''
Statistical Computing for Scientists and Engineers
Homework 4 Problem 3 b1
Fall 2018
University of Notre Dame
'''
import numpy as np
import matplotlib.pyplot as plt
import math
import scipy.stats
# the true distribution
def f(v):
return scipy.stats.gamma.pdf(v,a=4.3,scale=1/6.2)
# ... |
from messy2sql.core import Messy2SQL, MESSYTABLES_TO_SQL_DIALECT_MAPPING |
from .shell import ShellSubcommand |
# Reference: https://chrisalbon.com/python/basics/set_the_color_of_a_matplotlib/
# Reference: http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
import matplotlib.pyplot as plt
import numpy as np
n = 100
r = 2 * np.random.rand(n)
theta = 2 * np.pi * np.random.rand(n)
area = 200 * r ** 2 * np.random.rand(n)
colo... |
from django.views.generic.dates import ArchiveIndexView, YearArchiveView, MonthArchiveView, DayArchiveView, DateDetailView
from easyblog import settings
from easyblog.models import Post
class PostArchiveIndexView(ArchiveIndexView):
def get_context_data(self, **kwargs):
# Call the base implementation first... |
from .aleph import Aleph |
"""
Tutorial
==============================================================================
**hardDecisions** is library for representing and evaluating decision trees.
.. image:: ./images/tree_example.png
:width: 550px
:align: center
>>> from hardDecisions.decisiontree import *
>>> tree = DecisionTree()
... |
# Log Parser for RTI Connext.
#
# Copyright 2016 Real-Time Innovations, 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
#
# ... |
# Write your solution here
def column_correct(sudoku: list, column_no: int):
list1 = []
list2 = []
for row in sudoku:
if row[column_no] not in list1 and row[column_no] != 0:
list1.append(row[column_no])
if row[column_no] != 0:
list2.append(column_no)
if len(list1)... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.MainPage, name='Home'),
path('withdrawl/', views.withdrawlPage, name='withdrawl'),
path('createUser/', views.createUser, name='createAnAccount'),
path('afterSignIn/', views.afterSignIn, name='afterSignIn')
] |
""" Game fix for You Need a Budget 4
"""
#pylint: disable=C0103
from protonfixes import util
def main():
""" Installs corefonts
"""
# https://github.com/ValveSoftware/Proton/issues/7
util.protontricks('corefonts')
|
# -*- coding: utf8 -*-
PROG_NAME = "IIDADA"
VERSION = "v0.2"
if __name__ == '__main__':
print("{} version: {}".format(PROG_NAME, VERSION))
|
import numpy as np
import copy
import gym
import torch
import plotly.graph_objs as go
import plotly.io as pio
import cv2
from nsrl.base_classes import Environment
from nsrl.helper.pytorch import device
from nsrl.helper.gym_env import StepMonitor, PickleableEnv
import matplotlib.pyplot as plt
class MyEnv(Environment)... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# usage:
"""
"""
import csv
import os
import os.path
import pandas as pd
import sys
def main():
load_path1 = ""
load_path2 = ""
save_path = "merged.csv"
if len(sys.argv) > 1:
# 引数解析
i = 1
while i < len(sys.argv):
s = s... |
from .base import CPObject, TextField, ObjectField
from .domestic import Domestic
from .address_details import AddressDetails
class Destination(CPObject):
_name = 'destination'
_fields = {
# NonContractShipping
"name": TextField("name"),
"company": TextField("company"),
"addit... |
from graphql import GraphQLError
class ErrorHandler():
'''Raise errors'''
def check_conflict(self, model, field, value, error_type=None):
# Database integrity error
message = f'{model} with {field} {value}, already exists!'
if error_type is not None:
raise error_type({'err... |
from setuptools import setup, find_packages
from hcli import __version__
with open('README.md') as file:
long_description = file.read()
setup(
name='hrot-cli-tools',
version=__version__,
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/J... |
# Created by Martin Strohalm, Thermo Fisher Scientific
# import module
import pyeds
# open result file using the 'with' statement
with pyeds.EDS("data.cdResult") as eds:
# get path (be careful while using this method as it only follows the graph, not data logic)
via = ["BestHitIonInstanceItem"]
path... |
squares = [1, 4, 9, 16, 25]
print squares[0]
print squares[0l]
print squares[-1]
print squares[-3:]
print squares[:]
print squares + [36, 49, 64, 81, 100]
squares.append(66);
print squares
print squares[1::2]
squares.__setitem__(0, 2)
squares.__delitem__(1)
print squares
print squares.__getitem__(0)
|
# std
from typing import Any, Container, Dict, Optional, Type
from uuid import UUID
# external
import sqlalchemy
from sqlalchemy import orm, sql
from sqlalchemy.dialects import postgresql
from sqlalchemy.inspection import inspect
from sqlalchemy.orm.properties import ColumnProperty
# Derived from from https://github.... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Arista Networks, Inc. All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.
"""
read env variables or use sensible defaults
"""
import os
ARCOMM_DEFAULT_PROTOCOL = 'eapi+http'
ARCOMM_DEFAULT_TIMEOUT = 30
ARCOMM_DEFAULT_USERNAME = 'admin'
ARCOMM_DEFA... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.