text stringlengths 2 999k |
|---|
#!/bin/env python
# this was written for python2
# Import cobbler disto, arguments are:
# $1 = http or nfs path to iso
# $2 = arch
# ks file is hardcoded, /var/lib/cobbler/kickstarts/default.ks
# -----------------------------------------------------------
import os
from time import gmtime, strftime
import datetime
im... |
# Generated by Django 2.2.19 on 2022-03-28 19:19
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_MODEL),
]
op... |
import json
import operator
import os
from functools import reduce
from typing import Any, Dict, List
from django.db.models.query_utils import Q
from django.urls import reverse
from django.utils.html import strip_tags
from pagetools.search import extra_filter, search_mods
from pagetools.views import PaginatorMixin
f... |
import json
import os
def write_to_file(file_path, value):
"""
Write value to file.
"""
directory = os.path.dirname(file_path)
os.makedirs(directory, exist_ok=True)
if not isinstance(value, str):
value = str(value)
fout = open(file_path, "w")
fout.write(value + "\n")
fout.c... |
from fabric.operations import local
def debug():
local("sudo chmod +x ./tribblemaker.py")
local("echo -n '{0}' | {1} tribblemaker.py".format(
open("test_input.txt", "r").read(), open("interpreter.txt", "r").read()))
def test():
local("sudo chmod +x ./tribblemaker.py")
local("sudo bash test_cha... |
import os
import re
import unittest
import json
from troposphere.template_generator import TemplateGenerator
try:
u = unicode
except NameError:
u = str
class TestTemplateGenerator(unittest.TestCase):
maxDiff = None
# those are set by create_test_class
filename = None
expected_output = None
... |
"""
Helper code for plotting GPU utilization over time.
See also
---------
rlscope.profiler.cpu_gpu_util
"""
import os
import shutil
from os.path import join as _j, abspath as _a, exists as _e, dirname as _d, basename as _b
from rlscope.parser.common import *
def experiment_config_path(directory):
path = _j(direc... |
#!/usr/bin/python2.5
# Copyright (C) 2011 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 la... |
#!/usr/bin/env python3
import picamera
import rospy
import os
from sensor_msgs.msg import CompressedImage
class CamBuffer:
def __init__(self, width=640, height=480):
self.width = width
self.height = height
self.data = None
def write(self, s):
self.data = s
d... |
from django.apps import AppConfig
class AutomagicRestConfig(AppConfig):
name = 'automagic_rest'
|
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
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 wr... |
# -*- encoding: utf-8 -*-
r"""
Graphics objects
This file contains the definition of the class :class:`Graphics`.
Usually, you don't call the constructor of this class directly
(although you can do it), you would use :func:`plot` instead.
AUTHORS:
- Jeroen Demeyer (2012-04-19): split off this file from plot.py (:tra... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
from airbyte_cdk.models import AirbyteStream
from pygsheets import Worksheet
from .buffer import WriteBufferMixin
from .spreadsheet import GoogleSheets
class GoogleSheetsWriter(WriteBufferMixin):
def __init__(self, spreadsheet: GoogleSheets):
... |
# Just a test file to upload to a pypi instance.
from distutils.core import setup
setup(
name = 'mypackage',
packages = ['mypackage'], # this must be the same as the name above
version = '0.1',
description = 'A random test lib',
author = 'Jacob Smullin',
author_email = 'jsmullin@ea.com',
url = 'https://g... |
# Copyright (C) 2019 Advanced Media Workflow Association
#
# 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... |
# Copyright (c) 2018, NVIDIA CORPORATION.
import pytest
import numpy as np
import pandas as pd
import pyarrow as pa
from librmm_cffi import librmm as rmm
import cudf as gd
from cudf.dataframe.dataframe import Series, DataFrame
from cudf.dataframe.buffer import Buffer
from cudf.settings import set_options
from iter... |
from django.core.paginator import Paginator, InvalidPage
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from livesettings import config_value
from product.views import display_featured
from satchmo_utils.views import bad_or_m... |
# -*- coding: utf-8 -*-
import logging
import re
from django.core.exceptions import ValidationError
from osf.models import OSFUser
from osf.utils import sanitize
logger = logging.getLogger(__name__)
def has_anonymous_link(node, auth):
"""check if the node is anonymous to the user
:param Node node: Node wh... |
# Set plugin = True
plugin = True
plugin_dir = 'plugin/radar-v3/'
find_unused_parameters = True
#model = dict(
# type='UNet',
# in_channels=3,
# out_channels=1,
# base_channels=16,
# num_stages=5,
# strides=(1, 1, 1, 1, 1),
# enc_num_convs=(2, 2, 2, 2, 2),
# dec_num_convs=(2, 2, 2, 2),
# d... |
"""Requirements specific to SQLAlchemy's own unit tests.
"""
from sqlalchemy import util
import sys
from sqlalchemy.testing.requirements import SuiteRequirements
from sqlalchemy.testing import exclusions
from sqlalchemy.testing.exclusions import \
skip, \
skip_if,\
only_if,\
only_on,\
fails_... |
import datetime
from vit.formatter import DateTime
# TODO: Remove this once tasklib bug is fixed.
from tasklib.serializing import SerializingObject
serializer = SerializingObject({})
class UdaDate(DateTime):
def format(self, dt, task):
if not dt:
return self.markup_none(self.colorize())
... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 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 logic for skipping signature validation on old blocks.
Test logic for skipping signature validati... |
LINE_CHANNEL_ACCESS_TOKEN = ""
LINE_CHANNEL_SECRET_TOKEN = ""
ZOMATO_API_KEY = ""
GOOGLE_MAPS_API_KEY = ""
WEATHER_MAP_API = ""
DATABASE_URI = ""
|
import unittest
from server_commands import ServerCommandsTestCase
from connection_pool import ConnectionPoolTestCase
from pipeline import PipelineTestCase
from lock import LockTestCase
from pubsub import PubSubTestCase, PubSubRedisDownTestCase
use_hiredis = False
try:
import hiredis
use_hiredis = True
except ... |
import hashlib
import random
import logging
from sawtooth_sdk.protobuf.batch_pb2 import BatchHeader, Batch
from sawtooth_sdk.protobuf.transaction_pb2 import Transaction, TransactionHeader
from . import helper as helper
from .protobuf.payload_pb2 import TransactionPayload, Account, Token, Transfer, Heartbeat, BalanceAt... |
from common.ulam_spiral import *
from common.primes import *
SIEVE = PrimeSieve(100000)
def prime_ratio_below(limit):
corners_seen = 1
primes_seen = 0
n = 3
for corners in ulam_spiral_corners_except_center():
primes_seen += len(filter(is_prime, corners))
corners_seen += len(corners)
... |
while True:
s = input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
print('Too small')
continue
print('Input is of sufficient length')
# 自此处起继续进行其它任何处理 |
from . import *
from udsoncan.Response import Response
from udsoncan.exceptions import *
class ReadMemoryByAddress(BaseService):
_sid = 0x23
_use_subfunction = False
supported_negative_response = [ Response.Code.IncorrectMessageLegthOrInvalidFormat,
... |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
#... |
# -*- coding: utf-8 -*-
from .ext import init_app
from flask import Flask
import config
app = Flask(__name__,
# remap to distributed static files
static_url_path='/static',
static_folder='static/dist'
)
app.config.from_object(config)
init_app(app)
|
#
# PySNMP MIB module BLUECOAT-SG-AUTHENTICATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BLUECOAT-SG-AUTHENTICATION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:22:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... |
from __future__ import division
from physicsTable import *
from physicsTable.constants import *
import os, sys
import pygame as pg
from showTrials import *
# Open screenshot
pg.init()
scshot = pg.image.load('RGScShot_Arrow.png')
# Make trial plot
trsc = drawPath('RTr_Bl3_8',40)
# Transform together
trdims = trsc.get... |
import inspect
def execute_all_tests_in_current_file(mod):
all_functions = inspect.getmembers(mod, inspect.isfunction)
for key, value in all_functions:
if key.startswith('test_'):
print(">>>>>>>> executing test [" + key + "]")
value()
|
from __future__ import annotations
from typing import Any, Dict, List, Tuple, Union, TYPE_CHECKING, Callable
from .base_core import InvokableApplicationCommand, _get_overridden_method
from disnake.app_commands import SlashCommand, Option
from disnake.enums import OptionType
from disnake._hub import _ApplicationCommand... |
# Copyright (c) SenseTime. All Rights Reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch.nn as nn
class AdjustLayer(nn.Module):
def __init__(self, in_channels, out_channels, center_size=7):
... |
# -*- coding: utf-8 -*-
import pytest
from snl_d3d_cec_verify.result.base import _TimeStepResolver
@pytest.mark.parametrize("index, expected", [
(-3, 0),
(-2, 1),
(-1, 2),
( 0, 0),
... |
# Copyright 2019 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... |
"""
Location Service Module
This package contains the shipping methods defined by Fedex's
LocationService WSDL file. Each is encapsulated in a class for
easy access. For more details on each, refer to the respective class's
documentation.
"""
from ..base_service import FedexBaseService
class FedexSearchLocationRe... |
from datetime import datetime
from sqlite3 import PARSE_DECLTYPES, Connection, register_adapter
def create_connection() -> Connection:
register_adapter(datetime, datetime.isoformat)
c = Connection("battle.db", detect_types=PARSE_DECLTYPES)
with c:
c.execute(
"""
create tabl... |
# -*- coding: utf-8 -*-
'''
The default file server backend
This fileserver backend serves files from the Master's local filesystem. If
:conf_master:`fileserver_backend` is not defined in the Master config file,
then this backend is enabled by default. If it *is* defined then ``roots`` must
be in the :conf_master:`fil... |
gold = int(input())
price = input()
price_for_number = [int(i) for i in price.split(" ")]
number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
mark_for_number = []
for i in range(0, 9):
mark_for_number.append(number[i] / price_for_number[i])
num = []
max_mark = mark_for_number.index(max(mark_for_number))
while gold >= 0:
if gold -... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytz
import datetime
from django.test import TestCase
from django.utils import timezone
from ..utils import timezone as utils_timezone
from ..utils.timezone import timezones
class UtilsTimezoneTests(TestCase):
def test_timezones(self):
... |
if __name__ == "__main__":
import os
import numpy as np
import pandas as pd
import sys
import copy
if len(sys.argv) != 5:
raise Exception('Number of params incorrect')
dataFile = sys.argv[1]
weights = sys.argv[2]
impacts = sys.argv[3]
resultFile = sys.argv[4]
#note... |
#!/usr/bin/env python
# Wenchang Yang (wenchang@princeton.edu)
# Fri Oct 26 15:20:24 EDT 2018
from .util import get_land
from .amo import cal_amo_index
from .ipo import cal_ipo_index
|
'''
Created by auto_sdk on 2015.06.23
'''
from aliyun.api.base import RestApi
class Rds20130528RevokeAccountPrivilegeRequest(RestApi):
def __init__(self,domain='rds.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.AccountName = None
self.DBInstanceId = None
self.DBName = None
def getapiname(s... |
# -*- coding: utf-8 -*-
from .config import Config
import json, requests, urllib
class Server(Config):
_session = requests.session()
timelineHeaders = {}
JungelpangHeaders = {}
Headers = {}
def __init__(self):
self.Headers = {}
self.channelHeaders = {}
Config... |
'''
Construir um algoritmo que calcule o valor do novo salário
com reajuste
Nome: Edson Ricardo Czarneski
Disciplina: Programação II - Python
Data: 13/01/2018
'''
salario = float(input('Digite o valor do funcionário: R$'))
porc = int(input('Digite o valor de reajuste em %: '))
novo = (salario * porc/100) +... |
# 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... |
"""Various helper functions"""
import os
from PyQt5 import QtWidgets, QtCore
import cv2
def disconnect(signal, *args, **kwargs):
"""Disconnects the signal, catching any TypeError"""
try:
signal.disconnect(*args, **kwargs)
return True
except TypeError:
pass
else:
retur... |
from polyphony import testbench
class D:
def __init__(self, x):
self.x = x
class C:
def __init__(self, x, y):
self.d1 = D(x)
self.d2 = D(y)
def composition02(x, y):
c = C(x, y)
a = c.d1.x + c.d2.x
c.d1.x = 10
return a + c.d1.x
@testbench
def test():
assert 13 == c... |
from entities.ships.allies.ally import Ally
from utils.ids.projectile_id import ProjectileID
"""A friendly Citadel ship.
"""
class Citadel(Ally):
"""Constructs the citadel.
"""
def __init__(self, hp, shield, x, y, speed, fire_rate, *args, **kwargs):
super().__init__(hp, shield, x, y, speed, fire... |
import torch
from rlf.algos.il.gaifo import GaifoDiscrim
from rlf.algos.nested_algo import NestedAlgo
from goal_prox.method.goal_gail_algo import GoalGAILAlgo
from goal_prox.method.goal_gail_dataset import GoalGAILTrajDataset
class GoalGAIL(NestedAlgo):
def __init__(self, agent_updater=GoalGAILAlgo(), get_discri... |
from codecs import open
from os import path
from setuptools import setup
BASE_DIR = path.abspath(path.dirname(__file__))
with open(path.join(BASE_DIR, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='stdin-tagger',
version='1.1.0',
description='decorate stdin with curre... |
from setuptools import setup
setup(
name='pip-autoremove-3',
version='0.10.2',
description='Remove a package and its unused dependencies',
py_modules=['pip_autoremove'],
license='Apache License 2.0',
url='https://github.com/imba-tjd/pip-autoremove',
entry_points='''
[console_scripts]
... |
#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
"""A tiny Python program to check that Python is working.
Try running this program from t... |
try:
import importlib.resources as resources
except ModuleNotFoundError:
import importlib_resources as resources
from itertools import takewhile
import os
from pathlib import Path
import shutil
import subprocess as sp
import sys
from typing import Dict, Iterable, Optional, Tuple
with resources.path('pyscreener... |
# -*- coding: utf-8 -*-
import os, sys, pdb
import numpy as np
import deepdish as dd
from time import time
import matplotlib.pyplot as plt
from sklearn import manifold
from yellowbrick.text import TSNEVisualizer
# knee = dd.io.load('./data/feas1646_auto.h5')
knee = dd.io.load('./data/tsne/vgg19_feas1656_manual.h5')
... |
import requests
import pandas as pd
import numpy as np
from pycoingecko import CoinGeckoAPI
import time
from datetime import datetime
scriptPath = __file__
path = scriptPath[:-35] + '/data/'
filepath = path + 'LMPoolData_ShortTerm.csv'
while True:
start_time = pd.Timestamp.now()
print('Get data at '+str(sta... |
"""
Logging in basically means getting the custom_sessionid and VIN, which are used to make
every subsequent request.
"""
from Crypto.Cipher import Blowfish
import requests
import base64
def login(username, password, region_code='NNA', initial_app_strings='9s5rfKVuMrT03RtzajWNcA'):
baseprm = b'88dSp7wWnV3... |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import re
import time
import datetime
from . import helpers
from . import exceptions
class Tenant:
"""
Collect tenant metrics from the APIC
"""
def __init__(self, check, api, instance, instanc... |
from glob import glob
from os.path import splitext, basename
from setuptools import setup, find_packages
setup(
name='macie-slack',
version='0.7.0',
license='MIT License',
packages=find_packages('code/src'),
package_dir={'': 'code/src'},
py_modules=[
splitext(basename(path))[0] for pat... |
import MySQLdb
class MysqlAccessor:
def __init__(self, hostname, dbname, username, passwdstr):
'''
コンストラクタ
MYSQLへ接続し、カーソルを取得する。
'''
self.conn = MySQLdb.connect(
user = username,
passwd = passwdstr,
host = hostname,
... |
"""
MicroService configuration file.
"""
from __future__ import division
import os
import socket
from WMCore.Configuration import Configuration
# globals
HOST = socket.gethostname().lower()
ROOTDIR = os.getenv('MS_STATIC_ROOT', os.getcwd())
config = Configuration()
main = config.section_("main")
srv = main.section_(... |
# This file is part of Buildbot. Buildbot 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, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
import os
import fcntl
import signal
import json
import numpy as np
from selfdrive.hardware import TICI
CONF_PATH = '/data/ntune/'
CONF_LQR_FILE = '/data/ntune/lat_lqr.json'
ntunes = {}
def file_watch_handler(signum, frame):
global ntunes
for ntune in ntunes.values():
ntune.handle()
class nTune():
def __... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) "Neo4j"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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
#... |
# 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 numpy as np
from math import factorial as std_factorial
def hello(name: str) -> str:
return f"Hello {name}!!"
# Implement factorial for numpy arrays:
factorial = np.vectorize(std_factorial)
|
import json
import logging
import subprocess
import re
from conf.config import VOLATILITY_PATH
class MemoryDump:
def __init__(self, dump_path):
self.profile = None
self.memory_path = dump_path
logging.info('Loaded memory dump: {}'.format(self.memory_path))
def identify_profile(self)... |
from nltk.tree import Tree as Tree
from binary import *
Binary = Binary()
class Why:
def is_why(self, tree):
for t in tree.subtrees(lambda t: t.label() == "SBAR"):
if "because" in t.leaves() or "since" in t.leaves() or "so" in t.leaves():
return True
return False
def remove_SBAR(self, tree):
top_l... |
class Solution:
def peakElement(self,a, n):
if n==1:
return 0
# Code here
for i in range(n-1):
if a[i]>a[i+1]:
return i
if i==n-2:
return n-1
if __name__=='__main__':
t = int(input())
for i in range(t):
n... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
"""
This module updates the userbot based on Upstream revision
"""
from os import remove, execle, path, makedirs, gete... |
#!/usr/bin/env python2.7
"""
This is a simple program to query a running
GPUVerifyRise4Fun instance with a query.
Note any arguments passed after `kernel` will
be passed to GPUVerify instance running via
GPUVerifyRise4Fun.
"""
import argparse
import clientutil
import sys
import logging
import pprint
import urllib2
imp... |
"""
WSGI config for Django-Api project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION... |
from .generalmatrix import Matrix
from .squarematrix import SquareMatrix
|
def tokenize(s):
return s.replace('(', ' ( ').replace(')', ' ) ').split()
def read_from(tokens):
if len(tokens) == 0:
raise SyntaxError('unexpected EOF while reading')
token = tokens.pop(0)
if '(' == token:
L = []
while tokens[0] != ')':
L.append(read_from(token... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸 (Blueking) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may... |
# -*- coding: utf-8 -*-
#
# LNC: Local Notification Center
#
# Written in 2019 by Moky <albert.moky@gmail.com>
#
# ==============================================================================
# MIT License
#
# Copyright (c) 2019 Albert Moky
#
# Permission is hereby granted, free of ch... |
from typing import Any
from boa3.builtin import public
from boa3.builtin.nativecontract.gas import GAS
from boa3.builtin.type import UInt160
@public
def main(from_address: UInt160, to_address: UInt160, amount: int, data: Any) -> bool:
return GAS.transfer(from_address, to_address, amount, data)
|
#!/home/sevmardi/github/ml-projects/Text-Annotation-Tool/text-anno-tool/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
import os
# os.system('gcc -shared src/farthest_point_sampling.cpp -c -o src/farthest_point_sampling.cpp.o -fopenmp -fPIC -O2 -std=c++11')
os.system('cl.exe src/farthest_point_sampling.cpp /c /Fo"src/farthest_point_sampling.obj" /MD /EHsc /openmp /O2 /std:c++14')
from cffi import FFI
ffibuilder = FFI()
with open(os... |
#Erzeugung verschiedener Sternchenmuster
for i in range(3):
print("*","*","*","*")
print()
for i in range(5):
print((4-i)*" ",(i+1)*"* ",(i+1)*"* ")
print()
for i in range(5):
print((i)*" ",(5-i)*"* ",(5-i)*"* ")
print()
for i in range(4): #i fängt bei 0 an
print((3-i)*" ",(2*i... |
import operator
import numpy as np
class OpsMixin:
"""
Mixin for common binary operators
"""
def _binary_op(self, other, f, reflexive=False):
raise NotImplementedError
def __add__(self, other):
return self._binary_op(other, operator.add)
def __sub__(self, other):
re... |
#!/usr/bin/python
'''Controls the hud UI and resets the video stream as necessary.'''
import roslib; roslib.load_manifest('reefbot_hudui')
import rospy
import subprocess
import os.path
import sys
import re
import os
import signal
import multiprocessing
def WatchVideoThread(proc):
errorWatcher = VideoErrorWatcher(pro... |
"""The base Controller API
Provides the BaseController class for subclassing, and other objects
utilized by Controllers.
"""
from pylons import c, cache, config, g, request, response, session
from pylons.controllers import WSGIController
from pylons.controllers.util import abort, etag_cache, redirect_to
from pylons.de... |
"""QuantumComputer Module
Defines a quantum circuit with an input register and a memory register onto which
instructions can be encoded as a bitstring. The core quantum computer circuit executes
the instructions. The state of the memory register is read out and returned to the
user.
"""
import numpy as np
from qiski... |
from cereal import car
from selfdrive.car import dbc_dict
AudibleAlert = car.CarControl.HUDControl.AudibleAlert
VisualAlert = car.CarControl.HUDControl.VisualAlert
# Car button codes
class CruiseButtons:
RES_ACCEL = 4
DECEL_SET = 3
CANCEL = 2
MAIN = 1
#car chimes: enumeration from dbc file. C... |
# Copyright 2016 Red Hat, Inc.
# 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... |
import asyncio
from smbus2_asyncio import SMBus2Asyncio
from brick.device import Device, register_device
from brick.hardware.i2c import i2c_manager
@register_device()
class I2CDetect(Device):
def __init__(self, i2c_bus=0, **kwargs):
super().__init__(**kwargs)
self.bus = i2c_manager.get_bus(i2c_bus... |
import time
import requests
from armada_command import armada_api
from armada_command.scripts.compat import json
from armada_command.scripts.update import VERSION_CACHE_FILE_PATH
from armada_command.scripts.utils import get_logger, SyncOpen, suppress_exception, is_valid_response
logger = get_logger(__file__)
@supp... |
"""PSF Generator Module based on Fast Gibson Lanni Approximation
This is the exact same implementation (used with permission from
http://kmdouglass.github.io/posts/implementing-a-fast-gibson-lanni-psf-solver-in-python.html)
"""
import argparse
import json
from collections import OrderedDict
# ##################
# Gi... |
"""
Targeted grid search with line-robust BSGL statistic
====================================================
Search for a monochromatic (no spindown) signal using
a parameter space grid (i.e. no MCMC)
and the line-robust BSGL statistic
to distinguish an astrophysical signal from an artifact in a single detector.
"""
... |
#coding=utf8
# Django settings for dbss project.
import os
from django.conf import global_settings
import dbss.local_settings
DEBUG = False
TEMPLATE_DEBUG = False
DEFAULT_FROM_EMAIL = dbss.local_settings.DEFAULT_FROM_EMAIL
EMAIL_HOST= dbss.local_settings.EMAIL_HOST
EMAIL_PORT = dbss.local_settings.EMAIL_PORT
EMAIL_HOS... |
import random
from decimal import Decimal
import pytest
from prices import Money, TaxedMoney
from .....account.models import User
from .....order import OrderEvents, OrderStatus
from .....order.models import Fulfillment, FulfillmentLine, Order, OrderEvent, OrderLine
from .....payment import ChargeStatus
from .....pay... |
"""
Sphinx extension to add ReadTheDocs-style "Edit on GitHub" links to the
sidebar.
Loosely based on https://github.com/astropy/astropy/pull/347
"""
import os
import warnings
__licence__ = 'BSD (3 clause)'
def get_github_url(app, view, path):
return '{root_url}/{project}/{view}/{branch}/{prefix}/{path}'.form... |
from django.urls import reverse, resolve
from bestmatchfinder import views
class TestUrls:
def test_graphs_home(self):
path = reverse('graphs_home')
assert resolve(path).view_name == 'graphs_home'
def test_combo(self):
path = reverse('combo')
assert resolve(path).view_name ==... |
import unittest
from conans.test.utils.tools import TestClient, TestServer
from conans.test.utils.cpp_test_files import cpp_hello_conan_files
from conans.model.ref import ConanFileReference, PackageReference
from conans.util.files import save
import os
class UploadTest(unittest.TestCase):
def not_existing_error_... |
import requests
import requirements
from collections import OrderedDict
from packageurl import PackageURL
from packaging.utils import canonicalize_version
from packaging.version import parse as packaging_parse
from cyclonedx.bom import generator
from cyclonedx.models import *
DEFAULT_PACKAGE_INFO_URL = "https://pypi... |
import sys
import os
import numpy as np
from attrdict import AttrDict
import argparse
import time
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import yaml
from pprint import pprint
from paddlenlp.transformers import TransformerModel
from paddlenlp.transformers import position_encoding_init
f... |
total = 0
for number in range(2, 101, 2):
total += number
print(total) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.