text stringlengths 1 927k |
|---|
import cv2
from scipy import signal
import matplotlib.pyplot as plt
img = cv2.imread('images/1.jpg',cv2.IMREAD_GRAYSCALE)
kernel = [[1,1,1],[0,0,0],[-1,-1,-1]]
dest = signal.convolve2d(img,kernel)
plt.imshow(dest,cmap='gray')
plt.show() |
from fastapi import HTTPException
from sqlalchemy import orm
from ultron8.api.db.pagination.pagination import Pagination
class PaginationQuery(orm.Query):
def get_or_404(self, ident):
rv = self.get(ident)
if rv is None:
raise HTTPException(status_code=404, detail="Item not found")
... |
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Sylvain Afchain <sylvain.afchain@enovance.com>
#
# 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.apach... |
# -*- coding: utf-8 -*-
"""
Mesa Data Collection Module
===========================
DataCollector is meant to provide a simple, standard way to collect data
generated by a Mesa model. It collects three types of data: model-level data,
agent-level data, and tables.
A DataCollector is instantiated with two dictionaries... |
# Generated by Django 3.1.1 on 2020-12-05 04:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_store', '0011_auto_20201205_0846'),
]
operations = [
migrations.AddField(
model_name='shipping_address',
name='... |
from . import colours
from .better_embed import BetterEmbed
from .. import config
# pylint: disable=line-too-long
HELP_EMBED = BetterEmbed(
title="SpaceXLaunchBot Commands",
description=f"Command prefix: `{config.BOT_COMMAND_PREFIX}`",
color=colours.RED_FALCON,
inline_fields=False,
fields=[
... |
import lib.inportfunc
print(lib.inportfunc.cube(31)) |
#Program adapted from GeeksforGeeks: https://www.geeksforgeeks.org/twitter-sentiment-analysis-using-python/
#consumer_key = "yJsuGs8DcLZjVe4w46RlmE7EU"
#consumer_secret = "7LTHqVUngpY2TnrO2TUKIGDOU3pokGh1s48AhqGDArqrv6ajtv"
#access_token = "1090450437222948864-upQR0M9V0ChS6QKRsRMgsZnBtkZ5oT"
#access_token_secret = "5nt... |
import os
import cv2
import yaml
from inference import Lanefinder
def read_config():
if not os.path.isfile('config.yaml'):
raise FileNotFoundError('Could not find config file')
with open('config.yaml', 'r') as file:
config = yaml.load(file)
return config
def main():
# set video str... |
# coding=utf-8
# Copyright 2022 GradMax 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 or ag... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
"""
this script was designed to initialize the graph G
and the rest of the demo is in an interactive ipython stint
ie i just
%run example.py
this also loads some functions for manipulating G
as well as the coloring of G returned by networkx
so that I wouldn't have to come up with these routines on the spot
"""
impo... |
# -*- coding: utf-8 -*-
# Copyright 2018-2021 CERN
#
# 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 a... |
import os
image_files = []
os.chdir(os.path.join("data", "weed_data/data"))
for filename in os.listdir(os.getcwd()):
if filename.endswith(".jpeg"):
image_files.append("data/weed_data/data/" + filename)
os.chdir("..")
with open("train.txt", "w") as outfile:
for image in image_files:
outfile.writ... |
import tensorflow as tf
import numpy as np
import draw_util
import os
class Autoencoder(object):
def partial_fit(self, targets):
assert (self.is_training)
if not self.is_denoising:
self.sess.run(self.train_op, feed_dict={self.input_layer: targets,
self.batch_size: [len(... |
from django.conf import settings
from django.http import HttpResponseForbidden
from django.utils.deprecation import MiddlewareMixin
class Public(MiddlewareMixin):
acceptable_paths = (
"/api/v2/profile/",
)
def process_request(self, request):
if settings.PUBLIC is False and not request.us... |
'''Mod management model'''
# pylint: disable=invalid-name,missing-docstring,wildcard-import,unused-wildcard-import
from typing import Dict, List, KeysView, ValuesView
from os import path
import xml.etree.ElementTree as XML
from fasteners import InterProcessLock
from src.domain.mod import Mod
from src.domain.key impo... |
#!/usr/bin/python
from __future__ import print_function
from common import *
import tensorflow.contrib.lite as tflite
import keras
a = keras.models.Sequential()
model = load_model()
full_model_file_name = 'full_model.h5'
model.save(full_model_file_name)
converter = tflite.TFLiteConverter.from_keras_model_file(full... |
"""
========================================
Special functions (:mod:`scipy.special`)
========================================
.. module:: scipy.special
Nearly all of the functions below are universal functions and follow
broadcasting and automatic array-looping rules. Exceptions are noted.
Error handling
==========... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test fee estimation code."""
from test_framework.test_framework import FivebalanceTestFramework
from t... |
import logging
import pytest
import tensorflow as tf
from ludwig.combiners.combiners import (
ConcatCombiner,
SequenceConcatCombiner,
SequenceCombiner,
ComparatorCombiner,
sequence_encoder_registry,
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logging.getLogger("ludwig").s... |
""" Cisco_IOS_XR_infra_correlator_oper
This module contains a collection of YANG definitions
for Cisco IOS\-XR infra\-correlator package operational data.
This module contains definitions
for the following management objects\:
suppression\: Suppression operational data
correlator\: correlator
Copyright (c) 2013... |
from io import open
from setuptools import find_packages, setup
with open('userpath/__init__.py', 'r') as f:
for line in f:
if line.startswith('__version__'):
version = line.strip().split('=')[1].strip(' \'"')
break
else:
version = '0.0.1'
with open('README.rst', 'r', ... |
# coding: utf-8
from . import config
from . import auth
from . import session
def init():
config_filename = config.locate_config_file()
print(f"Loading config {config_filename}")
conf = config.parse_config(config_filename)
return conf, None |
import hug
import sagax.api as api
def test_api_health():
r = hug.test.get(api, 'health')
assert r.status == hug.HTTP_200 |
from django.urls import path
from . import views
urlpatterns = [
path('', views.product_list, name='product_list'),
path('<slug:category_slug>/', views.product_list, name='product_list_by_category'),
path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'),
] |
# --------------
# Code starts here
class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio']
class_2=['Hilary Mason','Carla Gentry','Corinna Cortes']
new_class=class_1+class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
# Co... |
#
# Copyright (c) 2019 Juniper Networks, Inc. All rights reserved.
#
"""Base class for feature plugins."""
import abc
from builtins import object
from builtins import str
from collections import OrderedDict
import copy
from abstract_device_api.abstract_device_xsd import (
IpAddress, LogicalInterface, PhysicalInt... |
'''Autogenerated by get_gl_extensions script, do not edit!'''
from OpenGL import platform as _p, constants as _cs, arrays
from OpenGL.GL import glget
import ctypes
EXTENSION_NAME = 'GL_ARB_texture_storage'
def _f( function ):
return _p.createFunction( function,_p.GL,'GL_ARB_texture_storage',False)
_p.unpack_constan... |
class BaseStrings:
version = "2.1.1"
version_sub = "Beta"
title = f"ArkNights-Farmer V{version}-{version_sub}"
hello_title = "注意"
hello_info = "本应用完全免费,如果你通过任何渠道购买获得,就很气。对此,作者建议对贩售人员*龙门粗口*,并威胁他向作者捐赠源石。"
farm = "刷图"
gay = "基建"
task_list = ""
customized_task = "自定义"
refresh_adb = "... |
#!/usr/bin/env python
import argparse
import io
import os
import sys
import tensorflow as tf
SCRIPT_PATH = os.path.dirname(os.path.abspath(__file__))
# Default paths.
DEFAULT_LABEL_FILE = os.path.join(
SCRIPT_PATH, '../labels/2350-common-hangul.txt'
)
DEFAULT_GRAPH_FILE = os.path.join(
SCRIPT_PATH, '../save... |
#
# $Id$
#
from __future__ import print_function
from sphinxapi import *
import sys, time
if not sys.argv[1:]:
print("Usage: python test.py [OPTIONS] query words\n")
print("Options are:")
print("-h, --host <HOST>\tconnect to searchd at host HOST")
print("-p, --port\t\tconnect to searchd at port PORT")
print("-i,... |
# This script does 1 thing:
#
# 1. tensorflow/lite/micro/compatibility.h:
# There seems to be a build error with in TF_LITE_REMOVE_VIRTUAL_DELETE
# Update the macro to ensure the "delete" operator is public
def should_patch_file(path: str) -> object:
if path.endswith('kiss_fftr.c'):
return dict(st... |
# exception_logger.py
import logging
def create_logger():
"""
Creates a logging object and returns it
"""
logger = logging.getLogger("example_logger")
logger.setLevel(logging.INFO)
# create the logging file handler
fh = logging.FileHandler(r"logger.log")
fmt = '%(asctime)s - %(name)s... |
"""HomeKit session fixtures."""
from unittest.mock import patch
import pytest
from pyhap.accessory_driver import AccessoryDriver
@pytest.fixture(scope='session')
def hk_driver():
"""Return a custom AccessoryDriver instance for HomeKit accessory init."""
with patch('pyhap.accessory_driver.Zeroconf'), \
... |
from plumeria.message.attachment import *
from plumeria.message.message import * |
import pytest
import contextlib
import os
asyncio = pytest.importorskip("asyncio")
httpx = pytest.importorskip("httpx")
import vcr # noqa: E402
class BaseDoRequest:
_client_class = None
def __init__(self, *args, **kwargs):
self._client = self._client_class(*args, **kwargs)
class DoSyncRequest(Ba... |
import smtplib
import os
import json
SMTP_SERVER = 'smtp.gmail.com' #Email Server (don't change!)
SMTP_PORT = 587 #Server Port (don't change!)
with open(os.path.expanduser('~/env'), 'r') as env_file:
env = json.loads(env_file.read())
class Emailer:
def sendmail(self, recipient, subject, content):
gmail_us... |
import Queue
import threading
import urllib2
from sklearn import linear_model
from nltk.classify import SklearnClassifier
from sklearn.svm import SVC
from nltk.classify import MaxentClassifier
import heapq
import numpy as np
import sys
from helper import *
sys.path.insert(0, '../')
from definitions import *
sys.path.in... |
import random
list5 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
N = (random.choice(list5) + random.choice(list5))
S = (random.choice(list5) * random.choice(list5))
G = (random.choice(list5) / random.choice(list5))
Fall = [N, S, G]
while True:
for x in Fall:
if x > 50:
print(x)
print("its larger than then 50")
... |
from typing import Optional, List, Tuple
from presidio_analyzer import Pattern, PatternRecognizer
class AuTfnRecognizer(PatternRecognizer):
"""
Recognizes Australian Tax File Numbers ("TFN").
The tax file number (TFN) is a unique identifier
issued by the Australian Taxation Office
to each taxpay... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.9.3
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... |
"""
Word Vectors module
"""
import os
import pickle
import tempfile
from errno import ENOENT
from multiprocessing import Pool
import numpy as np
# Conditionally import Word Vector libraries as they aren't installed by default
try:
import fasttext
from pymagnitude import converter, Magnitude
WORDS = Tru... |
# Generated by Django 2.2.1 on 2019-06-17 01:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0006_auto_20190616_2354'),
]
operations = [
migrations.AlterField(
model_name='student',
name='name',
... |
# Generated by Django 3.0.7 on 2020-06-28 01:18
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('Form', '0003_auto_20200627_2233'),
]
operations = [
migrations.RemoveField(
model_name='lead',
... |
"""
Functions needed for dealing with age stratification
"""
def add_zero_to_age_breakpoints(breakpoints):
"""
append a zero on to a list if there isn't one already present, for the purposes of age stratification
:param breakpoints: list
integers for the age breakpoints requested
:return: lis... |
from .analysis import polyfit
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
def plot_water_levels(station, dates, levels):
#plot the dates and water levels
plt.plot(dates, levels, label = 'Water level')
# Add axis labels, rotate date labels and add plot title
plt.xlabel('date')
... |
import os
import re
# room, sector, checksum
p = re.compile("([\w-]+)-(\d+)\[(\w+)\]")
def checksum(room_name):
counts = {}
for char in room_name.replace('-', ''):
if char in counts:
counts[char] += 1
else:
counts[char] = 1
result = []
for item in sorted(counts.items(), key=lambda pair: (-pair[1], pa... |
type = 'SMPLifyX'
body_model = dict(
type='SMPLX',
gender='neutral',
num_betas=10,
use_face_contour=True,
keypoint_src='smplx',
keypoint_dst='smplx',
model_path='data/body_models/smplx',
batch_size=1)
stages = [
# stage 1
dict(
num_iter=10,
fit_global_orient=Tru... |
import time
import copy
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
import flowrect
from flowrect.simulations.util import calculate_age, calculate_mt, eta_SRM
from flowrect.simulati... |
"""
Module with scrounger configurations
"""
# get home directory
from os import getenv
# Logging
import logging as _logging
#_LOGGING_FORMAT = "%(asctime)17s - %(module)8s.%(funcName).10s : %(message)s"
_LOGGING_FORMAT = "%(asctime)17s - %(module)30s : %(message)s"
_LOGGING_TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
_formatt... |
# Copyright 2019 The Bazel 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 applicable la... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from send_email import send_email
from sqlalchemy.sql import func
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://jessequinn:9155@localhost/height_collector'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'... |
from unitmeasure import converters
from unitmeasure import dimension
from unitmeasure.util import classproperty
class UnitVolume(dimension.Dimension):
class Symbol(object):
megaliters = "ML"
kiloliters = "kL"
liters = "L"
deciliters = "dl"
centiliters = "cL"
milli... |
"""
Django settings for website project.
Generated by 'django-admin startproject' using Django 1.10.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... |
import argparse
from pprint import pprint
from experiments.classification import ClassificationExperiment
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--arch', default='resnet', choices=['alexnet', 'resnet'],
help='architecture (default: alexnet)')
parser.ad... |
import os
import pytest
import torch
import tests.base.utils as tutils
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.core import memory
from pytorch_lightning.trainer.distrib_parts import (
parse_gpu_ids,
determine_root_gpu_device,
)
from ... |
from app import cache
from github import get, compute
# Note: This can be further parallelized using grequests or celery
def get_data_async():
cached_resources = cache.get("resources_to_cache")
if not cached_resources:
return
for resource in cached_resources:
(data, status, header) = get... |
from django import template
register = template.Library()
@register.filter(name='times')
def times(number):
return range(1,number+1) |
#!/usr/bin/python
#coding=utf-8
'''
@author: sheng
@license:
'''
SPELL=u'shàngliáo'
CN=u'上髎'
NAME=u'shangliao42'
CHANNEL='bladder'
CHANNEL_FULLNAME='BladderChannelofFoot-Taiyang'
SEQ='BL31'
if __name__ == '__main__':
pass |
# -*- coding: utf-8 -*-
#@+leo-ver=5-thin
#@+node:ekr.20171124080430.1: * @file ../commands/commanderOutlineCommands.py
#@@first
"""Outline commands that used to be defined in leoCommands.py"""
import leo.core.leoGlobals as g
#@+others
#@+node:ekr.20031218072017.1548: ** c_oc.Cut & Paste Outlines
#@+node:ekr.2003121807... |
import copy
import numpy as np
from .base import Visuals
from . import color
from .. import util
from .. import caching
from .. import grouping
from .material import SimpleMaterial, PBRMaterial, empty_material # NOQA
class TextureVisuals(Visuals):
def __init__(self,
uv=None,
... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
# pylint: ... |
# Copyright 2020 The SODA 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 or agreed to in writin... |
# Code written by: Maksim Imakaev (imakaev@mit.edu)
"""
Analyses of polymer conformations
=================================
This module presents a collection of utils to work with polymer conformations.
Tools for calculating contacts
------------------------------
The main function calculating contacts is: :py:fun... |
import gym, random, time
import numpy as np
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import *
import matplotlib.pyplot as plt
""" Q-Network Q(a, s) - TD Learning, Off-Policy, e-Greedy Exploration (GLIE)
Q(S, A) <- Q(S, A) + alpha * (R + lambda * Q(newS, newA) - Q(S, A))
delta_w = R + l... |
import pycom
import machine
from machine import Timer, Pin, PWM
from helpers import *
import _thread
import utime
import adc
from sht1x import SHT1X
from pms5003 import PMS5003, PMSData
import persistence
from datapoint import DataPoint
from ds3231 import DS3231
pycom.heartbeat(False)
VERSION = '0.7.0'
alive_timer ... |
import yaml
class CConfig:
def __init__(self, configfile):
self._conf = None
self.loadConfig(configfile)
def loadConfig(self, configfile):
if not configfile:
configfile = "config.yaml"
try:
with open(configfile, "r") as ymlfile:
conf = y... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, unicode_literals, absolute_import
##/usr/bin/env python
##
## Author: Bertrand Lacoste
## Modified from daemon.runner and from watcher (https://github.com/splitbrain/Watcher, original work https://github.com/gregghz/Watcher)
#... |
#!/usr/bin/env python3
from contextlib import contextmanager
from os import path as osp
import joblib
import pandas as pd
from sklearn.ensemble import AdaBoostClassifier
from sklearn.svm import SVC
DEMO_DIR = osp.abspath(osp.dirname(__file__))
DATA_DIR = osp.join(DEMO_DIR, "data")
MODELS_DIR = osp.join(DEMO_DIR, "m... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
import predictive_punter
import pytest
@pytest.fixture(scope='module')
def seed_command(database_uri):
predictive_punter.SeedCommand.main(['-d', database_uri, '2016-2-1', '2016-2-2'])
def test_samples(database, seed_command):
"""The seed command should populate the database with the expected number of samp... |
# Copyright (c) 2019 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 appli... |
from flask import Flask,request,jsonify
from flask_cors import CORS
from bert import Ner
app = Flask(__name__)
CORS(app)
model = Ner("out_base")
@app.route("/predict",methods=['POST'])
def predict():
text = request.json["text"]
try:
out = model.predict(text)
return jsonify({"result":out})
... |
# http://github.com/timestocome
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import signal
# use data leveled, log'd and otherwise smoothed in
# https://github.com/timestocome/StockMarketData
# to do some analysis
# http://www.mdpi.com/1999-4893/5/4/588
# after I started worki... |
from typing import List
import pytest
from .common import BaseTestRule
class TestPyPiApiToken(BaseTestRule):
@pytest.fixture(params=[
[
"pypi-AgEIcHlwaS5vcmc" #
"CJGE3ZjdlNzVmLTRhOGEtNGY1MC1iMzEwLWQzZTQ1NmJiYzMzMQ" #
"ACJXsicGVybWlzc2lvbnMiOiAidXNlciIsICJ2ZXJzaW9uI... |
"""
Django Unit Test and Doctest framework.
"""
from django.test.client import Client, RequestFactory
from django.test.testcases import (
TestCase, TransactionTestCase,
SimpleTestCase, LiveServerTestCase, skipIfDBFeature,
skipUnlessDBFeature
)
from django.test.utils import (ignore_warnings, modify_settings... |
"""
Copyright (C) 2017 Cosmin Ștefănică
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, publish, distribut... |
import scrapy
from kingfisher_scrapy.base_spider import LinksSpider
from kingfisher_scrapy.util import parameters
class DominicanRepublicAPI(LinksSpider):
"""
Domain
Dirección General de Contrataciones Públicas (DGCP)
Spider arguments
from_date
Download only data from this date onward... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import platform
from spack import *
class IntelOneapiIppcp(IntelOneApiLibraryPackage):
"""Intel oneAPI IPP Crypto.... |
from werkzeug.middleware.http_proxy import ProxyMiddleware
from werkzeug.test import Client
from werkzeug.wrappers import Response
def test_http_proxy(standard_app):
app = ProxyMiddleware(
Response("ROOT"),
{
"/foo": {
"target": standard_app.url,
"host":... |
import argparse
import sys
import logging
import os
import subprocess
import re
SRC_EXTENSION = ".mp4"
LOG_EXTENSION = ".log"
# Instantiate the parser
parser = argparse.ArgumentParser(description="This script renames and/or creates links for WonderStitch batch outputs ")
parser.add_argument("directory", type=str, hel... |
# coding=utf-8
# Copyright 2021 The TensorFlow Datasets 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 appl... |
password="secreto"
entrada=""
suma=0
while suma<3
entrada =input("introduce la palabra secreta")
suma+=1
print("Intento%d\n" %suma)
print ("Utilizaste %d intentos" %suma) |
# Copyright 2020 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... |
from rest_framework import serializers
from menu.models import Review, Category, Item, Country, ItemVariant
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = "__all__"
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = It... |
import pygame
import math
pygame.init()
pi = ('Pi = ' + str(math.pi))
e = ('E = ' + str(math.e))
f = ('F = 0,1,1,2,3,5,8,13...')
p = ('P = 1,2,5,12,29...')
l = ('L = 2,1,3,4,7,11,18,29...')
pl = ('P-L = 2,6,14,34,82...')
display = pygame.display.set_mode((800,600))
pygame.display.set_caption('Nums')
font = pygame.font.... |
#coding=utf-8
import os, sys
sys.path.append(os.getcwd())
from selenium import webdriver
from util.Handle_ini import Handle_ini
import time
wd = webdriver.Chrome()
wd.get("http://tools.jb51.net/tools/jisuanqi/jsq_base.htm")
# 3+2
'''
hi = Handle_ini(ini_file=r'../config/element.ini')
method1, n3 = hi.get_value('sim... |
import sys
import six
from pathlib2 import Path
from ...binding.frameworks.base_bind import PatchBaseModelIO
from ..frameworks import _patched_call, WeightsFileHandler, _Empty
from ..import_bind import PostImportHookPatching
from ...config import running_remotely
from ...model import Framework
class PatchPyTorchMod... |
# Python - 3.6.0
Test.describe('Basic tests')
Test.assert_equals(max_multiple(2, 7), 6)
Test.assert_equals(max_multiple(3, 10), 9)
Test.assert_equals(max_multiple(7, 17), 14)
Test.assert_equals(max_multiple(10, 50), 50)
Test.assert_equals(max_multiple(37, 200), 185)
Test.assert_equals(max_multiple(7, 100), 98)
Test.as... |
import subprocess
from shortest_path import ShortestPath
class AppController:
def __init__(self, manifest=None, target=None, topo=None, net=None, links=None):
self.manifest = manifest
self.target = target
self.conf = manifest['targets'][target]
self.topo = topo
self.net =... |
'''
* Copyright (c) 2021, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
'''
from functools import partial
from multiprocessing.sharedctypes import Value
from models.v... |
from .checkpoint import (
load_checkpoint,
load_state_dict,
save_checkpoint,
weights_to_cpu,
)
from .hooks import (
CheckpointHook,
ClosureHook,
DistSamplerSeedHook,
Hook,
IterTimerHook,
LoggerHook,
LrUpdaterHook,
OptimizerHook,
PaviLoggerHook,
TensorboardLoggerHo... |
# import unittest
# class TestGoodreadsReader(unittest.TestCase):
# def setUp(self):
# def test_get_quotes(self): |
class Hash(object):
def __init__(self, name, hashlen, blocklen):
"""
:param name: Name of hash function algorithm
:type name: str
:param hashlen: HASHLEN = size in bytes of the hash output. Must be 32 or 64.
:type hashlen: int
:param blocklen: BLOCKLEN = size in bytes... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('djangocms_forms', '0004_redirect_delay'),
]
operations = [
migrations.AddField(
model_name='formfield',
... |
import _plotly_utils.basevalidators
class BaseValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name='base', parent_name='bar', **kwargs):
super(BaseValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
array_ok=True... |
"""
Base settings to build other settings files upon.
"""
from pathlib import Path
import environ
ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
# liquidatewallstreet/
APPS_DIR = ROOT_DIR / "liquidatewallstreet"
env = environ.Env()
READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default... |
"""Example: minimal OLS
"""
import pytest
import numpy as np
from numpy.testing import assert_almost_equal, assert_allclose
import sm2.api as sm
@pytest.mark.not_vetted
def test_HC_use():
np.random.seed(0)
nsample = 100
x = np.linspace(0, 10, 100)
X = sm.add_constant(np.column_stack((x, x**2)), prep... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.