text stringlengths 2 999k |
|---|
class IllegalOrderException(Exception):
pass
|
__all__ = ['wfpackage', 'wfsite'] |
# pylint: disable=C1001
class Config:
# Custom
DEBUG_FILE = '/tmp/gmw.log'
ENVIRONMENT = 'development'
# Application related
REPOSITORY_WORTH_SOLID = 6
REPOSITORY_WORTH_DEFAULT = 3
# Flask
DEBUG = True
PERMANENT_SESSION_LIFETIME = 1209600 # 14 days
SECRET_KEY = ''
TESTING ... |
# Copyright 2021 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... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
ohlc_data = pd.read_csv('nifty-50\SBIN.csv', index_col=0, parse_dates=True)
daily = np.array(ohlc_data)
money = int(input('Enter amount you want to invest : '))
risk = int(input('Enter no of shares you want to buy/sell in each transaction : '))
... |
from scipy.cluster.vq import kmeans
import numpy as np
import pymc3 as pm
import theano.tensor as tt
cholesky = pm.distributions.dist_math.Cholesky(nofail=True, lower=True)
solve_lower = tt.slinalg.Solve(A_structure='lower_triangular')
solve_upper = tt.slinalg.Solve(A_structure='upper_triangular')
solve = tt.slinalg.... |
import numpy as np
import torch
import math
from torch import nn, optim
from torch.utils.data import DataLoader
from torch.utils.data import SubsetRandomSampler
import importlib
import copy
import argparse
from torchvision import transforms, datasets
from torch.autograd import Variable
from torch.optim impor... |
from datetime import datetime
from olympia.addons.models import Addon
from olympia.api.serializers import BaseESSerializer
class BasicSerializer(BaseESSerializer):
class Meta:
model = Addon
fields = ()
def test_handle_date_strips_microseconds():
serializer = BasicSerializer()
date = dat... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... |
"""This is the docstring"""
import datetime
from flask import jsonify, request, g
from ..utils.auth import requires_auth
from ..utils.tools import fileUpload, enrich_posts
from ..utils.db_handler import insert_post_to_db, find_related_posts, like_post
from .. import app
@app.route('/post', methods=['GET'])
@requires_... |
from abc import ABC, abstractmethod
import numpy as np
import copy
from rl.tools.utils.mvavg import ExpMvAvg, PolMvAvg
from rl.tools.utils.misc_utils import deepcopy_from_list
class OnlineNormalizer(ABC):
"""
A normalizer that adapts to streaming observations. Given input x, it computes
x_cook... |
##############################################################################
#
# Copyright (c) 2003 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2018 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on Friday Feb 20 2020
This code was implemented by
Louis Weyland, Floris Fok and Julien Fer
"""
# Import built-in libs
import math
# Import 3th parties libraries
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st
cla... |
###############################################################################
##
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "Redistribution and use in source and binary for... |
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib imp... |
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Clas... |
from django.test import tag
from ..models import OrgUnit, Form, Instance, OrgUnitType, Account, Project, SourceVersion, DataSource
from math import floor
from rest_framework.test import APIClient
import json
from ..test import APITestCase
import typing
class BasicAPITestCase(APITestCase):
def setUp(self):
... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListExtendsParamsRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): T... |
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
def send_welcome_email(name,receiver):
# Creating message subject and sender
subject = 'Welcome to Joseph shitandi Instagram clone'
sender = 'jsphshtnd@gmail.com'
#passing in the context vairables
... |
import torch
import torch.nn as nn
from utils.network_utils import *
from networks.architectures.base_modules import *
class UNetDecoder(nn.Module):
def __init__(self, opt, nf):
super(UNetDecoder, self).__init__()
ic, oc, norm_type, act_type, mode = \
opt.ic, opt.oc, opt.norm_type, opt.act_type, opt.dec_mode
... |
# coding: utf-8
"""
Automox Console API
API for use with the Automox Console # noqa: E501
OpenAPI spec version: 2021-11-16
Contact: support@automox.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class OneOfEventData(ob... |
# Note: The information criteria add 1 to the number of parameters
# whenever the model has an AR or MA term since, in principle,
# the variance could be treated as a free parameter and restricted
# This code does not allow this, but it adds consistency with other
# packages such as gretl and X1... |
# 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... |
#!/usr/bin/env python3
#
# Copyright 2018 Brian T. Park
#
# MIT License.
"""
Read the raw TZ Database files at the location specified by `--input_dir` and
generate the zonedb files in various formats as determined by the '--action'
flag:
* --action tzdb
JSON file representation of the internal zonedb named 't... |
# -*- coding: utf-8 -*-
from simmate.calculators.vasp.tasks.base import VaspTask
from simmate.calculators.vasp.inputs.potcar_mappings import (
PBE_ELEMENT_MAPPINGS_LOW_QUALITY,
)
class Quality03Relaxation(VaspTask):
# returns structure separately from vasprun object
return_final_structure = True
# ... |
import taichi as ti
from pytest import approx
import autograd.numpy as np
from autograd import grad
@ti.all_archs
def grad_test(tifunc, npfunc=None):
if npfunc is None:
npfunc = tifunc
x = ti.var(ti.f32)
y = ti.var(ti.f32)
@ti.layout
def place():
ti.root.dense(ti.i, 1).place(x, x.grad, y, y.grad)
... |
import numpy as np
import pandas as pd
import pylab as plt
import components.visualization
from components.flowUtils import annotateProgress, cached
class PerformanceUserMatrixPlot:
def __init__(self, flow, orderUsers=None):
self.flow = flow
self.performanceMatrix = flow.getPerformanceMatrix(flow... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pydm.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from qtpy import QtCore, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjec... |
from abc import ABC, abstractmethod
from collections import namedtuple
import ctypes
import json
import logging
import os
import requests
import socket
import subprocess
import sys
import urllib.parse
from utils import clip
try:
# omxplayer is only available on Raspberry Pi
from omxplayer.player import OMXPla... |
#!/usr/bin/env python
# rgb2colorname.py
# by wilsonmar@gmail.com, ayush.original@gmail.com, https://github.com/paarthneekhara
# Usage:
# Explained in https://github.com/jetbloom/rgb2colorname/blob/master/README.md
import numpy as np
from scipy import spatial
A = np.array([ \
[240,248,255] \
,[250,235,215] \
,[2... |
from .React import React
from .Vue import Vue
from .ReactTailwind import ReactTailwind
from .VueTailwind import VueTailwind
from .ReactBootstrap import ReactBootstrap
from .VueBootstrap import VueBootstrap
from .Tailwind import Tailwind
from .Bootstrap import Bootstrap
|
from __future__ import absolute_import
from itertools import izip_longest
import Queue
import MySQLdb as mysql
from MySQLdb.cursors import DictCursor
from dejavu.database import Database
class SQLDatabase(Database):
"""
Queries:
1) Find duplicates (shouldn't be any, though):
select `hash`, `so... |
# Sentiment Analyzer.py
#!/usr/bin/python
import os
import sys
import json
import joblib
import itertools
from statistics import mode
import numpy as np
import sklearn
from keras.models import load_model
from sklearn.ensemble import VotingClassifier
from keras.preprocessing.text import Tokenizer
from sklearn.metrics i... |
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. T... |
#!/usr/bin/env python
"""
dnolivieri: 23 dec 2015
Bootstrap workflow for the MR ensemble RF code.
"""
import collections
import random as rnd
import numpy as np
import matplotlib.pyplot as plt
import time
import os, fnmatch
import sys
import itertools
from operator import itemgetter, attrgetter
import math
f... |
# from beluga.optim import *
from optimalcontrol.elements import Problem
from sympy import *
from sympy.core.function import AppliedUndef, Function
import pystache, imp, inspect, logging, os
import re as _re
import beluga.bvpsol.BVP as BVP
from beluga.utils import sympify, keyboard, ipsh
from beluga.optim.problem imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2020-present Daniel [Mathtin] Shiko <wdaniil@mail.ru>
Project: Overlord discord bot
Contributors: Danila [DeadBlasoul] Popov <dead.blasoul@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this softw... |
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
import numpy as np
import pandas as pd
def read_reference_structure_for_q_calculation_4(oa, contact_threshold,rnative_dat, min_seq_sep=3, max_seq_sep=np.inf):
# use contact matrix for Q calculation
# this change use the canonica... |
N = int(input())
y = list(map(int, input().split()))
sy = sum(y)
print(*[sy - yi * (N - 1) for yi in y])
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.contrib import admin
class CloudAdmin(admin.ModelAdmin):
search_fields = ("name",)
list_display = ("name",)
save_on_top = True |
import sys
import qtvscodestyle as qtvsc
from qtvscodestyle.qtpy.QtWidgets import QApplication, QDialog, QFrame, QGridLayout, QLabel
app = QApplication(sys.argv)
main_win = QDialog()
# Create line=======================
h_line, v_line = QFrame(), QFrame()
h_line.setProperty("type", "h_line")
v_line.setProperty("type... |
# Generated by Django 3.1.1 on 2020-11-12 21:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0003_auto_20201112_2107'),
]
operations = [
migrations.AlterField(
model_name='order',
name='orderTrakingN... |
#!/usr/bin/env python
#
# For use as appointed as SSH_ASKPASS when starting ssh-agent, call
# on the user seconds factor instead.
#
# Needs https://github.com/duosecurity/duo_client_python installed
# or cloned and this script copied to the cloned directory.
#
# duo_config should define ikey, skey and api_hostname per ... |
#
# PySNMP MIB module ASKEY-ENTITY-ALARM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASKEY-ENTITY-ALARM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:29:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (d... |
# Developed by Vinicius José Fritzen
# Copyright (c) 2019 Vinicius José Fritzen and Albert Angel Lanzarini
import logging
import pytest
from django.test import Client, TestCase
from django.urls import reverse
from escola.models import Conteudo, Profile
logger = logging.getLogger(__name__)
pytestmark = pytest.mar... |
# 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... |
num1 = input()
set1 = set(map(int, input().split()))
num2 = input()
set2 = set(map(int, input().split()))
print(len(set1^set2))
|
##########################################################################
#
# Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistribu... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.core.validators import RegexValidator
from .models import Link
_alias = Link._meta.get_field('alias')
_url = Link._meta.get_field('url')
class URLShortenerForm(forms.Form):
alias = forms.CharField(
max_length=_... |
# Adapted from test_file.py by Daniel Stutzbach
import sys
import os
import io
import errno
import unittest
from array import array
from weakref import proxy
from functools import wraps
from test.support import (run_unittest, cpython_only, swap_attr)
from test.support.os_helper import (TESTFN, TESTFN_UNIC... |
from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.nn.modules.batchnorm import BatchNorm2d
from torch.nn.modules.instancenorm import InstanceNorm2d
from torchvision.ops import ConvNormActivation
from ..._internally_replaced_utils import load_... |
import PIL
from userbot.utils import admin_cmd
from userbot import CMD_HELP
# ascii characters used to build the output text
import pygments, os, asyncio
from pygments.lexers import Python3Lexer
from pygments.formatters import ImageFormatter
from userbot.utils import admin_cmd
from userbot import bot
from userbot impor... |
import copy
from typing import List, Dict, Any, Optional # noqa
from chalice.config import Config # noqa
from chalice import constants
from chalice import __version__ as chalice_version
class InvalidCodeBuildPythonVersion(Exception):
def __init__(self, version):
# type: (str) -> None
super(Inv... |
# -*- coding: utf-8 -*-
"""
grades/gradetable.py - last updated 2021-06-02
Access grade data, read and build grade tables.
==============================
Copyright 2021 Michael Towers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License... |
"""
Setup module for the jupyterlab_github proxy extension
"""
import setuptools
from setupbase import (
create_cmdclass, ensure_python, find_packages
)
data_files_spec = [
('etc/jupyter/jupyter_notebook_config.d',
'jupyter-config/jupyter_notebook_config.d', 'jupyterlab_github.json'),
]
cmdclass = cr... |
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
class Movie(models.Model):
title = models.CharField(max_length=32)
description = models.TextField(max_length=360)
def no_of_ratings(self):
ratings = Rat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#****************************************************************************************************************************************************
# Copyright 2017 NXP
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifi... |
import olutils.collection as lib
def test_FlatStr():
assert repr(lib.FlatStr("Hello")) == "Hello"
|
import numpy as np
def open_pdb(file_location):
"""
Open and read coordinates from a pdb file.
The pdb file must specify the atom elements in the last column, and for
the conventions outlined in the pdb format specification.
Parameters
----------
file_location : string
The locatio... |
from flask import redirect, session
class Device_XML():
endpoints = ["/device.xml"]
endpoint_name = "file_device_xml"
def __init__(self, fhdhr):
self.fhdhr = fhdhr
def __call__(self, *args):
return self.get(*args)
def get(self, *args):
if self.fhdhr.config.dict["rmg"]["... |
from .semseg_loss import filter_valid_label, SemSegLoss
from .cross_entropy import CrossEntropyLoss
from .focal_loss import FocalLoss
from .smooth_L1 import SmoothL1Loss
__all__ = [
'filter_valid_label', 'SemSegLoss', 'CrossEntropyLoss', 'FocalLoss',
'SmoothL1Loss'
]
|
from easygraphics.turtle import *
create_world(800, 600)
set_speed(10)
lt(45)
fd(100)
lt(90)
move_arc(100, 90)
lt(90)
fd(100)
lt(90)
fd(100)
rt(90)
move_arc(-100, 90)
rt(90)
fd(100)
rt(90)
bk(100)
rt(90)
move_arc(100, -90)
rt(90)
bk(100)
rt(90)
bk(100)
lt(90)
move_arc(-100, -90)
lt(90)
bk(100)
lt(90)
pause()
cl... |
import time
import pytest
from ray import serve
from ray.serve.deployment_state import (
SLOW_STARTUP_WARNING_S,
SLOW_STARTUP_WARNING_PERIOD_S,
)
def test_slow_allocation_warning(serve_instance, capsys):
# this deployment can never be scheduled
@serve.deployment(ray_actor_options={"num_cpus": 99999})... |
from tfbspline.BSplineTF import BSpline, get_spline
from .util import interpolate
__version__ = '1.0.0' |
# -*- coding:utf-8 -*-
#
# Copyright (C) 2012, Maximilian Köhl <linuxmaxi@googlemail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option)... |
import codecs
import copy
from decimal import Decimal
from django.apps.registry import Apps
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.utils import six
import _sqlite3
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
sql_delete_table = "DROP TABLE %(table)s"
sql_cr... |
import os
import shutil
from pathlib import Path
def get_obj_name(files):
for file in files:
if (str(file).endswith(".obj")):
return (str(file).split('.')[0], True)
return (None, False)
def filter_specify_file(root, files, name, type, verbose=False):
output = []
for file in files:... |
from typing import Any, Dict, Optional, Sequence
from ..argument_utility import (
ActionScalerArg,
EncoderArg,
QFuncArg,
ScalerArg,
UseGPUArg,
check_encoder,
check_q_func,
check_use_gpu,
)
from ..constants import IMPL_NOT_INITIALIZED_ERROR, ActionSpace
from ..dataset import TransitionMi... |
#!/usr/bin/python3
import os
BOSON_BUS = 10
BOSON_I2C_ADDR = 0x6C
CMD_REG = 0
def send_i2c(bus, address, reg, val):
os.system(f'sudo i2cset -f -y {bus} {hex(address)} {hex(reg)} {hex(val)}')
def read_i2c(bus, address, reg):
os.system(f'sudo i2cget -f -y {bus} {hex(address)} {hex(reg)}')
def send_packet... |
from Web import app as application |
# flake8: noqa
from mot.trackers.single_object_trackers.gauss_sum_tracker import GaussSumTracker
from mot.trackers.single_object_trackers.nearest_neighbour_tracker import (
NearestNeighbourTracker,
)
from mot.trackers.single_object_trackers.probabilistic_data_association_tracker import (
ProbabilisticDataAssoc... |
import os, re, shutil, sys, sysconfig
import platform
import subprocess
from distutils.version import LooseVersion
from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext
# Project structure and CMake build steps adapted from
# https://www.benjack.io/2018/02/02/python... |
#!U:\PROG\Reknamorcen\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
... |
def section1():
import dtlpy as dl
if dl.token_expired():
dl.login()
organization = dl.organizations.get(organization_name=org_name)
with open(r"C:\gcsfile.json", 'r') as f:
gcs_json = json.load(f)
gcs_to_string = json.dumps(gcs_json)
organization.integrations.create(name='gcsint... |
# coding:utf-8
#
# The MIT License (MIT)
#
# Copyright (c) 2016-2018 yutiansut/QUANTAXIS
#
# 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 th... |
# coding: utf-8
#
# Copyright 2014 The Oppia 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 requi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.
"""
Simple Bot to reply to Telegram messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is ... |
import os
import numpy as np
import src
from setuptools import setup, find_packages
from Cython.Build import cythonize
from Cython.Distutils import build_ext
from src.extra import utils
compiler_directives = {
'language_level': 3,
'cdivision': True,
'boundscheck': True,
'wraparound': False,
}
def... |
import speech_recognition as sr
import datetime
import wikipedia
import pyttsx3
import webbrowser
import random
import os
import time
import smtplib
import wolframalpha
try:
app = wolframalpha.Client("X27662-QTV98PXR56")
except Exception:
print("NO found")
# Project Personal Assistance Zen 406;
engine = pytts... |
# -*- coding: utf-8 -*-
# Copyright 2014, 2015 OpenMarket 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 applica... |
""" Code is generated by ucloud-model, DO NOT EDIT IT. """
from ucloud.core.typesystem import schema, fields
class CheckResultItemSchema(schema.ResponseSchema):
"""CheckResultItem - 预检查结果项"""
fields = {
"ErrMessage": fields.Str(required=True, load_from="ErrMessage"),
"State": fields.Str(requ... |
from flask import Flask
from flask_restplus import Resource,Api
from flask_cors import CORS
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
#CORS(app, supports_credentials=True)
api = Api(app)
@api.route('/hack/<string:username>/<string:password>',methods=['OPTIONS'])
class Hacker(Resource):
def option... |
"""
Classes for the ticks and x and y axis.
"""
import datetime
import functools
import logging
import numpy as np
import matplotlib as mpl
from matplotlib import _api
import matplotlib.artist as martist
import matplotlib.cbook as cbook
import matplotlib.lines as mlines
import matplotlib.scale as msca... |
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import cv2
import time
import os
'''
writer.write(example.SerializeToString()) input 最后生成数据。
从TFRecords文件中读取数据,
首先需要用tf.train.string_input_producer生成一个解析队列。
之后调用tf.TFRecordReader的tf.parse_single_example解析器。如下图:
'''
IMAGE_SIZE = ... |
from aiohttp_security import AbstractAuthorizationPolicy
from .users import user_map
class AuthorizationPolicy(AbstractAuthorizationPolicy):
"""
This class implement access policy to admin interface.
"""
async def permits(self, identity, permission, context=None) -> bool:
user = user_map.get... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from .game_server_cluster import *
from .game_serve... |
"""Gotify notification service"""
import logging
import json
from typing import List
from django.conf import settings
from moni.utils.requests_proxy import requests_post
from notifiers.services import NotifierService
logger = logging.getLogger(__name__)
class Gotify(NotifierService):
"""Gotify notifiers"""
... |
import argparse
import logging
# Need to import there for pickle
from debias.datasets.dataset_utils import QuantileBatcher
from debias.datasets.squad import AnnotatedSquadLoader
from debias.experiments.eval_debiased_squad import compute_all_scores
from debias.models.text_pair_qa_model import TextPairQaDebiasingModel
f... |
"""
Defines a functions for training a NN.
"""
from data_generator import AudioGenerator
import _pickle as pickle
from keras import backend as K
from keras.models import Model
from keras.layers import (Input, Lambda)
from keras.optimizers import SGD
from keras.callbacks import ModelCheckpoint
import os
def ctc_la... |
#!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [s.strip() for s in open('requirements.txt', 'r').readlines()]... |
import argparse
import os
import random
import torch
import os
import misc_utils as utils
def parse_args():
# experiment specifics
parser = argparse.ArgumentParser()
parser.add_argument('--tag', type=str, default='cache',
help='folder name to clear')
parser.add_argument('--rm... |
#!"E:\zip my django projects\basic Django\crud operations\venv\Scripts\python.exe"
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?... |
import xmnlp
xmnlp.set_model('../xmnlp-onnx-models')
with open("text.txt", "r", encoding='utf8') as f:
text = f.read()
result = xmnlp.keyphrase(text, k=1)
sentiment = xmnlp.sentiment(result[0])
print(result, sentiment)
|
from math import sin, cos, radians
for i in range(int(input())):
v, theta, x, h1, h2 = list(map(float, input().split()))
t = x / v / cos(radians(theta))
yt = v * t * sin(radians(theta)) - (1 / 2 * 9.8 * t**2)
print("Safe" if h2 - yt >= 1 and yt - h1 >= 1 else "Not safe")
|
style = '''
/* /////////////////////////////////////////////////////////////////////////////////////////////////
QTableWidget */
QTableWidget {{
background-color: {_bg_color};
outline: 0;
padding: 5px;
border-radius: {_radius}px;
gridline-color: {_grid_line_color};
}}
/*
QTableWidget::item:hover {{
... |
""" IO Handler for LAS (and compressed LAZ) file format """
import pylas
from laserchicken import keys
from laserchicken.io.base_io_handler import IOHandler
from laserchicken.io.utils import convert_to_short_type, select_valid_attributes
DEFAULT_LAS_ATTRIBUTES = {
'x',
'y',
'z',
'intensity',
'gps... |
import zmq
ctx = zmq.Context.instance()
server = ctx.socket(zmq.PULL)
server.bind('inproc://foo')
clients = [ctx.socket(zmq.PUSH) for i in range(10)]
for client in clients:
client.connect('inproc://foo')
client.send(b'DATA')
for i in range(10):
print(repr(server.recv()))
|
from django.core.urlresolvers import resolve
from django.template.loader import render_to_string
from django.test import TestCase
from django.http import HttpRequest
from lists.views import home_page
from lists.models import Item, List
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(sel... |
from .alert_model import *
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.