content stringlengths 5 1.05M |
|---|
# Generated by Django 3.1a1 on 2020-05-31 04:37
from django.db import migrations
import djstripe.enums
import djstripe.fields
class Migration(migrations.Migration):
dependencies = [
("djstripe", "0008_djstripepaymentmethod_type_width"),
]
operations = [
migrations.AlterField(
... |
from bisect import bisect_right
from utils import chunks
from six import iterkeys
class Node(object):
__last_ID = 0
def __init__(self):
self.ID = Node.__last_ID = Node.__last_ID + 1
@property
def is_leaf(self):
return isinstance(self, Leaf)
class InnerNode(Node):
def __init__(se... |
# -*- coding: utf-8 -*-
import os
try: # Try importing Python3 urllib
import urllib.request
except ImportError: # Now importing Python2 urllib
import urllib
def get_content(url):
try: # Using Python3 urllib.
with urllib.request.urlopen(url) as response:
return response.read() # Return... |
import pandas as pd
import numpy as np
import os
def read_data():
#set the path of the raw data
raw_data_path = os.path.join(os.path.pardir,'data','raw')
train_file_path = os.path.join(raw_data_path, 'train.csv')
test_file_path = os.path.join(raw_data_path, 'test.csv')
#read data with all default ... |
import os
from typing import Dict, List, Optional
import attr
from openlineage.constants import DEFAULT_PRODUCER
PRODUCER = os.getenv("MARQUEZ_PRODUCER", DEFAULT_PRODUCER)
SCHEMA_URI = "https://raw.githubusercontent.com/OpenLineage/OpenLineage/main/spec/OpenLineage.json"
@attr.s
class BaseFacet:
_producer: st... |
#
# Copyright (c) 2006-2016, Prometheus Research, LLC
#
from ....core.util import to_name
from ....core.adapter import adapt
from ....core.error import Error, act_guard
from ....core.connect import transaction
from ....core.domain import UntypedDomain, RecordDomain, Value, Product
from ....core.cmd.embed import Embed... |
#!/usr/bin/python
from Tkinter import *
from PIL import Image, ImageTk
import subprocess
import locale
import os
import time
import thread
from collections import deque
import paramiko
import memcache
# NUMS times WPT should be 600 for the scale to work out
NUMS = 200 # number of values to show in strip
WPT = 3 ... |
from aspi import AsPi, AsPiLogger
import time
import random
from pathlib import Path
SENSORS = [
AsPi.SENSOR_MOTION,
AsPi.SENSOR_LAT,
AsPi.SENSOR_LON,
AsPi.SENSOR_ECLIPSED,
AsPi.SENSOR_USERDATA
]
class DataProcessor:
def __init__(self):
self.imgcounter = 0
def process_data(se... |
# Copyright 2019 Huawei Technologies 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... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.flatpages.models import FlatPage
from django.test import TestCase
from django.test.utils import override_script_prefix
class FlatpageModelTests(TestCase):
def test_get_absolute_url_urlencodes(self):
pf = FlatPage(title=... |
import numpy as np
from tuner.maximizers.base_maximizer import BaseMaximizer
class GridSearch(BaseMaximizer):
def __init__(self, objective_function, lower, upper, resolution=1000):
"""
Evaluates a equally spaced grid to maximize the acquisition function
in a one dimensional input space.
... |
"""
Setup for compiling cache
Jonas Toft Arnfred, 2013-04-22
"""
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize(["cache.pyx", "fastmatch.pyx", "turntable_ground_truth.pyx"])
)
|
import time
import signal
import timeout_decorator
from contextlib import contextmanager
@contextmanager
def time_limit(seconds):
def signal_handler(signum, frame):
raise TimeoutError("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(seconds)
try:
yield
final... |
# pylint: disable=C0303, C0103
# Simplified batch manager
import multiprocessing
from collections import namedtuple
from time import sleep
from numpy import random
from pythia.X_to_tautau import generate_X_to_tautau
JobParams = namedtuple('JobParams',
['cmndfile', # path to Pythia command file
'ta... |
#Good morning! Here's your coding interview problem for today.
#
#This problem was asked by Stripe.
#
#Given an array of integers, find the first missing positive integer in linear time and constant space.
#In other words, find the lowest positive integer that does not exist in the array.
#The array can contain... |
import sys
import time
import datetime
class WError(Exception):
def __init__(self, errno, msg):
super().__init__(f"[Errno {errno}]: {msg}")
def hello_world():
print("Hello world!")
def exit():
sys.exit()
def time(time):
if time == "now" or time == 0:
return datetime.datetime.now()
... |
# -*- coding: utf-8 -*-
import os
from lithoxyl import (Logger,
StreamEmitter,
SensibleSink,
SensibleFilter,
SensibleFormatter)
from lithoxyl.sinks import DevDebugSink
# import lithoxyl; lithoxyl.get_context().enable_async()
ch... |
from posixpath import dirname
from flask import Flask, render_template, request, session, redirect, url_for, send_file
import os
import sys
import requests
from flask_paginate import Pagination, get_page_args #pip install flask-paginate
from datetime import timedelta
import json
import uuid
import base64
import redis
i... |
# Write a program to create a queue called Doctor to perform the
# basic operations on queue using list. The list contains two
# data fields: Docid and Docname. Write the following functions:
# InsertDoc() – To push the data values into the list Docinfo
# DeleteDoc() – To remove the data value from the list Docinfo
#... |
from setuptools import setup, find_packages
setup(
name='acs_student_attendance',
version='1.0.4',
url='https://github.com/petarmaric/acs_student_attendance',
license='BSD',
author='Petar Maric',
author_email='petarmaric@uns.ac.rs',
description='Console app and Python API for analyzing and... |
name=["Bill","Anne","Angy","Cony","Daniel","Occhan"]
for i in range(0,5):
if(name[i]!="Angy"):
print("{}.{} is my classmate".format(i+1,name[i]))
else:
print("{}.My name is {}".format(i+1,name[i]))
|
import sys
from aiohttp import web
from aio_recaptcha import Recaptcha
TEMPLATE = '''
<!DOCTYPE html>
<html lang="en">
<body>
<form action="/check" method="POST">
<p class="g-recaptcha" data-sitekey="{site_key}"></p>
<p>is verify: {is_verify}</p>
<button type="submit">check captcha</butt... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# __author__ = 'Benjamin'
import sys, os
import json
import requests
import random
import time
domain = 'redfish.blawesom.com'
lines = open('/usr/share/dict/words').read().splitlines()
new_name =random.choice(lines)
def test_root():
response = requests.get('ht... |
from flask import Flask, request, Response, redirect
# expected import error. API is run as a standalone from server.py
# noinspection PyUnresolvedReferences, PyPackageRequirements
from resources.keys import c, private_keys, idol_folder, top_gg_webhook_key, db_conn
# noinspection PyUnresolvedReferences, PyPackageRequi... |
"""
MagPy
Intermagnet ImagCDF input filter
(based on cdflib)
Written by Roman Leonhardt October 2019
- contains test, read and write functions for
ImagCDF
- supports python >= 3.5
- currently requires cdflib<=0.3.18
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future... |
#!/usr/bin/env python
import os.path
import curses
import time
import jobtracker
class File:
def __init__(self, name, size, status, update_time):
self.name = name
self.size = size
self.status = status
self.currsize = 0
self.currtime = time.time()
self.update()
... |
import unittest
import ramda as R
from ramda.private._curry3 import _curry3
from ramda.private._inspect import funcArgsLength
"""
https://github.com/ramda/ramda/blob/master/test/internal/_curry3.js
"""
def f(a, b, c): return [a, b, c]
g = _curry3(f)
class Test_Curry3(unittest.TestCase):
def test_supports_pla... |
import numpy as np
import torch
import torch.nn
import matplotlib.pyplot as plt
dtype = torch.float
device = torch.device("cpu")
# device = torch.device("cuda:0") # Uncomment this to run on GPU
schedule = [False, False, True]
########## Basic (FB prediction)
if schedule[0]:
N, D_in, D_out = 1, 5, 5
# Initia... |
"""
Created by Amor on 2018-09-22
"""
import xadmin
from .models import Fav, Comment, Reply, Like, Message, Dynamics
__author__ = '骆杨'
class FavAdmin(object):
model_icon = 'fa fa-star'
class CommentAdmin(object):
model_icon = 'fa fa-commenting'
class ReplyAdmin(object):
model_icon... |
import json
from django.core.paginator import PageNotAnInteger
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse,HttpResponse
# Create your views here.
from django.views.generic.base import View
from django_filters.rest_framework import DjangoFilterBackend
from pure_pagination... |
""" Abstracts the capturing and interfacing of applications """
import os
import re
import time
import pyperclip
import platform
import subprocess
from .RegionMatching import Region
from .SettingsDebug import Debug
if platform.system() == "Windows":
from .PlatformManagerWindows import PlatformManagerWindows
P... |
import pytest
from tests import strategies
from tests.utils import example
@pytest.fixture(scope='function')
def filtration_method() -> str:
return example(strategies.filtration_methods)
|
from django.db import models
from django_extensions.db.models import TimeStampedModel
# Create your models here.
class Link(TimeStampedModel):
url = models.URLField()
description = models.TextField(blank=True)
posted_by = models.ForeignKey(
to="hn_users.HNUser", null=True, on_delete=models.PROTECT... |
#Use to create local host
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
Handler.extensions_map.update({
".js": "application/javascript",
})
httpd = socketserver.TCPServer(("", PORT), Handler)
print(f"Starting server on http://localhost:{PORT}")
try:
ht... |
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
# python3 (3.6)
# Coded on iPad Pro 2020 4th Generation
# Pythonista an Apple iPad App
# MIT License Copyright (c) 2020 Rogelio Fiorenzano
#
# ITS320: Basic Programming
# Colorado State University Global
# Dr. Joseph Turano
# Option #1: String Values in Reverse Order
# Assignment Instructions
# Write a Python functi... |
#Printing stars in 'S' shape!
'''
***
*
*
***
*
*
***
'''
for row in range(7):
for col in range(5):
if(row==0 or row==3 or row==6) and (col>0 and col<4) or (col==0 and row>0 and row<3) or (col==4 and row>3 and row<6):
print('*', end='')
else:
print(end=' ')
pr... |
from . import core, plugins, utils
|
# encoding: utf-8
from __future__ import print_function
import os
from argparse import ArgumentParser
from websocket_server import start_server
from db import database
from models import __all__, User
import migrations
parser = ArgumentParser()
subparsers = parser.add_subparsers()
parser_start = subparsers.add_parser... |
import os, datetime
import csv
import pycurl
import sys
import shutil
from openpyxl import load_workbook
import pandas as pd
import download.box
from io import BytesIO
import numpy as np
import json
from download.box import LifespanBox
verbose = True
snapshotdate = datetime.datetime.today().strftime('%m_%d_%Y')
#catf... |
#########################################################
#
# DO NOT EDIT THIS FILE. IT IS GENERATED AUTOMATICALLY. #
# PLEASE LOOK INTO THE README FOR MORE INFORMATION. #
#
#########################################################
# coding: utf-8
# # Control Ops Tutorial
#
# In this tutorial we show how to use... |
# -*- coding: utf-8 -*-
"""
This file is covered by the LICENSING file in the root of this project.
"""
import os
# "javascript" section for javascript. see @app.route('/config.js') in app/views.py
# NOTE: all following key/secrets for test purpose.
ENDPOINT_WEB = "http://localhost" # host name of the UI site
ENDPOIN... |
import argparse
import logging
import os
import random
import socket
import sys
import traceback
import numpy as np
import psutil
import setproctitle
import torch
import wandb
from mpi4py import MPI
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader
# add the... |
import random
print('''
Porta da Fortuna
Existe um super prêmio atrás de um destas 3 portas!
Advinhe qual é a porta certa para ganhar o prêmio!
_______ _______ _______
| | | | | |
| [1] | | [2] | | [3] |
| | | | | |
| | | | | |
------- --... |
"""``cubi-tk archive prepare``: Prepare a project for archival"""
import errno
import os
import re
import shutil
import sys
import tempfile
from cookiecutter.main import cookiecutter
from logzero import logger
from ..common import execute_shell_commands
from ..isa_tpl import IsaTabTemplate
from ..isa_tpl import load... |
# 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 time
from flask import request
from flask.ext.restful import abort
from funcy import project
from peewee import IntegrityError
from redash import models
from redash.wsgi import api
from redash.tasks import record_event
from redash.permissions import require_permission, require_admin_or_owner, is_admin_or_owner,... |
"""Definition of stuff that can be used directly by a user in a dodo.py file."""
import sys
from doit.cmd_base import ModuleTaskLoader
from doit.doit_cmd import DoitMain
def run(task_creators):
"""run doit using task_creators
@param task_creators: module or dict containing task creators
"""
sys.exit... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020 Yeolar
#
import multiprocessing
import os
import subprocess
import sys
def _wrap_with(code):
def inner(text, bold=False):
c = code
if bold:
c = '1;%s' % c
return '\033[%sm%s\033[0m' % (c, text)
return inner
... |
from .bitmovin_json_encoder import BitmovinJSONEncoder
from .serializable import Serializable
|
import scipy
import pdb
import numpy as np
import pandas as pd
#from inquire.interactions.modalities import *
from inquire.interactions.feedback import Query, Feedback, Choice, Modality
from inquire.utils.learning import Learning
from inquire.utils.sampling import TrajectorySampling
from inquire.agents.agent import Age... |
from django.apps import AppConfig
class SearchAppConfig(AppConfig):
name = 'search_app'
|
from __future__ import print_function
from builtins import str
from django.core.exceptions import FieldDoesNotExist
from django.core.management.base import BaseCommand
from django.utils.module_loading import import_string
from bluebottle.assignments.models import Assignment, Applicant
from bluebottle.events.models imp... |
"""
Datum Object Model
"""
from decimal import Decimal
from typing import Any, Dict, Optional
import numpy as np
from pydantic import BaseModel, validator
class Datum(BaseModel):
r"""Facilitates the storage of quantum chemical results by labeling them with basic metadata.
Attributes
----------
labe... |
# ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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.apa... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""This test module contains old tests coming from the instrumentation package.
Some are still relevant, others are not, w... |
"""
Factory and interface for file parser
"""
import os
import warnings
from .sources import *
from .generic import GenericParser
class ParserFactory(type):
"""
Metaclass for creating source classes for different CHIANTI filetypes
"""
def __call__(cls, *args, **kwargs):
# Allow for standalon... |
import unittest
from parsers import groups_parser, student_list_parser, student_parser
class ParserTestCase(unittest.TestCase):
def test_groups_parser(self):
text = '''
<select id="group" name="group">
<option value=""/>
<option value="15798">АЭМББТ</option>
... |
#! coding: utf-8
from django.db import models
class Producers(models.Model):
Name = models.CharField("Название", max_length=150)
def __unicode__(self):
return self.Name
class Meta:
verbose_name = "Производитель"
verbose_name_plural = 'Производители'
class Categories(models.Model... |
def compute_iou_with_regular_coord(box1, box2):
# Prevent NaN in benchmark results
validate_box(box1)
validate_box(box2)
# change float to int, in order to prevent overflow
box1 = map(int, box1)
box2 = map(int, box2)
tb = min(box1[0]+0.5*box1[2],box2[0]+0.5*box2[2])-max(box1[0]-0.5*box1[2... |
from django.forms import ModelForm, Form, TextInput, HiddenInput, DateField, DateInput, \
ModelChoiceField, ModelMultipleChoiceField, ChoiceField, \
CharField, BooleanField, formset_factory
from opencivicdata.legislative.models import Event, EventParticipant
from openci... |
"""A textured gyroid shape cut by a sphere"""
from vedo import *
import numpy as np
# Equation of a "gyroid" (https://en.wikipedia.org/wiki/Gyroid)
x, y, z = np.mgrid[:30,:30,:30] * 0.4
U = sin(x)*cos(y) + sin(y)*cos(z) + sin(z)*cos(x)
# Create a Volume, take the isosurface at 0, smooth and subdivide it
gyr = Volume(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: winston
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Model
from keras.layers import Dense, Input
from keras.callbacks import ModelCheckpoint
from keras.optimizers import Adam
from scipy.io import loadmat
from utils ... |
import os
from os.path import join
import pytest
import OpenSSL.crypto
from cryptography import x509
from cryptography.x509.oid import ExtensionOID
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']
).get_hosts('all')
cert_d... |
import random
import re
WIN_POSITION = 63
BRIDGE_HEAD = 6
BRIDGE_TAIL = 12
DICE_FACE = 6
GOOSES = [5, 9, 14, 18, 23, 27]
def get_old_label(old_position):
if old_position == 0:
old_label = "Start"
else:
old_label = old_position
return old_label
def get_new_label(new_position):
if new_p... |
"""
DogStatsd is a Python client for DogStatsd, a Statsd fork for Datadog.
"""
import logging
from random import random
from time import time
import socket
from functools import wraps
try:
from itertools import imap
except ImportError:
imap = map
log = logging.getLogger('dogstatsd')
class DogStatsd(object... |
#!/usr/bin/env python
# coding: utf-8
# # 开发 AI 应用
#
# 未来,AI 算法在日常生活中的应用将越来越广泛。例如,你可能想要在智能手机应用中包含图像分类器。为此,在整个应用架构中,你将使用一个用成百上千个图像训练过的深度学习模型。未来的软件开发很大一部分将是使用这些模型作为应用的常用部分。
#
# 在此项目中,你将训练一个图像分类器来识别不同的花卉品种。可以想象有这么一款手机应用,当你对着花卉拍摄时,它能够告诉你这朵花的名称。在实际操作中,你会训练此分类器,然后导出它以用在你的应用中。我们将使用[此数据集](http://www.robots.ox.ac.uk/~vgg/dat... |
# -*- coding: utf-8 -*-
import time
import numpy as np
import scipy.integrate
import matplotlib.pyplot as plt
from pyequion2 import InterfaceSystem
from pyequion2 import water_properties
def reynolds_number(flow_velocity, pipe_diameter, TK=298.15): #Dimensionless
kinematic_viscosity = water_properties.water_kin... |
# -*- coding: utf-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want wit... |
import os
from img_classify import *
try:
from PIL import Image
import discord
from discord.ext import commands
from dotenv import load_dotenv
except:
os.system("pip3 install discord.py")
os.system("pip3 install python-dotenv")
from discord.ext import commands
from dotenv import load_do... |
#!/usr/bin/env python
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torchsummary import summary
import sys
sys.path.append('../')
from wideresnet import Wide_ResNet
'''
Function that loads the dataset and returns the d... |
# -*- coding: utf-8 -*-
"""
Created on 2019/7/17
File run.py
@author:ZhengYuwei
"""
import os
import logging
import numpy as np
import tensorflow as tf
from tensorflow import keras
from logging.handlers import RotatingFileHandler
from multi_label.trainer import MultiLabelClassifier
from configs import FLAGS
if FLAGS.... |
import sys
from os.path import dirname,abspath
sys.path.append(dirname(dirname(abspath(__file__))))
from unittest import TestCase
from unittest import main
from extensions.Util import Util
class TestUtilConfig(TestCase):
def test_getConfigbrowser(self):
result = Util.getConfig("browser")
... |
from flask import Flask, render_template, request
import pickle
import numpy as np
app = Flask(__name__)
model = pickle.load(open("C:/Users/Omneya Essam/Desktop/tutorial/model.pkl","rb"))
vectorizer = pickle.load(open("C:/Users/Omneya Essam/Desktop/tutorial/Vectorizer.pkl","rb"))
@app.route('/<strin... |
# Generated by Django 3.1 on 2020-09-02 20:30
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('shopping', '0029_auto_20200830_1157'),
('order', '0012_auto_20200824_2040'),
]
operations = [
migrati... |
import warnings
import astropy.units as u
import numpy as np
from einsteinpy import constant
from einsteinpy.coordinates import BoyerLindquistDifferential, CartesianDifferential
from einsteinpy.integrators import RK45
from einsteinpy.utils import kerr_utils, schwarzschild_radius
_G = constant.G.value
_c = constant.c... |
import os
import pytest
import tempfile
from tests.utils import (
get_open_port,
)
from cpc_fusion import Web3
from .common import (
GoEthereumEthModuleTest,
GoEthereumNetModuleTest,
GoEthereumPersonalModuleTest,
GoEthereumTest,
GoEthereumVersionModuleTest,
)
from .utils import (
wait_for_... |
# Copyright 2019 Nokia
# 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, softwar... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('info_transportation', '0014_auto_20150227_2248'),
]
operations = [
migrations.AddField(
model_name='line',
... |
import sys
import traceback
from discord.ext import commands
from ansura import AnsuraBot, AnsuraContext
class ErrorHandler(commands.Cog):
def __init__(self, bot: AnsuraBot):
self.bot = bot
# @commands.Cog.listener()
async def on_command_error(self, ctx: AnsuraContext, error: Exception):
... |
# pfryby.py
import pandas as pd
import requests
from bs4 import BeautifulSoup
from os import path
from fantasyfootball.config import DATA_DIR
def pfr_year_by_year_table_grab(year):
"""Grabs fantasy stats for a given year """
url = f'https://www.pro-football-reference.com/years/{year}/fantasy.htm'
r = requ... |
import requests
from requests.auth import HTTPBasicAuth
import json
api_key = "" # Your API Key
youtube_link = "" # Your YouTube link
url = "https://api-us.musiio.com/api/v1/upload/youtube-link"
payload = {
"link": youtube_link
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(ur... |
import time
import sys
import os
import tempfile
import tornado
from datetime import datetime
from circus.py3compat import StringIO
from circus.client import make_message
from circus.tests.support import TestCircus, async_poll_for, truncate_file
from circus.tests.support import TestCase, EasyTestSuite
from circus.str... |
import numpy as np
import ast
def vandermonde(x,y):
x = ast.literal_eval(x)
y = ast.literal_eval(y)
y = np.array(y)
x = np.array(x)
vanx = np.vander(x)
yT = y.T
invX = np.linalg.inv(vanx) # Get the inverse of matrix x
dotPoint = np.dot(invX,yT) # dot point between inverse x a... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Do-nothing script for making a release
This idea comes from here:
https://blog.danslimmon.com/2019/07/15/do-nothing-scripting-the-key-to-gradual-automation/
Author: Gertjan van den Burg
Date: 2019-07-23
"""
import colorama
import os
import sys
import tempfile
de... |
from unittest import TestCase, mock
from django.contrib.auth.models import User
from rest_framework.test import APIClient
class TestIndexView(TestCase):
@classmethod
def setUpClass(cls):
cls.user = User(username='test')
@classmethod
def tearDownClass(cls):
User.objects.all().delete()... |
"""Import this module to run the service"""
import os
import sys
import django
BASE_DIR = os.path.abspath(os.path.join(
os.path.dirname(os.path.abspath(__file__)),
os.path.pardir,
os.path.pardir,
))
sys.path.append(BASE_DIR)
os.environ["DJANGO_SETTINGS_MODULE"] = "webca.ca_service.settings"
django.setup(... |
from .tokenized_validators import run_if, run_if_any, run_if_all, run_if_tokens_satisfy_condition |
from backend.django_algolia.client import get_index
# def perform_search(query):
# index = get_index()
# params = {
# 'hitsPerPage': 10
# }
# results = index.search(query, params)
# return results
def search_index(query):
index = get_index()
return index.search(query) |
print("Some content")
|
import csv, re
def cleanNumber(n):
n = int(n.replace('.', '').replace(',', ''))
if (n < 100):
n *= 1000
if (n < 1000):
n *= 10
if (n < 10000):
n *= 10
return n
def cleanupMedians():
with open('county-median-incomes-normalized.csv', 'r') as csvfile:
reader =... |
from .version_header import VersionHeader
from .header import Header
from .items import InfoItem, VersionItem
class TeeworldsMap:
def __init__(self, version_header: VersionHeader, header: Header,
version_item: VersionItem, info_item: InfoItem):
self.version_header = version_header
... |
from pathlib import Path
from pypj.environment import Version
from pypj.file_path import PypjFilePath
from pypj.setting import PackageName, PypjSetting
from pypj.task.pyproject import Pyproject
from tests.conftest import does_contain_specific_words, prepare_dir, validate_toml
def test_pyproject() -> None:
# prep... |
import os
import json
import difflib
import logging
import threading
from pathlib import Path
from itertools import islice
from collections import OrderedDict
from typing import List, Optional, Tuple, NamedTuple
from nornir.core.task import AggregatedResult, MultiResult, Result
from nornir_utils.plugins.tasks.files.wri... |
from django.conf import settings
from django.db import models
import datetime
# Create your models here.
class Event (models.Model):
title = models.CharField(verbose_name='Título',
max_length=50, blank=True, null=True)
start = models.CharField(verbose_name='Data Inicio',
... |
import json
from flask import request, jsonify, g
from random import randint
import requests
from sqlalchemy import func
from . import main
from app.models import User, Box, BoxWithCard, Card, db, UserOpenid, Photo, Message
from app.utils.tool import Token, user_login_required, user_often_get_api, msg_unsafe, have_acc... |
import os
import random
import argparse
import pandas as pd
import numpy as np
from tqdm import tqdm
import torch
from transformers import AutoTokenizer, EncoderDecoderModel
from rouge_score import rouge_scorer
from models import EncoderDecoderModelWithGates, EncoderModelWithGates
from scorers import WRR, bleu_score
... |
# Copyright Notice:
# Copyright 2017 Distributed Management Task Force, Inc. All rights reserved.
# License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/Redfish-Usecase-Checkers/blob/master/LICENSE.md
import datetime
import json
import os
import sys
class Results(object):
def __init__(... |
import json
import os
import shutil
import pytest
from graphql_relay import to_global_id
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import Client
from db.models import Attachment, Image, At... |
"""
The MIT License (MIT)
Copyright © 2018 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
from network import WLAN
from socket import getaddrinfo
from time import sleep, ticks_ms, ticks_diff
from binascii import hexlify
from os import mkdir
from json import load, dumps
class MicroWifi :
# ==========... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.