content stringlengths 5 1.05M |
|---|
from numba import jit, njit
@njit(fastmath=True)
def numba_compare_images_2(image_to_warp, target_image, target_image_not_smoothed, affine_matrix, m_per_height_unit, match_threshold_m=0.07, weight_by_height=True):
target_image_not_smoothed_height, target_image_not_smoothed_width = target_image_not_smoothed.shape
... |
from django.shortcuts import render,redirect,reverse
from django.http import JsonResponse,HttpResponse,HttpResponseNotAllowed
# Create your views here.
def No_ne(req):
return render(req,'lianxi_app/8000.html')
def my_json(req):
data = {
"name":"张定",
'age':23,
'gender':'男',
'con... |
"""
============================
Draw flat objects in 3D plot
============================
Demonstrate using pathpatch_2d_to_3d to 'draw' shapes and text on a 3D plot.
"""
import matplotlib as mpl
import matplotlib.pyplot as pl
from matplotlib.patches import Circle, PathPatch, Rectangle
# register Axes3D class with m... |
from functools import reduce
from operator import add
import numpy as np
class Patches:
""" Methods for analyzing patch patterns. """
def __init__(self, data):
self.data = data
@property
def keys(self):
return self.data.keys()
def apply(self, func, join):
""" Apply to re... |
from django.shortcuts import render
from .models import Post
# Create your views here.
def trips_home(request):
post_list = Post.objects.all()
return render(request, 'trips/home.html', {
'post_list': post_list,
})
def trips_post_detail(request, pk):
post = Post.objects.get(pk=pk)
return... |
import json
import requests
from battleforcastile.constants import BATTLEFORCASTILE_BACKEND_URL
from battleforcastile.exceptions import MatchCouldNotBeStartedException
def start_match(match_id: int):
url = f'{BATTLEFORCASTILE_BACKEND_URL}/matches/{match_id}/'
r = requests.patch(url, data=json.dumps({
... |
from policy.policy_interface import PolicyInterface
from os import environ
import numpy as np
import tensorflow as tf
# The keras Controller Class.
class KerasPolicy(PolicyInterface):
def __init__(self, state, config):
super().__init__(state, config)
# Avoid using GPU
environ['CUDA_VISIB... |
# Generated by h2py from /usr/include/termios.h
VEOF = 0
VEOL = 1
VEOL2 = 2
VERASE = 3
VWERASE = 4
VKILL = 5
VREPRINT = 6
VINTR = 8
VQUIT = 9
VSUSP = 10
VDSUSP = 11
VSTART = 12
VSTOP = 13
VLNEXT = 14
VDISCARD = 15
VMIN = 16
VTIME = 17
VSTATUS = 18
NCCS = 20
IGNBRK = 0x00000001
BRKINT = 0x00000002
IGNPAR = 0x00000004
PA... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-07-08 09:11
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('instaclone', '0003_auto_20190708_1109'),
]
operations = [
migrations.AlterFie... |
from flask import Flask, render_template
app = Flask(__name__,template_folder='template')
@app.route('/')
def index():
return render_template('template1.html')
if __name__ == '__main__':
app.run(debug=True)
|
from celery import Celery
"""
1. 创建任务
2. 创建Celery实例
3. 在celery中 设置 任务,broker
4. worker
"""
#1. celery 是一个 即插即用的任务队列
# celery 是需要和 django(当前的工程) 进行交互的
# 让celery加载当前的工程的默认配置
#第一种方式:
# import os
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mall.settings")
#第二种方式:
import os
if not os.getenv('DJANGO_SETTINGS_MO... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
from dataclasses import dataclass
from fbpcp.entity.pce_compute import PCECompute
from fbpcp.entity.pc... |
import boto3
import json
from botocore.exceptions import ClientError
from botocore.client import Config
from boto3.dynamodb.conditions import Key, Attr
dynamodb = boto3.resource('dynamodb','ap-southeast-1')
problems_table = dynamodb.Table('codebreaker-problems')
submissions_table = dynamodb.Table('codebreaker-submissi... |
price = float(input("Qual o preço do produto: "))
desconto = (price / 100) * 5
print(f"Seu desconto vai ser igual a R${(price / 100) * 5:.2f}")
print(f"O produto vai ficar por R${price - desconto:.2f}")
|
from django.db import models
# Create your models here.
class HighSchool(models.Model):
featured = models.CharField(max_length=500)
high_school_name = models.CharField(max_length=500)
high_school_logo = models.ImageField(upload_to='high_school/high_school_photos')
high_school_motto = models.CharFiel... |
import collections.abc
import json
import logging
from typing import Union, Sequence
import csv
import numpy as np
logger = logging.getLogger(__name__)
"""
Contains classes necessary for collecting statistics on the model during training
"""
class BatchStatistics:
"""
Represents the statistics collected fro... |
# coding=utf8
# Copyright 2018 JDCLOUD.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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
#!/usr/bin/env python3
"""
Zurich Eye
"""
import unittest
import numpy as np
import numpy.testing as npt
import ze_py.transformations as tf
import ze_trajectory_analysis.align as align
class TestAlign(unittest.TestCase):
def test_align_se3(self):
for i in range(100):
# Random data
... |
import copy
from my_utils.misc.logging import logger
class Trainer():
'''
Trainer for mini-batch stochastic gradient decent.
Args
----------
model :
A model to train.
train_loader : my_utils.DataLoader
DataLoader with training dataset.
'''
def __init__(self, model, trai... |
#!/usr/bin/python
import imp
import subprocess
import argparse
argparser = argparse.ArgumentParser()
argparser.add_argument( "--Traces", type = bool, default=False, help = "Run Traces of the Benchmarks.")
argparser.add_argument( "--Metrics", type = bool, default=False, help = "Runs Metrics of the Benchmarks.")
argpa... |
'''
Check Permutation
Send Feedback
For a given two strings, 'str1' and 'str2', check whether they are a permutation of each other or not.
Permutations of each other
Two strings are said to be a permutation of each other when either of the string's characters can be rearranged so that it becomes identical to the other ... |
from logging import log
import boto3
import uuid
from tempfile import SpooledTemporaryFile
from logger_creator import CreateLogger
logger = CreateLogger('AWSClient', handlers=1)
logger = logger.get_default_logger()
class AWSClient():
def __init__(self) -> None:
try:
self.s3_client = boto3.cli... |
import turtle
import time
import math
l = int(input("Input spiral lenght l = "))
turtle.shape('turtle')
for i in range(l):
t = i / 20 * math.pi
x = (1 + 1 * t) * math.cos(t)
y = (1 + 1 * t) * math.sin(t)
turtle.goto(x, y)
time.sleep(5)
|
import argparse
import json
import os
import pickle
from pathlib import Path
import numpy as np
from tensorflow import gfile
from tensorflow.python.lib.io import file_io
from keras.models import Model, Input
from keras.layers import LSTM, Embedding, Dense, TimeDistributed, Dropout, Bidirectional
from keras.callbacks im... |
# Copyright 2014 CloudFounders NV
#
# 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 writ... |
class Solution:
def beautifulArray(self, n: int) -> List[int]:
A = [i for i in range(1, n + 1)]
def partition(l: int, r: int, mask: int) -> int:
nextSwapped = l
for i in range(l, r + 1):
if A[i] & mask:
A[i], A[nextSwapped] = A[nextSwapped], A[i]
nextSwapped += 1
... |
import numpy as np
import csv
import sys
with open('answer_train.csv', 'w') as f:
K = 3
N = 1000
I = np.identity(K).astype(np.int32)
for k in xrange(K):
yn = I[k, :]
for i in xrange(N):
f.write(','.join([str(yn_i) for yn_i in yn]) + '\n')
|
# <auto-generated>
# This code was generated by the UnitCodeGenerator tool
#
# Changes to this file will be lost if the code is regenerated
# </auto-generated>
import unittest
import units.volume.litres
class TestLitresMethods(unittest.TestCase):
def test_convert_known_litres_to_millilitres(self):
self.assertAlmo... |
NAME = 'volback'
AUTHOR = 'Jam Risser'
VERSION = '0.1.0'
COPYRIGHT = '2017'
BANNER = '''
''' + NAME + ' v' + VERSION + '''
Copyright (c) ''' + COPYRIGHT + ' ' + AUTHOR + '''
'''
CONFIG_FILENAME = 'volback.yml'
|
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
__all__ = [
"Diagnostic",
"DiagnosticCollection",
"DiagnosticError",
"DiagnosticErrorSummary",
]
from dataclasses import dataclass, field, replace
from types import TracebackType
from typing import Any, Iterator, List, Literal, Optional, Type
from beet import FormattedPipelineException, TextFileBase
... |
'''
Defines the NIDAQmx engine interface
General notes for developers
-----------------------------------------------------------------------------
This is a wraper around the NI-DAQmx C API. Refer to the NI-DAQmx C reference
(available as a Windows help file or as HTML documentation on the NI website).
Google can hel... |
#!/bin/env python
import click
@click.command()
@click.option('--invcf')
@click.option('--outvcf')
def main(invcf,outvcf):
file_outvcf=open(outvcf,'w')
with open(invcf) as file_invcf:
for line in file_invcf:
Line=line.strip().split()
if Line[0].startswith('#'):
... |
"""Common configure functions for cdp"""
# Python
import logging
# Unicon
from unicon.core.errors import SubCommandFailure
log = logging.getLogger(__name__)
def configure_cdp(device, interfaces=None):
"""
Enables cdp on target device
Args:
device ('obj'): Device object... |
import pyfx
import numpy as np
from skimage import filters, measure, morphology
class Background:
"""
Class to measure difference between each frame and a background frame.
"""
def __init__(self,bg_frame,blur_sigma=10):
self._bg_frame = bg_frame
self._blur_sigma = blur_sigma
... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import os
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 15:28:00 2020
@author: Frank
"""
from pyspark.sql import SparkSession
from pyspark.sql import functions as func
from pyspark.sql.types import StructType, StructField, IntegerType, LongType
import codecs
def loadMovieNames():
movieNames = {}
# CHANGE THIS TO T... |
class Sport:
sport_id: int
name: str
link: str
def __init__(self, sport_id: int, name: str, link: str) -> None:
self.sport_id = sport_id
self.name = name
self.link = link
def __str__(self) -> str:
return f"""Sport(
\tsport_id={self.sport_id}
\tname=... |
"""
Job search with persistent and transitory components to wages.
Wages are given by
w = exp(z) + y
y ~ exp(μ + s ζ)
z' = d + ρ z + σ ε
with ζ and ε both iid and N(0, 1). The value function is
v(w, z) = max{ u(w) / (1-β), u(c) + β E v(w', z')}
The continuation value function satisfies
... |
# Generated by Django 3.2.1 on 2021-08-08 07:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('admin_panel', '0016_wish_list'),
]
operations = [
migrations.AddField(
model_name='wish_list',
name='is_wished',
... |
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
# Copyright (c) 2020.
#
# @author Mike Hartl <mike_hartl@gmx.de>
# @copyright 2020 Mike Hartl
# @license http://opensource.org/licenses/gpl-license.php GNU Public License
# @version 0.0.1
import os
import types
class Pd1Files:
def list(self, path):
inter... |
# -*- coding: utf-8 -*-
import io, re, glob, os, datetime
from setuptools import setup
SETUP_PTH = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(SETUP_PTH, 'requirements.txt')) as f:
required = f.read().splitlines()
setup(
name = 'mpcontribs-utils',
version = datetime.datetime.today().... |
import numpy as np
import matplotlib.pyplot as plt
file= 'input.dat'
file= 'output.dat'
#file='potential.dat'
f = open(file, "rb")
nx=np.fromfile(f,count=1,dtype=np.int32)[0]
ny=np.fromfile(f,count=1,dtype=np.int32)[0]
print nx,ny
x=np.fromfile(f,count=nx,dtype=np.float32)
y=np.fromfile(f,count=ny,dtype=np.float32... |
#!/usr/bin/env python3
# TODO config file for setting up filters
# TODO save filters to disk before exiting
# TODO normal bloom filters
# TODO change server banner
# TODO instruction using apache/nginx as reverse proxy
# TODO logging
# TODO daemonize, pid file, watchdog script
# TODO specify listen address/port
# TODO... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2017 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# ****************************************************************************
# This file is part of the package _ReST.
#
# This module is licensed under the terms ... |
import unittest
from app.models import Source
class SourceTest(unittest.TestCase):
'''Class testing behaviours of the Source class'''
def setUp(self):
'''method that will run before every test case'''
self.new_source = Source('1234','citizen news','Your trusted source for breaking news, analys... |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def isBalanced(root: TreeNode) -> bool:
if not root: return True
lh = get_depth(root.left)
rh = get_depth(root.right)
return abs(lh - rh) <= 1 and isBalanced(root.left) and isBalanced(ro... |
# Copyright 2021 the V8 project authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Build rules to choose the v8 target architecture."""
load("@bazel_skylib//lib:selects.bzl", "selects")
V8CpuTypeInfo = provider(
doc = "A singleto... |
"""Dictionary-based filesystem for your pocket."""
from collections.abc import Iterator
from typing import Any
from typing import cast
from cutty.filesystems.domain.filesystem import Access
from cutty.filesystems.domain.nodefs import FilesystemNode
from cutty.filesystems.domain.nodefs import NodeFilesystem
from cutty.... |
import numpy as np
from .utils import log_nowarn
from .checks import _check_size, _check_labels
def multinomial_logreg_inference(X, W, b):
"""Predict class probabilities.
Parameters
----------
X : ndarray, shape (m, n)
input features (one row per feature vector).
W : ndarray, shape (n, k... |
"""Dragon Candy ported from https://twitter.com/MunroHoberman/status/1346166185595985920
"""
from pypico8 import (
add,
camera,
circ,
cos,
pico8_to_python,
printh,
pget,
pset,
rnd,
run,
sin,
sqrt,
t,
)
printh(
pico8_to_python(
"""
camera(-64,-64)... |
#!/usr/bin/env python
"""
@package
KiBOM - Bill of Materials generation for KiCad
Generate BOM in xml, csv, txt, tsv or html formats.
- Components are automatically grouped into BoM rows (grouping is configurable)
- Component groups count number of components and list component designators
- R... |
#!/usr/bin/python
# script find clusters of small RNA reads in the genome
# version 3 - 24-12-2013 evolution to save memory !!! TEST !!!
# Usage clustering.py <bowtie input> <output> <bowtie index> <clustering_distance> <minimum read number per cluster to be outputed> <collapse option> <extention value> <average_clust... |
# coding: utf-8
from __future__ import unicode_literals
import re
import random
import urllib.parse
import pprint
from .common import InfoExtractor
from ..utils import (
urlencode_postdata,
ExtractorError)
class RawFuckIE(InfoExtractor):
IE_NAME = 'rawfuck'
IE_DESC = 'rawfuck'
_VALID_URL = r"http... |
import numpy as np
import matplotlib.pyplot as plt
import math
############ functions #############################################################
def dprime(gen_scores, imp_scores):
x = math.sqrt(2) * abs(np.mean(gen_scores) - np.mean(imp_scores)) # replace 1 with the numerator
y = math.sqrt(pow(np.... |
#!/usr/bin/python3
# for flask app
# note NEED SCALE (reference unit) AS FLOAT for decent accuracy - using an int leads to systematic error
#
# uses paramiko to append data to remote files to avoid writing frequently to rpi ssd
#
# multiple HX711 version - separate data/clock port pair for each
# uses curses so we can... |
#
# Copyright (c) 2013-2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
#
from sm_client.common import utils
from sm_client.v1 import smc_service_shell
from sm_client.v1 import smc_service_node_shell
from sm_client.v1 import smc_servicegroup_shell
COMMAND_MODULES = [
smc_service_shell,
... |
pkgname = "tevent"
pkgver = "0.11.0"
pkgrel = 0
build_style = "waf"
configure_script = "buildtools/bin/waf"
configure_args = [
"--disable-rpath", "--disable-rpath-install",
"--builtin-libraries=replace", "--bundled-libraries=NONE",
]
hostmakedepends = [
"pkgconf", "python", "gettext-tiny", "docbook-xsl-nons... |
from enum import Enum
class GolfSwingLabel(Enum):
other = 0
swing = 1
@staticmethod
def to_json():
label_dict = {}
for l in GolfSwingLabel:
label_dict[l.value] = l.name
return label_dict
|
import sys
import inspect
import textwrap
def function_to_script(func):
function_sig = inspect.signature(func)
assert all(p.default != p.empty for p in function_sig.parameters), 'Function should not require parameters'
function_name = func.__name__
function_impl = inspect.getsource(func)
function_... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tickets', '0006_ticketseventmeta_receipt_footer'),
]
operations = [
migrations.CreateModel(
name='AccommodationI... |
import sqlite3
conn = sqlite3.connect('database.db')
print "Executed successfully";
conn.execute('CREATE TABLE coders (handle TEXT, email TEXT, password TEXT)')
print "Table Created successfully";
conn.close() |
"""
2.2 – Mensagens simples: Armazene uma mensagem em uma variável e, em seguida, exiba essa mensagem. Então altere o valor de sua variável para uma nova mensagem e mostre essa nova mensagem.
"""
var = "Olá, mundo!"
print(var)
var = "Python é magnífico!"
print(var) |
import astropy.io.fits
import numpy as np
import matplotlib.pyplot as plt
# Create an empty numpy array. 2D; spectra with 4 data elements.
filtered = np.zeros((2040,4))
combined_extracted_1d_spectra_ = astropy.io.fits.open("xtfbrsnN20160705S0025.fits")
exptime = float(combined_extracted_1d_spectra_[0].header['EXPTIME... |
# 1120. Maximum Average Subtree
# Runtime: 60 ms, faster than 44.70% of Python3 online submissions for Maximum Average Subtree.
# Memory Usage: 17.1 MB, less than 11.35% of Python3 online submissions for Maximum Average Subtree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, ... |
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import sys
if sys.version_info < (3,):
str_cls = unicode # noqa
byte_cls = str
else:
str_cls = str
byte_cls = bytes
def verify_unicode(value, param_name, allow_none=False):
"""
Raises a Type... |
import os
import sys
import acconeer.exptool as et
def main():
parser = et.utils.ExampleArgumentParser()
parser.add_argument("-o", "--output-dir", type=str, required=True)
parser.add_argument("--file-format", type=str, default="h5")
parser.add_argument("--frames-per-file", type=int, default=10000)
... |
# Copyright 2014 Google Inc. All Rights Reserved.
"""Utility functions for managing customer supplied master keys."""
import argparse
import base64
import json
from googlecloudsdk.calliope import exceptions
EXPECTED_RECORD_KEY_KEYS = set(['uri', 'key'])
BASE64_KEY_LENGTH_IN_CHARS = 44
SUPPRESS_MASTER_KEY_UTILS = ... |
# Copyright 2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'AddDialog.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_AddDialog(object):
def setupUi(self, AddDialog):
AddDialog.s... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import emojilib
def main():
data = emojilib.generate(
text="絵文\n字。",
width=128,
height=128,
typeface_file='./example/NotoSansMonoCJKjp-Bold.otf'
)
with open('./example/emoji.png', 'wb') as f:
f.write(data)
if __name_... |
import calendar
import datetime
from dao.dao import SlackMessager,ExtractMessageFromPubSubContext,OSEnvironmentState
def send_message(context, info):
webhook=OSEnvironmentState.getSlackWebhook()
slackMessager=SlackMessager(webhook=webhook)
message = ExtractMessageFromPubSubContext.messageDecode(contex... |
from fastai.vision import *
from fastai.distributed import *
@call_parse
def main():
path = url2path(URL.MNIST_SAMPLE)
tfms = (rand_pad(2, 28), [])
data = ImageDataBunch.from_folder(path, ds_tfms = tfms, bs = 64).normalize(imagenet_stats)
learn = cnn_learner(data, models.resnet18, metrics = accuracy)
... |
import subprocess
args = [ 'black', 'tsu/', 'tests/' ]
subprocess.run(args)
|
from ape import plugins
from ape.api import create_network_type
from .providers import LocalNetwork
@plugins.register(plugins.NetworkPlugin)
def networks():
yield "ethereum", "development", create_network_type(chain_id=69, network_id=69)
@plugins.register(plugins.ProviderPlugin)
def providers():
yield "eth... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
import requests
from bs4 import BeautifulSoup
def filter_input(link, data_is_empty, store_data_is_empty):
should_ret = False
if link == "err" or "skroutz.gr/s/" not in link and "skroutz.gr/shop/" not in link:
print('-' * 50)
print('Error loading requested URL: No URL was given.\nOr given... |
# Function for enumerative model counting.
# Courtesy of Lucas Bang.
from z3 import *
import time
result = {}
count = 0
def get_models(F, timeout):
"""
Do model counting by enumerating each model.
Uses Z3Py.
Args:
F (<class 'z3.z3.AstVector'>): SMT-LIB formula
timeout (int): timeout ... |
from threadpoolctl import threadpool_info
from pprint import pprint
try:
import numpy as np
print("numpy", np.__version__)
except ImportError:
pass
try:
import scipy
import scipy.linalg
print("scipy", scipy.__version__)
except ImportError:
pass
try:
from tests._openmp_test_helper impo... |
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2022, Oracle and/or its affiliates.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
# Portions Copyright 2001-2007, Computronix (Canada) Ltd., Edmonton, Alberta,
# Canada. All rights reserved... |
from .base import Store |
from pycspr import crypto
from pycspr import factory
from pycspr.serialisation import to_bytes
from pycspr.types import CLTypeKey
from pycspr.types import ExecutableDeployItem
from pycspr.types import DeployHeader
def create_digest_of_deploy(header: DeployHeader) -> bytes:
"""Returns a deploy's hash digest.
:... |
"""unittests for hwaddresses factory functions."""
from random import choice, choices
from string import hexdigits
import unittest
from hwaddress import get_address_factory, get_verifier, \
new_hwaddress_class, MAC, MAC_64, GUID, \
EUI_48, EUI_64, WWN, WWNx, IB_LID, IB_GUID,... |
import pygtk
#pygtk.require('2.0')
import gtk
#Just another test
#http://stackoverflow.com/questions/6782142/pygobject-left-click-menu-on-a-status-icon
#With this code we connect the status icon using "button-press-event"
#With this code, the SAME popup menu appears BOTH in right and left mouse click on gtkstatusicon.... |
# coding: utf-8
# Copyright 2016 Vauxoo (https://www.vauxoo.com) <info@vauxoo.com>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
from odoo import models, api, _
class AccountChartTemplate(models.Model):
_inherit = "account.chart.template"
@api.multi
def _load_template(
self... |
class Event:
def __init__(self, type='GenericEvent', data=None):
self.type = type
if data is None:
self.data = {}
else:
self.data = data
def __repr__(self):
return ''.join(['Event<', self.type, '> ', str(self.data)]) |
# -*- coding: utf-8 -*-
"""Common routines for data in glucometers."""
__author__ = 'Diego Elio Pettenò'
__email__ = 'flameeyes@flameeyes.eu'
__copyright__ = 'Copyright © 2013, Diego Elio Pettenò'
__license__ = 'MIT'
import collections
import textwrap
from glucometerutils import exceptions
# Constants for units
UNI... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import rospy
import cv2
class ImageConverter:
def __init__(self):
# 创建图像的发布者
self.image_pub = rospy.Publisher("cv_bridge", Image, queue_size=1)
# 创建CvBridge
... |
"""empty message
Revision ID: da63ba1d58b1
Revises: 091deace5f08
Create Date: 2020-10-04 17:06:54.502012
"""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from project import dbtypes
# revision identifiers, used by Alembic.
revision = "da63ba1d58b1"
down_revision = "091deace5f08"
branch_lab... |
import datetime as _datetime
import typing
from google.protobuf.json_format import MessageToDict
from flytekit import __version__
from flytekit.common import interface as _interface
from flytekit.common.constants import SdkTaskType
from flytekit.common.tasks import task as _sdk_task
from flytekit.common.tasks.sagemak... |
import RPi.GPIO as GPIO
from .light_errors import LedError
class Led:
"""
This is a class used to control LED's directly connected to the GPIO via a pin given.
See the documentation for an example of how to wire the LED.
"""
def __init__(self, pin):
"""
This initates the LED on the ... |
"""
training_batch_generate_audio_features.py
Given a event dataset (audio clips extracted from foa_dev through generate_audio_from_annotations.py), this script calculates the audio features
according to the methods defined in get_audio_features.py.
The output files are saved in a folder audio_features in the input ev... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 29 16:50:58 2018
@author: Benedikt
"""
import win32com.client
class Microscope(object):
def __init__(self, simulation=False, z0=None):
'''
Parameters
----------
z0: int
only used when in simulation. It is... |
# Generated by Django 2.0.2 on 2020-06-18 03:52
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('system', '0002_auto_20200617_0840'),
]
operations = [
migrations.AddField(
model_name='menu',
... |
"""
test_multi_group.py
Author: Jordan Mirocha
Affiliation: University of Colorado at Boulder
Created on: Sun Mar 24 01:04:54 2013
Description:
"""
|
from rest_framework import serializers
from .models import Course, CourseSection, CourseMeetingTime
from .models import Instructor, InstructorOfficeHours
class CourseMeetingTimeSerializer(serializers.ModelSerializer):
coursesectionID = serializers.PrimaryKeyRelatedField(queryset=CourseSection.objects.all(), source='m... |
from typing import List
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
import numpy as np
from scipy.sparse import hstack
def run_classification(train_df, dev_df, regula... |
# -*- coding: utf-8 -*-
import scrapy
import os
from ..Util.VideoHelper import ParseVideo,VideoGot
from ..items import TumblrItem
from redis import *
from ..Util.Conf import Config
origin_url='https://www.tumblr.com'
origin_video_url='https://vtt.tumblr.com/{0}.mp4'
redis_db = StrictRedis(host='127.0.0.1', port=6379, ... |
# -*- coding: utf-8 -*-
"""
preprocess_image.py
created: 14:56 - 18/08/2020
author: kornel
"""
# --------------------------------------------------------------------------------------------------
# IMPORTS
# --------------------------------------------------------------------------------------------------
# standar... |
# Decombinator
# James M. Heather, August 2016, UCL
# https://innate2adaptive.github.io/Decombinator/
##################
### BACKGROUND ###
##################
# Searches FASTQ reads (produced through Demultiplexor.py) for rearranged TCR chains
# Can currently analyse human and mouse TCRs, both alpha/beta and gamma/d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.