content stringlengths 5 1.05M |
|---|
"""
Python mapping for the CoreMedia framework.
This module does not contain docstrings for the wrapped code, check Apple's
documentation for details on how to use these functions and classes.
"""
import objc
import sys
import Foundation
from CoreMedia import _metadata
from CoreMedia import _macros
from CoreMedia im... |
# Simple python tool to retrieve weather station information and display it on an e-Paper display
import requests
import json
from ast import literal_eval
import sys
import os
picdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'gfx')
libdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), ... |
#!/usr/bin/env python3
###
#
#
#
# Program Description :
# Created By : Benjamin Kleynhans
# Creation Date : January 25, 2020
# Authors : Benjamin Kleynhans
#
# Last Modified By : Benjamin Kleynhans
# Last Modified Date : August 20, 2020
# Filename : launcher.py
#
###
# Syste... |
import django_filters
from django.db import models
from .models import Item
class OrderingFilter(django_filters.filters.OrderingFilter):
"""ソートの表示変更"""
descending_fmt = '%s (Descending)'
class ItemFilterSet(django_filters.FilterSet):
"""
django-filter 構成クラス
https://django-filter.readthedocs.io/... |
import sys
from sys import stdin
sys.setrecursionlimit(1500)
n = stdin.readline()
N, M = int(n.split(" ")[0]), int(n.split(" ")[1])
arr = list()
[arr.append(x+1) for x in range(N)]
print("<", end="")
while len(arr):
[arr.append(arr.pop(0)) for _ in range(M-1)]
if len(arr)-1:
print(arr.pop(0), end=",... |
import smart_imports
smart_imports.all()
class MessagesContainerTest(utils_testcase.TestCase):
def setUp(self):
super(MessagesContainerTest, self).setUp()
self.messages = messages.JournalContainer()
def create_message(self, message, turn_delta=0, time_delta=0, position='some position info'... |
class RateLimitException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return (repr(self.value))
class AzureAPIException(Exception):
def __str__(self):
return (repr("Azure API exception."))
class AuthException(Exception):
def __str__(self):
... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import pickle
import matplotlib.patches as patches
from labellines import labelLine, labelLines
#plot parameters
font_size=10
plt.style.use('seaborn-paper')
plt.rc('text', usetex=True)
plt.rc('font',family='serif',... |
class Icon(object):
def __init__(self):
self.img='AAABAAEAgIAAAAEAIAAoCAEAFgAAACgAAACAAAAAAAEAAAEAIAAAAAAAAAABABMLAAATCwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAIgAAAEMAAABfAAAAcgAAAHUAAAB1AAAAdQAAAHUAAAB1AAAAdQAAAHUAAAB1AAAAdQAAAHUAAAB1AAAAdQAAAHUAAAB1AAAAdQAAAHUAAAB1AAAAdQAAAHUAAAB1AAA... |
import PySimpleGUI as pysg
pysg.Window(title="Hello World", layout=[[]], margins=(100, 100)).read()
|
# coding: utf-8
# Deep Learning Models -- A collection of various deep learning architectures, models, and tips for TensorFlow and PyTorch in Jupyter Notebooks.
# - Author: Sebastian Raschka
# - GitHub Repository: https://github.com/rasbt/deeplearning-models
# In[2]:
import tensorflow as tf
import numpy as np
from ... |
#!/usr/bin/env python
"""auto_recovery.py
Run auto-recovery if the robot's safety system is in recovery state,
otherwise run damped floating with joint soft limit disabled, so that the
user can manually trigger a safety system recovery state by moving any joint
close to its limit. See flexiv::Mode::MODE_AUTO_RECOVER... |
from typing import List, Optional
from fastapi import FastAPI
from enum import Enum
from fastapi.params import Query
from pydantic import BaseModel
app = FastAPI()
class ModelName(str, Enum):
name = "sambit"
class Item(BaseModel):
name: str
quantity: int
fake_items_db: List[Item] = []
# root
@app.g... |
res_file=["res_0.txt", "res_1000.txt", "res_100.txt", "res_10.txt", "res_2.txt"]
results=[]
for file_name in res_file:
scores=[];
with open(file_name, 'r') as f:
for line in f:
if line.startswith("Score:"):
scores.append(int(line[7:]))
if len(scores)!=10000:
pr... |
from django.shortcuts import redirect, render
from rest_framework import viewsets
from .models import University, Student
from .serializers import UniversitySerializer, StudentSerializer
from .forms import UniversityForm, StudentForm
class UniversityViewSet(viewsets.ModelViewSet):
queryset = University.objects.... |
# -*- coding: utf-8 -*-
"""Test suite."""
import datetime
import pytest
from axonius_api_client.api import json_api
from axonius_api_client.api.system.dashboard import DiscoverData, DiscoverPhase
class DashboardBase:
@pytest.fixture(scope="class")
def apiobj(self, api_dashboard):
return api_dashboar... |
#
# Example file for working with Calendars
#
# import the calendar module
import calendar
# create a plain text calendar
c = calendar.TextCalendar(calendar.SUNDAY)
# st = c.formatmonth(2021, 5, 0, 0)
# print(st)
# create an HTML formatted calendar
# hc = calendar.HTMLCalendar(calendar.SUNDAY)
# st = hc.formatmonth(... |
#
# Copyright 2015, 2016 Human Longevity, 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 or agr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import os
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.style as style
# Get File Directory
WORK_DIR = os.path.dirname((os.path.realpath(_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
import base64
import requests
import urllib.parse
import json
import datetime
import time
from tornado.options import define, options
define('port', default=800... |
# Generated by Django 2.2.13 on 2020-07-28 14:10
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("barriers", "0075_auto_20200717_1142"),
]
operations = [
migrations.AlterField(
model_name="pub... |
from abc import ABC, abstractmethod
import boto3
import botocore
import os
import shutil
class BaseDataSaver:
def __init__(self, bucket_name='model-result'):
"""Base class implementing S3 file saving logic
Args:
bucket_name (str): S3 bucket into which the files will be saved
"... |
#!/usr/local/bin/python3
# Matteo Del Vecchio
from utils import preprocessing
from unigram import unigram
from bigram import bigram
from trigram import trigram
from pprint import pprint
def main():
# Reading corpus
wordsList = []
corpus = open("corpus.txt", "r")
i = 0
for line in corpus.readlines():
# Every ... |
"""
Problem Description:
This problem requires you to create a output string from input string such that for every character in input string, there are three same characters in output string.
Input:
First line contains N, the number of letters in the string.
The next line contains the string.
Output:
Print the output... |
def linearSearch(list, targetValue):
for i in range(len(list)):
if (targetValue == list[i]):
return i
return "Not Found"
def main():
# Example
exampleList = [1, 2, 3, 4, 5, 6, 7, 8, 9]
exampleTarget = 5
result = linearSearch(exampleList, exampleTarget)
if (result == "N... |
import cropmask.preprocess as pp
from cropmask.misc import make_dirs, remove_dirs
import os
import pytest
@pytest.fixture
def wflow():
wflow = pp.PreprocessWorkflow("/home/ryan/work/CropMask_RCNN/cropmask/test_preprocess_config.yaml",
"/permmnt/cropmaskperm/unpacked_landsat_downlo... |
"""Interaction between the reference machinery and content objects."""
import gocept.reference.interfaces
import gocept.reference.reference
import transaction
import zope.component
import zope.container.interfaces
import zope.interface
import zope.location
import zope.traversing.api
import zope.traversing.interfaces
... |
valores = []
maior = menor = 0
for c in range(0, 5):
valores.append(int(input(f'Digite o {c}° valor: ')))
if c == 0:
maior = menor = valores[c]
else:
if valores[c] > maior:
maior = valores[c]
if valores[c] < menor:
menor = valores[c]
print(f'O maior valor digi... |
def bin_fixed_23(n, bits_per_word=16):
result = bin_twos_complement(n, bits_per_word)
return (('0'*bits_per_word)+result)[-bits_per_word:]
|
#!/usr/bin/env python
# encoding: utf-8
from pyo import *
##############################################################
READY = True # Set to True when ready for the radio
TITLE = "Daleks" # The title of the music
ARTIST = "J T Hutton (hipnofoo)" # Your artist name
DURATION = 420 # The dura... |
from django.contrib import admin
from . import models
# Register your models here.
@admin.register(models.Profile)
class UserAdmin(admin.ModelAdmin):
list_display = ["account_id", "email", "first_name", "last_name", "username", "phone_number", "tax_id", "is_active"]
list_editable = ["is_active"] |
# Copyright (C) 2019 by eHealth Africa : http://www.eHealthAfrica.org
#
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with
# the License. Y... |
# Copyright 2015 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 agree... |
import os
import pickle
import pandas as pd
import numpy as np
from sklearn.utils import shuffle
from outcomes_modelling import outcomes_sentence_labeler
from sklearn.metrics import f1_score
import shutil
import nltk
class OutcomesMultiLabelPredictor:
def __init__(self, model_folder, ner_model_folder="", threshol... |
#!/usr/bin/env python
import unittest
from arni_processing.specification_handler import *
from arni_processing.specification import *
import traceback
import rospy
PKG = "arni_processing"
test_spec = [
{
'n!test_node': {
'node_cpu_usage_mean': [0.03, 0.09],
'node_ramusage_mean': ... |
import torch
import torch.nn as nn
from torch_geometric.nn import MessagePassing
from torch_geometric.nn.conv.gcn_conv import gcn_norm
from torch_geometric.nn.inits import glorot, zeros
from torch_scatter import scatter
from torch_sparse import SparseTensor, matmul
class EfficientGraphConv(nn.Module):
"""The EGC ... |
import csv
print("without-BOM-UTF8 / open with utf_8")
csv_file = open("./woBOM.csv","r",encoding="utf_8")
f = csv.DictReader(csv_file)
for row in f:
print(row)
# OrderedDict([('#', '1'), ('a', 'あ'), ('b', '𦀗')])
csv_file.close()
print("without-BOM-UTF8 / open with utf_8_sig")
csv_file = open("./woBOM.csv","r",enc... |
import urllib.request
import urllib.parse
def search(parsmeters)
data = urllib.parse.urlencode(parameters)
print(data)
request_ = urllib.request.Request(url='http://www.baidu.com/s?'+data
,method="GET")
response = urllib.request.urlopen(request_)
print(response.url)
HTML=response.read().decode()
print(HTML)
with o... |
import time
from adafruit_circuitplayground.express import cpx
while True:
x, y, z = cpx.acceleration
print((x, y, z))
time.sleep(0.5)
|
#!/usr/bin/env python3
#Black Lotus v2-dev-
#Copyright of Th3 Jes7er
#----------------------------------------------------------------------------------------------------------------------
import os
from getpass import getpass
import time
import sys
def login():
os.system('cls||clear')
usr = input("\033[37m Us... |
import unittest
import pathlib
from signify.authenticode import TRUSTED_CERTIFICATE_STORE
from signify.authroot import CertificateTrustList
root_dir = pathlib.Path(__file__).parent
class AuthrootTestCase(unittest.TestCase):
def test_certificate_can_be_opened(self):
ctl = CertificateTrustList.from_stl_fi... |
from collections import defaultdict
"""
Leetcode(https://leetcode.com/problems/number-of-submatrices-that-sum-to-target/)
"""
class Solution:
def numSubmatrixSumTarget(self, matrix, target) -> int:
# presum of 2D array
S = [[0 for _ in range(len(matrix[0]) + 1)] for _ in range(len(matrix) + 1)]
... |
import queue
import logging
from betfairlightweight import BetfairError, filters
from tenacity import retry, wait_exponential
from .basestream import BaseStream
from ..events.events import CurrentOrdersEvent
from .. import config
logger = logging.getLogger(__name__)
class OrderStream(BaseStream):
@retry(wait=wa... |
from pypy.translator.oosupport.constant import is_primitive
from pypy.rpython.ootypesystem import ootype
class Database(object):
def __init__(self, genoo):
self.genoo = genoo
self.cts = genoo.TypeSystem(self)
self._pending_nodes = set()
self._rendered_nodes = set()
self._un... |
#!/usr/bin/env python3
import argparse
import sys
import json
indent_level=4
def parse_cli():
parser = argparse.ArgumentParser(description='Ferris keymap formatter')
parser.add_argument("--input", type=argparse.FileType('r'),
default=sys.stdin, help="Input keymap (json file produced by qmk configurat... |
""" Tables for movie cateogry fields """
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship
from src.model import db
from src.model import common
class MovieColor(db.ModelBase):
""" Movie color """
__tablename__ = 'movie_colors'
#: Primary key
pk = Column(Integer,... |
from unittest import TestCase
from unittest import main
from what_dominates_your_array import dominator
class TestWhatDominamtesYourArray(TestCase):
def test_dominator(self):
ptr = [
([3, 4, 3, 2, 3, 1, 3, 3], 3),
([1, 2, 3, 4, 5], -1),
([1, 1, 1, 2, 2, 2], -1),
... |
#!/usr/bin/env python
#
# ======================================================================
#
# Brad T. Aagaard, U.S. Geological Survey
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c) 2010-2017 University of California, Davis
#
#... |
from LOSS_likelihoods import color_likelihood,MK_likelihood,eo_likelihood,morphology_likelihood
from LOSS_hubbletype import hubbletype
import numpy as np
from uncertainties import ufloat
from astropy.cosmology import FlatLambdaCDM
cosmo = FlatLambdaCDM(H0=70, Om0=0.3, Ob0=0.05)
def galsnid_params(eo,z,RFcolors,Morphol... |
# Concord
#
# Copyright (c) 2020 VMware, Inc. All Rights Reserved.
#
# This product is licensed to you under the Apache 2.0 license (the 'License').
# You may not use this product except in compliance with the Apache 2.0 License.
#
# This product may include a number of subcomponents with separate copyright
# notices a... |
"""
Checks to see if openedx.yaml follows minimum standards
And gathers info
"""
import os
import pytest
import yaml
from pytest_repo_health import add_key_to_metadata
from repo_health import get_file_content
# Decision: require openedx.yaml to be parsable
module_dict_key = "openedx_yaml"
@pytest.fixture(name='op... |
# Flatten the package import
from fake_gen.base import *
from fake_gen.dictionary import *
from fake_gen.factories.sequences import *
from fake_gen.factories.strings import *
from fake_gen.factories.datetimes import *
from fake_gen.factories.fake import *
from fake_gen.factories.numeric import *
from fake_gen.factories... |
#!/usr/bin/env python3
import os
import re
import sys
import time
import shutil
import subprocess
biobbs_dir = "/Users/pau/projects/"
bioconda_recipes_dir = "/Users/pau/other_projects/bioconda-recipes"
tmp_dir = "/tmp"
editor_cmd = "atom"
twine_user = "andriopau"
# firefox, safari, chrome...
web_browser_cmd = "open"
... |
from NN_Model import FasterRCNN
f1 = FasterRCNN()
# f1.train_RPN_RoI()
# f1.save_weight()
f1.load_weight()
f1.test_proposal_visualization()
f1.faster_rcnn_output() |
from distutils.core import setup, Extension
from distutils.sysconfig import get_python_inc
query = Extension("query", ["query/Py_query_res.c"])
sort = Extension("sort_map", ["sort/sort_map.c"])
setup(
ext_modules=[query, sort],
include_dirs=[get_python_inc(), "sort", "query", "utilites"]
)
|
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import yaml
import os
import warnings
warnings.simplefilter('ignore')
def config_loader():
"""Set config path and load variables."""
config_path = os.path.join('./configs/config.yaml')
with open(config_path,'r') as ymlfile:
... |
"""
" Seats manage Players, chip stack, and Hands.
" Note: Maybe repr should return the position of the seat?"
"""
from . import hand
class Seat(object):
""" Defines a Seat object that occupies a Table. """
def __init__(self, table=None, position=0):
self.table = table
self.position = ... |
import MeCab
mecab = MeCab.Tagger ('-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd')
text = '解析したいテキスト'
mecab.parse('')#文字列がGCされるのを防ぐ
node = mecab.parseToNode(text)
while node:
#単語を取得
word = node.surface
#品詞を取得
pos = node.feature.split(",")[1]
print('{0} , {1}'.format(word, pos))
#次の単語に進める
... |
# -*- coding: UTF-8 -*-
#######################################################################
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @Daddy_Blamo wrote this file. As long as you retain this notice you
# can do whatever you want wi... |
from __future__ import division, print_function
import numpy as np
from astropy.io import fits
from astropy.table import Table
import os
import kcorrect
from astropy.cosmology import FlatLambdaCDM
def load_SDSS(filename, colors, SDSS_kcorrection_z):
"""
Compute the CDF of SDS... |
import numpy as np
import time
from scipy.ndimage.filters import gaussian_filter1d
def putPixel(strip, ledIndex, r, g, b, velocity):
if(ledIndex <= len(strip[0])):
strip[0][ledIndex] = r / 127 * (velocity + 1)
strip[1][ledIndex] = g / 127 * (velocity + 1)
strip[2][ledIndex] = b / 127 * (... |
import numpy as np
from time import sleep
from bplustree.bplustree import BPlusTree
np.random.seed(42)
# data = np.random.choice(200, size=200, replace=False)
data = [1, 5, 6, 7, 8, 9, 12, 4]
tree = BPlusTree()
print('data:', data)
for value in data:
tree.insert(value)
tree.render()
tree.delete(5)
# WORKING
# ... |
import dalec
class DALEC(object):
metadata_inputs = {
# 'time' : {
# 'data' : self._time,
# 'data_type' : 'int',
# 'unit' : 'day',
# 'range' : (-9999,-9999)
# 'loc' : 0
# 'description' : 'curre... |
# -*- coding: utf-8 -*-
import os
import datetime
import time
import uuid
import pytest
from etg import ETGHotelsClient
from etg import ( # models
GuestData,
)
from etg import ETGException
auth = (os.getenv('ETG_KEY_ID'), os.getenv('ETG_KEY'))
partner_email = os.getenv('ETG_MAIL')
client = ETGHotelsClient(auth)... |
# -*- coding: utf8 -*-
"""
this module will be loaded in app init
forbid importing runtime modules
"""
__all__ = ['app_config']
from config.config import config as app_config
|
# coding:utf-8
import codecs
import os
import re
from os.path import getsize, splitext
import json
import shutil
luaDir = "tolua++"
snippetsDir = "snippets"
templatePath = "template.sublime-snippet"
completionTemplatePath = "template_completions.sublime-completions"
completionItemTemplatePath = "template_completions_i... |
a = {4,21}
b = {6}
c = {9}
d = {11}
e = {18,4}
f = {4,21}
g = {23,11}
h = {25}
setlist = [a,b,c,d,e,g,f,h]
# setlist = [{8}, {46,9}, {18,10}, {18,67}, {107,19}, {144, 29}, {108, 38}, {50},
# {53, 99}, {54, 67}, {63,99}, {73}, {74}, {67,75}, {76,177}, {78},
# {81}, {83}, {93}, {18,94}, {67,102},... |
from pathlib import Path
from checkpoint_io import CheckpointIo
from classifier import FrozenFeatureDetector
from classifier import FlowerClassifier
from data_handling import DataProvider
from device_setup import prepare_device
from logger import ResultLogger
from train_arguments import TrainArgumentParser
from traine... |
# Generated by Django 3.2.2 on 2021-05-16 18:47
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category... |
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
# Uncomment the following lines to enable verbose logging
import logging
logging.basicConfig(level=logging.INFO)
# Create a new instance of a ChatBot
bot = ChatBot('ChatbotTeste')
# trainer = ChatterBotCorpusTrainer(bot)
# traine... |
from . import views
from django.urls import path, re_path
app_name = 'trade_account'
urlpatterns = [
path('',
views.TradeAccountsHomeView.as_view(), name='index'),
path('create/',
views.create_tradeaccount, name='create'),
path('comments/<ts_code>/<position_id>/',
views.position... |
from hailtop.frozendict import frozendict # noqa: F401 pylint: disable=unused-import
|
# -*- coding: utf-8 -*-
#!/usr/env python3
# Copyright (C) 2017 Gaby Launay
# Author: Gaby Launay <gaby.launay@tutanota.com>
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
... |
'''
汉明距离总和
两个整数的 汉明距离 指的是这两个数字的二进制数对应位不同的数量。
计算一个数组中,任意两个数之间汉明距离的总和。
'''
from typing import List
'''
思路1,回溯遍历数组中所有元素的组合,求其异或的1的个数(n&(n-1))
时间复杂度:O(n^2)
思路2,回溯遍历数组中所有元素的组合,求其异或的1的个数(jdk类库算法)
时间复杂度:O(n^2)
思路3,1次遍历所有位上的1的个数。只有0和1的异或才是1,所以对于每1位来说,只有与0其相反的位的组合才是有意义的。可以统计每位上1的个数count
然后这个位上产生的异或的1个个数是count*(n-count)。再合计32位上... |
import re
import types
import uuid
from typing import List, Match, Sequence
from google.datacatalog_connectors.mysql_.parse.transform_equ.commons \
import Commons
class TransformUpdate:
_alias_table = {}
def random_name(self, x: Match):
code = "uuid" + str(uuid.uuid1()).replace('-', '... |
# pylint: disable=duplicate-code
# -*- coding: utf-8 -*-
#
# ramstk.models.dbrecords.programdb_program_status_record.py is part of The
# RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""RAMSTKProgramStatus Record Model."""
#... |
import torch
import torch.nn as nn
import numpy as np
from src.complex import CPLX
class zReLU(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
rmask = torch.ge(x.r, torch.zeors_like(x.r)).float()
imask = torch.ge(x.i, torch.zeors_like(x.i)).float()
... |
from os import remove
from gtts import gTTS
from PyPDF2 import PdfFileReader
from typer import progressbar
import requests
from .utils import error_message
def download(pdf, file_out):
"""function that takes a pdf object and converts it to an audio file"""
with progressbar(length=pdf.getNumPages(), label='Do... |
'''
Class for maintaining and implementing reproductive behavior in Deep HyperNEAT.
Largely copied from neat-python. (Copyright 2015-2017, CodeReclaimers, LLC.)
'''
import random
from math import ceil
from deep_hyperneat.genome import Genome
from deep_hyperneat.stagnation import Stagnation
from itertools import count
... |
from guillotina import configure
from guillotina.addons import Addon
from guillotina.contrib.email_validation.interfaces import IValidationSettings
from guillotina.utils import get_registry
@configure.addon(name="email_validation", title="Guillotina Email Validation")
class EmailValidationAddon(Addon):
@classmeth... |
import sys
lines = []
for line in sys.stdin:
lines.append(line.strip())
n = int(lines[0])
nums = []
count = 0
for num in lines[1: ]:
num = int(num)
if num > 0:
nums.append(num)
elif num < 0:
count += 1
mean = round(sum(nums) / len(nums), 1)
output = ' '.join([str(count), str(mean)])... |
#! /usr/bin/env python
# IDLE Behavior
# WARNING! if person tracking is acting crazy, check that
# the person tracker node is using the correct camera!!
import rospy
import actionlib
import behavior_common.msg
import time
import rospkg
import rosparam
from std_msgs.msg import Float64
from std_msgs.msg import String... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# TODO: сделать детализацию счета и заказать в html/excel
# замаскировать телефоны
# сделать обработку excel на pandas: Analysis of account detail (excel)
import zipfile
with zipfile.ZipFile('Doc_df7c89c378c04e8daf69257ea95d9a2e.zip'... |
""" Transactions REST view """
from datetime import datetime
from typing import Any, Dict
from flask import Flask
from flask.views import MethodView
from werkzeug.exceptions import BadRequest, NotFound
from underbudget.common.decorators import use_args, with_pagination
from underbudget.database import db
from underbud... |
"""
2018 Gregory Way
9.tcga-classify/classify-cancer-types.py
Predicting 33 different cancer-types using elastic net logistic regression and
compressed gene expression features in TCGA PanCanAtlas
Usage:
python classify-cancer-types.py
Output:
Cancer-type specific DataFrames storing ROC, precision-recall, and c... |
from django import template
from django.contrib.contenttypes.models import ContentType
from django.urls import reverse
from ..forms import CommentForm
from ..hooks import hookset
from ..models import Comment
register = template.Library()
@register.filter
def can_edit_comment(comment, user):
return hookset.load_... |
from abc import ABCMeta, abstractmethod
class Book(object, metaclass=ABCMeta):
def __init__(self, title, author):
self.title = title
self.author = author
@abstractmethod
def display(): pass
# Write MyBook class
class MyBook(Book):
def __init__(self, title, author, price):
s... |
import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from tests import pyunit_utils
from h2o.estimators.deeplearning import H2OAutoEncoderEstimator
from h2o.estimators.random_forest import H2ORandomForestEstimator
def deeplearning_autoencoder():
resp = 784
nfeatures = 20 # number of feat... |
"""
Mixin class to help in flow inspection
"""
from unittest import TestCase
from google.protobuf.json_format import MessageToDict
from jsonpatch import make_patch
from simplejson import dumps
class FlowHelpers(TestCase):
# ~~~~~~~~~~~~~~~~~~~~~~~~~ HELPER METHODS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def asser... |
import glob
import numpy as np
from PIL import Image
from keras import Model
from keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D
from keras.applications.vgg19 import VGG19
from keras.applications.resnet50 import ResNet50
from keras.applications.inception_v3 import InceptionV3
def get_filenames(glob_pa... |
import logging
import socket
import time
import adb
from .. import app_test
logger = logging.getLogger(__name__)
class App(app_test.AppTest):
"""
Start the Vagrant virtual machine on the same machine running the script,
before running the test
"""
def __init__(self, **kwargs):
super().__... |
#!/usr/bin/env python3
import pprint
import boto3
# Set this to whatever percentage of 'similarity'
# you'd want
SIMILARITY_THRESHOLD = 75.0
if __name__ == '__main__':
client = boto3.client('rekognition')
# Our source image: http://i.imgur.com/OK8aDRq.jpg
with open('/Users/janae/data/elvisPMs_last100/Go... |
from django.db import models
from django.contrib.auth.models import User
class Role(models.Model):
id_role = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
weight = models.IntegerField(default=0)
class Meta:
db_table = 'eff_role'
class UserRole(models.Mode... |
# ------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -------------------------------------------------------------------------
from ._servi... |
import os
import argparse
from solver import Solver
from data_loader import get_audio_loader
def main(config):
assert config.mode in {'TRAIN', 'TEST'},\
'invalid mode: "{}" not in ["TRAIN", "TEST"]'.format(config.mode)
if not os.path.exists(config.model_save_path):
os.makedirs(config.model_s... |
# -*- encoding=utf8 -*-
__author__ = "TinyZ"
from tdydxc_game import do_endless_abyss, do_fetch_daily_task_reward, do_monster_iland
from GameHelper.core.airtest.cvex import AirImage
from GameHelper.core.helper.utility import Utility
from GameHelper.core.helper.nav import Node, NodeEnum
from GameHelper.core.util.ciede... |
import FWCore.ParameterSet.Config as cms
# Material effects to be simulated in the tracker material and associated cuts
TrackerMaterialBlock = cms.PSet(
TrackerMaterial = cms.PSet(
use_hardcoded_geometry = cms.bool(True),
disk_thickness = cms.vdouble(0.058,0.058,0.04,0.04,0.055,0.05,0.05,0.05,0.05,0.05,... |
from .client import Client
from .suite import CommandSuite
|
import test_test
path = 'data.json'
script = test_test.TestTest()
script.setup_method()
script.load_vars(path)
script.test_verify()
script.teardown_method() |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/utils.audio.ipynb (unless otherwise specified).
__all__ = ['mel_to_audio', 'differenceFunction', 'cumulativeMeanNormalizedDifferenceFunction', 'getPitch',
'compute_yin', 'convert_to_wav', 'match_target_amplitude', 'modify_leading_silence',
'normaliz... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.