content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
job_list = [
"python3 exp_neurolisp.py -o -t suite --dump --path=./test_data/suite_data/",
"python3 exp_neurolisp.py -o -t unify_mem --mem_size=2000 --dump --path=./test_data/unify_data/mem_test/",
"python3 exp_neurolisp.py -o -t unify_mem --mem_size=2500 --dump --path=./test_data/unify_data/mem_test/",
... | python |
# Copyright (c) 2020 ING Bank N.V.
#
# 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, distr... | python |
#!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import json
import unittest
from network_health_service.stats.fetch_stats import get_link_queries, get_node_queries
from network_health_service.stats.metrics import Metrics
class CreateQueryTests(unittest.TestCase):
def setUp(self) -... | python |
import pathlib
import os
from argparse import ArgumentParser
from e3372 import WebAPI, SMSHandler, SMS
config_dir = os.path.join(pathlib.Path.home(), '.e3372-sms-handler')
trusted_phone = ''
def sms_handler(sms: SMS, api: WebAPI):
global trusted_phone
print(f'from={sms.phone}, date={sms.date}, text={sms.t... | python |
# hex
<warning descr="Python version 2.6, 2.7, 3.4, 3.5 do not support underscores in numeric literals">0xCAFE_F00D</warning>
# oct
<warning descr="Python version 2.6, 2.7, 3.4, 3.5 do not support underscores in numeric literals">0o1_23</warning>
<error descr="Python version 3.6 does not support this syntax. It requir... | python |
#!/usr/bin/env python
"""
Generate framework agreement signature pages from supplier "about you"
information for suppliers who successfully applied to a framework.
Usage:
scripts/framework-applications/generate-framework-agreement-signature-pages.py
[-v...] [options]
<stage> <framework> <output_dir... | python |
# Generated by Django 2.2.3 on 2019-10-21 08:40
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('devices', '0001_initial'),
('users', '0001_initial'),
]
operations = [
migrations.AddField(
... | python |
import gevent
from gevent import wsgi
import test__pywsgi
from test__pywsgi import *
del TestHttps
test__pywsgi.server_implements_chunked = False
test__pywsgi.server_implements_pipeline = False
test__pywsgi.server_implements_100continue = False
TestCase.get_wsgi_module = lambda *args: wsgi
if __name__ == '__main__':... | python |
import nau7802py, time
myScale = nau7802py.NAU7802() # Create instance of the NAU7802 class
#
# Begin void setup() equivalent
#
print('Qwiic Scale Example')
if not myScale.begin():
print('Scale not detected. Please check wiring. Freezing...')
while True:
pass
print('Scale detected!')
#
# Begin voi... | python |
import unittest
# These can't be imported until the test_imported_enums_proto module has been built.
Status = None
MessageID = None
ExposesInternalEnumConstantsMessageinternal_enum = None
UsesImportedEnumsMessage = None
class ImportedEnumsTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
gl... | python |
# Generated by Django 3.2.5 on 2021-07-17 13:11
import contest.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_... | python |
import logging
from contextlib import contextmanager, AbstractContextManager
from typing import Callable
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import as_declarative, declared_attr
from sqlalchemy.orm import Session, sessionmaker, scoped_session
logger = logging.getLogger(__name__)
@as_... | python |
from flask import Flask, render_template, redirect, session, request
import random
import datetime
app = Flask(__name__)
app.secret_key = "12345678asdfghjk"
@app.route('/')
def index():
if not 'gold' in session:
session['gold'] = 0
if not 'log' in session:
session['log'] = ["Thanks for joining the game!"]
retu... | python |
from django.apps import AppConfig
class PersonConfig(AppConfig):
name = 'person'
| python |
#
# Copyright 2017-2018 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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... | python |
from hazma.decay import charged_pion, muon, neutral_pion
from hazma.field_theory_helper_functions.common_functions import minkowski_dot as MDot
from hazma.parameters import electron_mass as me
from hazma.parameters import muon_mass as mmu
from hazma.parameters import charged_pion_mass as mpi
from hazma.parameters imp... | python |
# -*- coding: utf-8 -*-
"""Test settings"""
import os
# Set your environment variables for testing or put values here
# user email or phone number
USER_LOGIN = os.getenv('VK_USER_LOGIN', '')
USER_PASSWORD = os.getenv('VK_USER_PASSWORD', '')
# aka API/Client ID
APP_ID = os.getenv('VK_APP_ID')
PHONE_NUMBER = os.getenv... | python |
import cost_funcs.info as info
import cost_funcs.standard as std
import pytest
def test_bounds_eggholder():
assert info.get_bounds(std.eggholder, 2)[0][0] == -512
def test_bounds_michal_dim():
for dim in range(10):
assert len(info.get_bounds(std.michal, dim)) == dim
def test_function_name_eggholde... | python |
import re
from django.core import exceptions as core_exceptions
from api.models import Contributor, ExtendedField, ProductType
from api.facility_type_processing_type import (
get_facility_and_processing_type,
)
def extract_int_range_value(value):
"""
Excel workbooks mat contain decimal values for number_o... | python |
import os
import json
from collections import namedtuple
import shutil
import pytest
import responses
from coincurve import PrivateKey
from requests.exceptions import ConnectionError
import common.receipts as receipts
from common.tools import compute_locator, is_compressed_pk
from common.appointment import Appointment... | python |
import requests
import json
def post_to_rapidapps(body):
url = "https://rapid-apps-2475.eu-gb.mybluemix.net/services/2984dcb289ef8da69bfdc2442546d334"
payload = {
"iduser":body['iduser'],
"firstname":body['firstname'],
"lastname":body['lastname'],
"height":body['height'],
... | python |
# BerylDB - A modular database.
# http://www.beryldb.com
#
# Copyright (C) 2021 Carlos F. Ferry <cferry@beryldb.com>
#
# This file is part of BerylDB. BerylDB is free software: you can
# redistribute it and/or modify it under the terms of the BSD License
# version 3.
#
# More information about our licensing can be fou... | python |
# Generated by Django 3.1.2 on 2021-02-09 12:17
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('mvp', '0016_notification_ratings'),
]
operations = [
migrations.CreateModel(
name='Hub_User',
... | python |
import cv2
import numpy as np
import matplotlib.pyplot as plt
'''
创建一个SURF对象:
cv2.xfeatures2d.SURF_create(, hessianThreshold, nOctaves, nOctaveLayers, extended, upright)
hessianThreshold:默认100
nOctaves:金字塔组数默认4
nOctaveLayers:每组金子塔的层数默认3
extended:默认False,扩展描述符标志,False表示使用64个元素描述符。
upright:默认... | python |
# terrascript/provider/rancher/rancher2.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:25:37 UTC)
import terrascript
class rancher2(terrascript.Provider):
"""Terraform Rancher2 provider"""
__description__ = "Terraform Rancher2 provider"
__namespace__ = "rancher"
__name__ = "ranche... | python |
#!/usr/bin/env python
import rospy
import numpy as np
from nav_msgs.msg import OccupancyGrid
from geometry_msgs.msg import PoseStamped
from tf import TransformListener
from copy import deepcopy
class MapWhiteout:
def map_callback(self, map):
print("received map!")
self.map = map
if self.... | python |
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.feature_selection import SelectPercentile, f_classif
# http://scikit-learn.org/stable/modules/feature_selection.html
# #############################################################################
# Univariate feature s... | python |
#Enter a number and identify whether it is palindrome or not.
n=int(input("Enter a no.:"))
n1=n2=n
count=0
temp=0
ans=0
while n!=0:
n=n//10
count=count+1
#print("count=",count)
count=count-1
while n1!=0:
temp=n1%10
n1=n1//10
ans=ans+(10**count)*temp
count=count-1
#print("ans=... | python |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | python |
import os
from mock import Mock
from mock import patch
from tests.base_unittest import BaseUnitTest
from aceonrivergui.server.game_manager import GameManager
import aceonrivergui.server.message_manager as MM
class MessageManagerTest(BaseUnitTest):
def test_broadcast_config_update(self):
uuids = ["hoge",... | python |
import qt
import numpy as np
import os
import shutil
import sys
import progressbar
from constants import *
fsv = qt.instruments.create('FSV', 'RhodeSchwartz_FSV', address = FSV_ADDRESS)
## FSV parameters
center_frequency = 6018.416185*MHz
span = 2000*Hz
RBW = 10*Hz
numpoints = 501
ref_level = -70 #dB... | python |
"""
This script is used to develop a baseline policy using only the observed patient data via Behavior Cloning.
This baseline policy is then used to truncate and guide evaluation of policies learned using dBCQ. It should only need to be
run once for each unique cohort that one looks to learn a better treatment policy ... | python |
from twisted.internet.defer import inlineCallbacks
from zope.interface import implements
from vumi.dispatchers.base import BaseDispatchWorker
from vumi.middleware import MiddlewareStack
from vumi.tests.helpers import (
MessageHelper, PersistenceHelper, WorkerHelper, MessageDispatchHelper,
generate_proxies, IH... | python |
test_cases = int(input().strip())
for t in range(1, test_cases + 1):
s = input().strip()
stack = []
bracket = {'}': '{', ')': '('}
result = 1
for letter in s:
if letter == '{' or letter == '(':
stack.append(letter)
elif letter == '}' or letter == ')':
if not ... | python |
from typing import Dict, List, Union
from icolos.core.containers.compound import Compound
from icolos.core.containers.perturbation_map import Edge
from icolos.core.workflow_steps.pmx.base import StepPMXBase
from pydantic import BaseModel
from icolos.utils.enums.program_parameters import (
GromacsEnum,
StepPMXEn... | python |
# Generated by Django 3.2.9 on 2022-02-06 17:56
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pet', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='pet',
name='explan... | python |
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Gabor
def Gabor_filter(K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0):
# get half size
d = K_size // 2
# prepare kernel
gabor = np.zeros((K_size, K_size), dtype=np.float32)
# each value
for y in range(K_size):
for x in range(K_size)... | python |
from aoc21.days.day04 import Board, BoardScore
NUMBERS = [
7,
4,
9,
5,
11,
17,
23,
2,
0,
14,
21,
24,
10,
16,
13,
6,
25,
12,
22,
18,
20,
8,
19,
3,
26,
1,
]
BOARD = Board(
[
22,
13,
17,
... | python |
from maza.core.exploit.option import OptEncoder
from maza.core.exploit.payloads import (
GenericPayload,
Architectures,
BindTCPPayloadMixin,
)
from maza.modules.encoders.perl.base64 import Encoder
class Payload(BindTCPPayloadMixin, GenericPayload):
__info__ = {
"name": "Perl Bind TCP",
... | python |
"""
Flask-AntiJs
-------------
Flask-AntiJs is a Flask extension the protects endpoints against
'undefined' javascript values by checking the URL, query params and payloads
and return a 400 (Bad request) response.
"""
from setuptools import setup
version = "0.0.2"
setup(
name='Flask-AntiJs',
version=version,... | python |
import configparser
import json
import os
import subprocess
import sys
import requests
import betamax
from betamax_serializers.pretty_json import PrettyJSONSerializer
import pytest
ABS_PATH = os.path.abspath(os.path.dirname(__file__))
FIXTURES_PATH = ABS_PATH + '/fixtures'
CASSETTES_PATH = FIXTURES_PATH + '/cassett... | python |
"""
Solution to Compound Interest Calculator
"""
if __name__ == '__main__':
principal = input('Enter the Principal: ')
# type checking here
try:
principal = float(principal)
except ValueError:
print('Invalid principal Amount')
exit(0)
rate = input('Enter ... | python |
# encoding: utf-8
"""
Core properties part, corresponds to ``/docProps/core.xml`` part in package.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from datetime import datetime
from ..constants import CONTENT_TYPE as CT
from ..extendedprops import ExtendedProperties
fr... | python |
import pytest
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.utils import timezone
from vms import models
def test_approve(client_admin_factory, employee_factory):
"""
Approving an employee should save the approval information and mark
the employee as activ... | python |
class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
l = 1
r = sum(candies) // k
def numChildren(m: int) -> bool:
return sum(c // m for c in candies)
while l < r:
m = (l + r) // 2
if numChildren(m) < k:
r = m
else:
l = m + 1
retur... | python |
# Generated from grammar/Evans.g4 by ANTLR 4.7.2
from antlr4 import *
if __name__ is not None and "." in __name__:
from .EvansParser import EvansParser
else:
from EvansParser import EvansParser
# This class defines a complete listener for a parse tree produced by EvansParser.
class EvansListener(ParseTreeListe... | python |
from builtins import object
import logging
from twisted.internet import abstract
from twisted.internet.tcp import Server
from twisted.internet import address, fdesc
log = logging.getLogger(__name__)
# AcceptedSocket
class AcceptedSocket(object):
transport = Server
def __init__(self, skt, addr, factory, re... | python |
import unittest
from user import User
from credentials import Credentials
import pyperclip
class TestUser(unittest.TestCase):
"""
Test case that defines the behavior that should be evident in the user class
"""
new_user= User("Mary","Wanjiku","wanjiku254")
new_account_name= Credentials("Instagram","... | python |
symbols = []
exports = [{'type': 'function', 'name': '??$_Getvals@_W@?$time_get@DV?$istreambuf_iterator@DU?$char_traits@D@std@@@std@@@std@@IEAAX_WAEBV_Locinfo@1@@Z', 'address': '0x7ffb3bb2d310'}, {'type': 'function', 'name': '??$_Getvals@_W@?$time_get@GV?$istreambuf_iterator@GU?$char_traits@G@std@@@std@@@std@@IEAAX_WAE... | python |
#!/usr/bin/env python
# FormatTIFFRayonixESRF.py
# Copyright (C) 2011 Diamond Light Source, Graeme Winter
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
#
# Sub class of FormatTiffRayonix to deal with images who have beam centers
# specifie... | python |
from unittest.mock import Mock
import pytest
from sso.user import context_processors
@pytest.fixture
def request_with_next_user_authenticated(rf):
request = rf.get('/', {'next': 'http://www.example.com'})
request.user = Mock(is_authenticated=Mock(return_value=True))
return request
@pytest.fixture
def ... | python |
from typing import Dict
from .expressions import (
Expression, Operation, Wildcard, AssociativeOperation, CommutativeOperation, SymbolWildcard, Pattern, OneIdentityOperation
)
__all__ = [
'is_constant', 'is_syntactic', 'get_head', 'match_head', 'preorder_iter', 'preorder_iter_with_position',
'is_a... | python |
from openzwave.network import ZWaveNode
from openzwave.value import ZWaveValue
from Firefly import logging
from Firefly.components.zwave.zwave_device import ZwaveDevice
from Firefly.const import ACTION_OFF, ACTION_ON, AUTHOR, DEVICE_TYPE_SWITCH, LEVEL, SWITCH
from Firefly.helpers.device_types.switch import Switch
from... | python |
import signal
import os
import subprocess
# Initializes a multi processing worker and prevents the interupt signal to be handled. This should be handled by the
# parent process.
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def minimal_ext_cmd(cmd):
# construct minimal environment
env ... | python |
"""Unit test package for aioxmppd."""
| python |
#! /usr/bin/env python3
# coding: utf-8
# flow@SEA
# Licensed under the MIT License.
import time
import hashlib
import datetime
from binascii import unhexlify
from base58 import b58encode, b58decode
class CommonTool:
@staticmethod
def now():
return time.time()
@staticmethod
def sci_to_str(s... | python |
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
s_len = len(s)
dp = [False] * (s_len+1)
dp[0] = True
for i in range(s_len):
for j in range(i+1, n+1):
... | python |
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# input is a H*W ndarray
def display(npimg):
plt.imshow(npimg, cmap='gray')
plt.show()
if __name__ == '__main__':
images_path = "./HCL2000-100/HCL2000_100_train.npz"
labels_path = "./HCL2000-100/HCL2000_100_train_label.npz"
... | python |
import socket
host, port = '', 8888
listen_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((host, port))
listen_socket.listen(1)
print("listening on port %s" % port)
while True:
client_connection, client_address = l... | python |
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
packageName = "arthur"
import re
versionLine = open("{0}/_version.py".format(packageName), "rt").read()
match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", versionLine, re.M)
versionString = match.group(1)
class Tox(... | python |
import os
from pip._vendor.colorama import Fore
from ws.RLUtils.monitoring.tracing.log_mgt import log_mgt
if __name__ == '__main__':
cwd = os.path.curdir
acwd = os.path.join(cwd, '_tests')
log_dir = os.path.join(acwd, "logs")
fn_log = log_mgt(log_dir, show_debug=False, fixed_log_file=False)[0]
c... | python |
real = float ( input(' Digite o valor em reais: R$'))
#dola = 5.34
dola = real / 5.34
euro = real / 6.25
print (' Convertendo o valor de R${:.2f}, você consegue US${:.2f} ou €{:.2f}.' .format( real,dola, euro))
#print (' Convertendo o valor de R${:.2f}, você consegue US${:.2f} ou € {:.2f}.'.format(real,(real/dola)))
... | python |
# -*- coding: utf-8 -*-
from openprocurement.auctions.core.tests.base import snitch
from openprocurement.auctions.core.tests.blanks.contract_blanks import (
# AuctionContractResourceTest
create_auction_contract_invalid,
get_auction_contracts,
# AuctionContractDocumentResourceTest
not_found,
crea... | python |
matrix = [
#0, 1, 2, 3, 4, 5, 6, 7], #0
[0, 1, 1, 0, 0, 0, 0, 0], #0
[1, 0, 1, 1, 0, 0, 0, 0], #1
[1, 1, 0, 0, 0, 0, 0, 0], #2
[0, 1, 0, 0, 1, 1, 0, 0], #3
[0, 0, 0, 1, 0, 0, 1, 0], #4
[0, 0, 0, 1, 0, 0, 1, 0], #5
[0, 0, 0, 0, 1, 1, 0, 1], #6
[0, 0, 0, 0, 0, 0, 1, 0], #7... | python |
from code.cli import Cli
if __name__ == '__main__':
Cli().run()
| python |
import cv2
import shutil
import os
import numpy as np
from pathlib import Path
from tqdm import tqdm
from utils import get_all_files_in_folder
def create_images_for_labeling():
dirpath = Path('denred0_data/prepare_images_for_labeling/result')
if dirpath.exists() and dirpath.is_dir():
shutil.rmtree(d... | python |
import datetime
import time
from huey import crontab
from hueyx.queues import hueyx
HUEY_Q1 = hueyx('queue1')
HUEY_Q2 = hueyx('queue2')
@HUEY_Q1.task()
def my_task1():
print('my_task1 called')
return 1
@HUEY_Q1.db_task()
def my_db_task1():
print('my_db_task1 called')
return 1
@HUEY_Q1.db_task(he... | python |
"""The FleetGO component."""
| python |
from typing import List
from .expresion_node import ExpressionNode
from .let_node import LetNode
class LetInNode(ExpressionNode):
def __init__(self, let_body: List[LetNode], in_body: ExpressionNode, line: int, column: int):
super(LetInNode, self).__init__(line, column)
self.let_body: List[LetNode]... | python |
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
import pyspark.sql as sql
from pyspark.sql.functions import *
from pyspark.sql.types import *
from collections import defaultdict
from pyspark.sql import functions as F
NUMBER_PRECISION = 2
def addSampleLabel(ratingSamples):
ratingS... | python |
from django.shortcuts import render
# Create your views here.
def home(request):
return render(request, 'website_component/home.html', {'ViewName': request})
| python |
"""
Entradas
Salidas
Impares-->int-->a
"""
a=0
while(a<100):
if(a%2!=0 and a%7!=0):
print(a)
a=a+1 | python |
from pyplan_core.classes.wizards.BaseWizard import BaseWizard
import json
class Wizard(BaseWizard):
def __init__(self):
self.code = "CreateIndex"
def generateDefinition(self, model, params):
nodeId = params["nodeId"]
if model.existNode(nodeId):
base_node = model.getNode(n... | python |
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below the provided parameter value number.
# multiplesOf3and5(10) should return a number.
# multiplesOf3and5(49) should return 543.
# multiple... | python |
# lextab.py. This file automatically created by PLY (version 3.6). Don't edit!
_tabversion = '3.5'
_lextokens = set(['DO', 'REMAINDER_ASSIGN', 'RSHIFT', 'SYNCHRONIZED', 'GTEQ', 'MINUS_ASSIGN', 'OR_ASSIGN', 'VOID', 'STRING_LITERAL', 'ABSTRACT', 'CHAR', 'LSHIFT_ASSIGN', 'WHILE', 'SHORT', 'STATIC', 'PRIVATE', 'LSHIFT... | python |
from vpv.ui.controllers import importer
from pathlib import Path
import pytest
def test_folder_filter():
#path: str, folder_include_pattern: str
assert importer.folder_filter('/mnt/bit_nfs/neil/mutants/output/jag2/20150409_JAG2_E14.5_13.3f_HOM_XX_REC_scaled_4.6823_pixel_14.0001/output/registrations/deformable_... | python |
from django.urls import path,include
from . import views
from bookshop.views import index
from django.contrib.auth import views as auth_views
urlpatterns = [
path('account/register',views.register,name='register'),
path('account/login',views.login,name='login'),
path('dashboard',index,name='dashboard'),
... | python |
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy import wcs
from astropy.io import ascii
# TODO set the
# UC4 296-009008
# (90.140913, -30.99747)
# ASASSN ID AP 18326421 V=12.79
def find_min(xobj,yobj, xlist, ylist):
'find the index of the star closest to position xobj,... | python |
# @file globalclasses.py
# @brief global classes and objects
# -
# MODULE_ARCH:
# CLASS_ARCH:
# README:
# Global variables dependence:
#
#standard
#start.py
#[GAP=FastApp(), life_cycle: always exist]
#used by: start.py, scli.py
#init at: start.globalclasses_init()
global GAP
GAP=None
# refer configobj.readthed... | python |
from http.server import HTTPServer, BaseHTTPRequestHandler
from logger import logger
from config import change_config, get_config
BADREQUEST = 400
handlers = {
'get': [],
'post': []
}
class BaseServer(BaseHTTPRequestHandler):
def match_and_call(self, method):
url = self.path.replace('..', '') #... | python |
'''MIT License
Copyright (c) 2021 Aditya Dangwal
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,... | python |
from data_collection.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "E07000107"
addresses_name = (
"local.2019-05-02/Version 1/polling_station_export-2019-03-04Dart.csv"
)
stations_name = (
"local.2019-05-02/Version 1/polling_sta... | python |
import numpy as np
def check_temperature(T, melting_point=3000):
"""
Check if an instantaneous temperature will melt the divertor.
"""
if T > melting_point:
print("Destroyed divertor!")
melted = True
elif T <= 0:
raise ValueError("Unphysical temperature value!")
else:... | python |
# T-SNEを用いた文章分散表現の可視化
import sys, os
sys.path.append('../')
from src import *
import matplotlib.pyplot as plt
import japanize_matplotlib
import numpy as np
from scipy import sparse
def visualize(xs, ys, labels, dataname):
plt.figure(figsize=(15, 15), dpi=300)
emotion = [ "happy", "sad", "angry", "fear/surp... | python |
"""HOBO API"""
from __future__ import annotations
import json
import logging
import time
from typing import Any, List, Optional, Union
import requests
from ..exceptions import ResponseError
# https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
logger = logging.getLogger('hobo_iot')
# logger.setLeve... | python |
from Lib.statistics import mean, harmonic_mean, median, mode, median_low, median_high, median_grouped, stdev, pstdev, \
pvariance, variance, StatisticsError
class Statistics(object):
"""The library used to define statistical outputs"""
def __init__(self):
self.allTimers = []
self... | python |
"""Simple test for using adafruit_motorkit with a DC motor"""
import time
import board
from adafruit_motorkit import MotorKit
kit = MotorKit(i2c=board.I2C())
kit.motor1.throttle = 1.0
time.sleep(0.5)
kit.motor1.throttle = 0
| python |
#!/usr/bin/env python
#
#Copyright 2020 Google LLC
#
#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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | python |
from django.conf.urls import url, include
urlpatterns = [
url(r'^oauth2/', include('django_auth_adfs.urls')),
url(r'^oauth2/', include('django_auth_adfs.drf_urls')),
]
| python |
from typing import List, Tuple
from instagrapi.exceptions import ClientError, HashtagNotFound
from instagrapi.extractors import (
extract_hashtag_gql,
extract_hashtag_v1,
extract_media_gql,
extract_media_v1,
)
from instagrapi.types import Hashtag, Media
from instagrapi.utils import dumps
class Hashta... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class ZhimaCreditEpDataRatingQueryResponse(AlipayResponse):
def __init__(self):
super(ZhimaCreditEpDataRatingQueryResponse, self).__init__()
self._amount = None
sel... | python |
# Import from standard library
import logging
import datetime
import math
# Import from third-party
from flask import Flask, render_template, json, request, jsonify, session
import pytz
# Import local files
import DAO.db_connect as db_connect
from config.config import ElasticConfig
def nessus_overview():
try:
... | python |
#!/usr/bin/env python
import distutils.log
import os
import subprocess
from distutils.spawn import find_executable
from setuptools import Command, find_packages, setup
from distutils.command.build import build
class BuildCommand(build):
def run(self):
self.run_command('compile_webui')
build.run(... | python |
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QScrollArea, QVBoxLayout, QWidget
from brainframe_qt.ui.resources import stylesheet_watcher
from brainframe_qt.ui.resources.mixins.style import TransientScrollbarMI
from brainframe_qt.ui.resources.paths import qt_qss_pa... | python |
# coding: utf-8
import os
import logging
import sys
import torch
import time
import copy
# my staff
from models.modules.context_embedder_base import ContextEmbedderBase, BertContextEmbedder, \
BertSeparateContextEmbedder, NormalContextEmbedder, BertSchemaContextEmbedder, BertSchemaSeparateContextEmbedder, \
Ele... | python |
# Copyright 2013 - Noorul Islam K M
#
# 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 w... | python |
"""
Crie um módulo chamado moeda.py que tenha as funções incorporadas aumentar(),
diminuir(), dobro() e metade(). Faça também um programa que importe esse módulo e
use algumas dessas funções.
"""
import moeda
from exercicios.geral import tratamento
p = tratamento.leiaFloat('Digite o preço: R$', 'preço')
print(f'A met... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/5/12 14:44
# @Author : PPq
from __future__ import print_function
import argparse
import os
import shutil
import time
from torch.nn import DataParallel
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import ... | python |
# Copyright (c) 2018 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 app... | python |
from __future__ import print_function
import os
import sys
import re
import json
from copy import deepcopy
# Build job list
###########################################
def job_builder(meta, valid_meta, workflow, job_dir, out_dir, coprocess=None, other_args="", writeimg=False):
"""Build a list of image processing ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.