text stringlengths 2 999k |
|---|
"""Support for the Asterisk Voicemail interface."""
import logging
from homeassistant.components.mailbox import (
CONTENT_TYPE_MPEG, Mailbox, StreamError)
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import DOMAIN as ASTERISK_DOMAIN
_LOGGER ... |
# 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 matplotlib.pyplot as plt
a = (0, 0, 0.5, 1)
b = (0, 0, 1, 0.25)
arrow_a = plt.arrow(a[0], a[1], a[2], a[3])
arrow_b = plt.arrow(b[0], b[1], b[2], b[3])
result = plt.arrow(
a[0] + b[0],
a[1] + b[1],
a[2] + b[2],
a[3] + b[3],
ec='green',
head_width=0.02, )
plt.legend([result, arrow_a, arro... |
# this is kinda like game of life isn't it...
seats = {}
maxX = 0
maxY = 0
class Seat:
def __init__(self, x, y):
self._adjacent = None
self._rcSeats = None
self.x = x
self.y = y
self.filled = False
self.nextFilled = False
def adjacent(self):
if self._ad... |
#! /usr/bin/env python3
# DouBan group url lists.
GROUP_LISTS = {"hz1": "https://www.douban.com/group/145219/"}
# paginate url query
GROUP_SUFFIX = "discussion?start={}"
# crawl 5 pages
MAX_PAGE = 5
# match rules
RULES = {
# 每个帖子项
"topic_item": "//table[@class='olt']/tr",
"url_list": "//table[@class='olt']... |
#
# This file is part of pyasn1-alt-modules software.
#
# Created by Russ Housley.
#
# Copyright (c) 2020-2021, Vigil Security, LLC
# License: http://vigilsec.com/pyasn1-alt-modules-license.txt
#
# CBOR Content for CMS
#
# ASN.1 source from:
# https://www.rfc-editor.org/rfc/rfc8769.txt
#
from pyasn1.type import univ
... |
# ------------------------------------------------------------------------------
# Based on:
# apex
# Copyright (c) NVIDIA
# Licence under The BSD 3-Clause "New" or "Revised" License
# https://github.com/NVIDIA/apex
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without mo... |
# Ported from pytorch example:
# https://github.com/pytorch/examples/blob/master/dcgan/main.py
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils... |
import json
import pkg_resources
import re
import time
import urllib.parse
from onfleet.error import PermissionError, HttpError, RateLimitError, ServiceError
from ratelimit import limits
from backoff import on_exception, expo
RATE_LIMIT = 20
class Request:
def __init__(self, http_method, path, session):
se... |
# Generated by Django 3.0.8 on 2020-07-07 18:03
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('weather', '0001_initial'... |
#The Boggle Solver Problem
#We were challenged to build a Boggle Solver in Python and this is the main solution.
#This solution:
# - Generates a random 4x4 board by making a random selection for each dice based on the 6 sides available in a
# standard board.
# - Using the list of permutations availab... |
#
# @lc app=leetcode.cn id=69 lang=python3
#
# [69] Sqrt(x)
#
# @lc code=start
class Solution:
def mySqrt(self, x: int) -> int:
left = 0
right = x
less_close = 0
while left <= right:
mid = (right - left) // 2 + left
if mid * mid == x:
print(... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
# Copyright 2019-2020 ETH Zurich and the DaCe authors. All rights reserved.
""" Contains functionality to perform find-and-replace of symbols in SDFGs. """
from dace import dtypes, properties, symbolic
from dace.frontend.python.astutils import ASTFindReplace
import re
import sympy as sp
from typing import Any, Union
i... |
import rl_games.algos_torch.layers
import numpy as np
import torch.nn as nn
import torch
import torch.nn.functional as F
import rl_games.common.divergence as divergence
from rl_games.algos_torch.torch_ext import CategoricalMasked
from torch.distributions import Categorical
from rl_games.algos_torch.sac_helper import Sq... |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2022 Apple Inc. All Rights Reserved.
#
from torch import nn, Tensor
from typing import NamedTuple, Dict, Any, Tuple
import argparse
from utils import logger
from ..classification import BaseEncoder
from ... import parameter_list
from ...misc.init_utils... |
import os
import sqlite3
from pathlib import Path
from sqlite3 import Error
import sys, shutil
from orator import DatabaseManager, Schema
from orator import Model
from models.application import Applications
from models.targets import Targets
class DatabaseUtilities:
def __init__(self):
self.sego_home =... |
import os
import time
import shutil
import simplejson
import sys
import config
import dockerapi as docker
import util
import network
if util.on_macos:
import OSes.macos as OS
elif util.on_wsl:
import OSes.windows_wsl2 as OS
elif util.on_linux:
if config.NAME == 'Ubuntu':
import OSes.ubuntu as OS... |
# -*- coding: utf-8 -*-
from enum import Enum
import numpy as np
class DatasetXY:
class XType(Enum):
ALL = 1 # all points of the plane
RANDOM = 2 # random (gaussian distribution) selected points
def __init__(self, t, x_lims, groups, traing_data_ratio, f):
self.... |
# Copyright 2016 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Demo of using ShapeStim to make a functioning visual clock.
"""
from __future__ import division
from psychopy import visual, core, event
import numpy, time
win = visual.Window([800, 800], monitor='testMonitor')
# vertices (using numpy means we can scale them easily)... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
OpenAPI spec version: release-1.16
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_import
import unittest
import... |
from flask import Flask, redirect
from flask import request
import json
from flask_cors import cross_origin
from flask_cors import CORS
import requests
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/')
def hello_world():
return redirect('/static/index.html')
@app.route("/api/v1/ttjj/t... |
"""Validate integration translation files."""
from __future__ import annotations
from functools import partial
from itertools import chain
import json
import re
import voluptuous as vol
from voluptuous.humanize import humanize_error
import homeassistant.helpers.config_validation as cv
from homeassistant.util import ... |
import networkx as nx
import numpy as np
from cdlib import algorithms
def random_walk(chord_graph, start_chord=None, progression_length=4):
chord_path = []
current_chord = start_chord
if current_chord == None:
pagerank = list(nx.get_node_attributes(chord_graph, "pagerank").values())
... |
"""mblog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... |
# Some m work shifts need fulfilled by some n employees
# Available shifts may overlap, i.e. two employees during same time
# This problem is reduced by simplifying the available time
# into unique slots for both workers and shifts
#
# Next, we relate worker's availability blocks to the shifts as pairs
# This results i... |
from pbl import *
'''
Dump out a single track to show the available attributes on a
Spotify Track
'''
if __name__ == '__main__':
teen_party = PlaylistSource('Teen Party')
teen_party = Annotator(teen_party, 'spotify')
teen_party = Annotator(teen_party, 'audio')
show_source(Debugger(teen_party)... |
import os
import h5py
from pytz import timezone
from astral import LocationInfo
PROJECT_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "../..")
RAW_DATA_PATH = os.path.join(PROJECT_PATH, "data/raw/davos")
DATASET_PATH = os.path.join(PROJECT_PATH, "data/datasets")
MODELS_PATH = os.path.join(PROJECT_PA... |
from django import forms
from homeschool.core.forms import DaysOfWeekModelForm
from homeschool.schools.models import GradeLevel
from .models import Course, CourseResource, CourseTask, GradedWork
class CourseForm(DaysOfWeekModelForm):
class Meta:
model = Course
fields = [
"name",
... |
"""
Copyright 2020 Qiniu Cloud (qiniu.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 to in writing, softw... |
import sys
from PIL import Image
from PIL.ExifTags import TAGS
image_file = sys.argv[1]
image_name = image_file.split(".")[0]
try:
image = Image.open(image_file)
except IOError:
print("Error in loading image!!")
sys.exit(1)
bw_image = image.convert('L')
bw_image.save("bw_"+image_name+".png")
|
from fabric.api import task, local
@task
def down():
local('docker-compose down')
local('rm -rf /tmp/manager_run')
@task
def up():
local('docker-compose up -d manager1 manager2 worker1 worker2')
local('docker-compose exec -T manager1 docker swarm init')
token_worker = local('docker-compose exec -T... |
from ..utils import choose_pixelization, HealpixScheme, GnomonicPixelScheme
from parallel_statistics import ParallelMeanVariance, ParallelSum
import numpy as np
class Mapper:
def __init__(self, pixel_scheme, lens_bins, source_bins, do_g=True, do_lens=True, sparse=False):
self.pixel_scheme = pixel_scheme
... |
from datetime import datetime, timedelta
class Report():
def __init__(self, dbm, data):
self.now = datetime.now()
self.today = self.now.strftime('%Y-%m-%d')
self.dbm = dbm
self.report_type = data['reportType']
self.pe_id = data['peId']
self.date_from = None
i... |
"""
tests for page parsing
Page parsing effectiveness is measured through the evaluation system. These
tests should focus on specific bits of functionality work correctly.
"""
from twisted.trial.unittest import TestCase, SkipTest
from scrapy.contrib.ibl.htmlpage import HtmlPage
from scrapy.contrib.ibl.descriptor impor... |
'''Write record to data lake'''
import json
import logging
import os
import boto3
import iso8601
log_level = os.environ.get('LOG_LEVEL', 'INFO')
logging.root.setLevel(logging.getLevelName(log_level)) # type: ignore
_logger = logging.getLogger(__name__)
DATA_LAKE_S3_BUCKET = os.environ.get('DATA_LAKE_S3_BUCKET')
S... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Script to generate list of seed nodes for chainparams.cpp.
This script expects two text files in the dir... |
from Instrucciones.Asignacion import Asignacion
from Instrucciones.Bloque import Bloque
from Instrucciones.Case import *
from Instrucciones.Declaracion import Declaracion
from Instrucciones.Execute import Execute
from Instrucciones.Funcion import *
from Instrucciones.Ifclass import Ifclass
from Instrucciones.Procedure ... |
from playhouse import shortcuts
class CoreNormalizer(object):
fields = None
def _model_to_dict(self, model_object):
raise NotImplemented
def normalize(self, queryset):
return [self.normalize_object(i) for i in queryset]
def normalize_object(self, model_object):
if self.field... |
from conftest import run_validator_for_test_file
def test_always_ok_for_empty_file():
errors = run_validator_for_test_file('empty.py')
assert not errors
errors = run_validator_for_test_file('empty.py', max_annotations_complexity=1)
assert not errors
def test_ok_for_unannotated_file():
errors = r... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
"""Basic example which iter... |
from bottle import route, run
import RPi.GPIO as GPIO
host = '192.168.1.8'
GPIO.setmode(GPIO.BCM)
led_pins = [18, 23, 24]
led_states = [0, 0, 0]
switch_pin = 25
GPIO.setup(led_pins[0], GPIO.OUT)
GPIO.setup(led_pins[1], GPIO.OUT)
GPIO.setup(led_pins[2], GPIO.OUT)
GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_... |
''' Query to illustrate Anne's use case for variants related to a gene involved in a rare pediatric brain cancer'''
# IMPORTS
from fasp.search import BigQuerySearchClient
searchClient = BigQuerySearchClient()
query = """
SELECT mut.case_barcode subject, meta.file_gdc_id as drs_id,
meta.file_gdc_url as tumor_bam_f... |
# Generated by Django 3.0.7 on 2020-06-18 23:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tags', '0005_merge_multiple_leaf_nodes'),
('institutions', '0008_auto_20200528_1330'),
]
operations = [
migrations.AddField(
... |
import os
BACKEND_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = False
SECRET_KEY = "secret-key-213213"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(BACKEND_DIR, "templates")],
"APP_DIRS": True,
}
]
DATABASES = {
"... |
import multiprocessing
import time
def f(x):
t = 0
while t < 10:
print "Running ", x, "-", t
t += 1
time.sleep(x)
if __name__ == '__main__':
p1 = multiprocessing.Process(target=f, args=(1,))
p2 = multiprocessing.Process(target=f, args=(2,))
p1.start()
time.sleep(0.5)
... |
"""Prepare CHiME3 background data.
Download, unpack and create manifest files.
Manifest file is a json-format file with each line containing the
meta data (i.e. audio filepath, transcript and audio duration)
of each audio file in the data set.
"""
from __future__ import absolute_import
from __future__ import division
... |
# -*- coding: utf-8 -*-
"""
pygments.style
~~~~~~~~~~~~~~
Basic style object.
:copyright: Copyright 2006-2019 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from typecode._vendor.pygments.token import Token, STANDARD_TYPES
from typecode._vendor.pygments.util import... |
# -*- coding: utf-8 -*-
"""A setuptools based setup module."""
from codecs import open
from os import path
from setuptools import setup, find_packages
import versioneer
__author__ = "Chris Lunsford"
__author_email__ = "chrlunsf@cisco.com"
__copyright__ = "Copyright (c) 2016-2018 Cisco and/or its affiliates."
__li... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# Copyright (c) 2020 Florent Kermarrec <florent@enjoy-digital.fr>
#
# Code adapted from ``litex`` and ``usb3_pipe``.
# SPDX-License-Identifier: BSD-3-Clause
""" Code for USB3 physical-layer encoding. """
from nmigen ... |
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# --------------------------------------------... |
# Run from Django shell (python manage.py shell) using following call.
# >>> exec(open("scripts/submissions_over_time.py").read())
import datetime
import matplotlib.pyplot as plt
import numpy as np
from apps.models import Paper
CFP_OPEN_DATE = datetime.date(2021, 4, 1)
CFP_CLOSE_DATE = datetime.date(2021, 5, 28)
CFP... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-20 15:48
from __future__ import unicode_literals
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0029_unicode_slugfield_dj19'),
('pag... |
from core.entity.entity_exceptions import EntityNotFoundException
class EntitySetObject:
"""
The EntitySetObject is a simple immitation of the entity set that allows to generate expected
results among search within the entity set itself. Such results must be coincided with another
ones retrieved from ... |
import logging
from . import nodes
from ... import ir, irutils
class CodeGenerator:
"""Transform llvm-ir into ppci-ir
This class has the humble job to convert llvm-IR into ppci-IR.
llvm variables are prefixed with ll_
"""
logger = logging.getLogger("llvm-gen")
def __init__(self):
s... |
#!/usr/bin/env python3
#
# This file is part of LiteX-Boards.
#
# Copyright (c) 2020 David Corrigan <davidcorrigan714@gmail.com>
# Copyright (c) 2020 Alan Green <avg@google.com>
# Copyright (c) 2020 David Shah <dave@ds0.me>
#
# SPDX-License-Identifier: BSD-2-Clause
import os
import argparse
from migen import *
from ... |
# coding=utf-8
from atlassian import Confluence
from pprint import pprint
"""This example shows how to get all users from group e.g. group_name """
confluence = Confluence(url="http://localhost:8090", username="admin", password="admin")
def get_all_members(group_name):
flag = True
i = 0
limit = 50
r... |
"""Main script"""
from models.ffmpeg import Ffmpeg
import config
log = config.log
ffmpeg = Ffmpeg()
total_videos = len(config.file_list)
n_videos = 0
for i, file in enumerate(config.file_list):
config.log.progress(i, config.file_list, file)
ffmpeg.test_file(file)
n_videos += 1
log.end(n_videos)
|
'''exclude unused ops from build'''
# !/usr/bin/env python3
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import os
import argparse
import shutil
import onnx
from onnx import AttributeProto as AP
from logger import log
domain_map = {'': 'kOnnxDomain',
'ai... |
# Copyright 2014 Google 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 applicable law or ag... |
# Computing Rescaled Features
#### Boilerplate #################################################################
import pickle
import numpy
import matplotlib.pyplot as plt
import sys
sys.path.append("../tools/")
from feature_format import featureFormat, targetFeatureSplit
def Draw(pred, features, poi, mark_poi=False... |
from contextlib import contextmanager
from unittest import mock
import pytest
from zulu import Timer
parametrize = pytest.mark.parametrize
@contextmanager
def mock_time(epoch):
with mock.patch("time.time", return_value=epoch):
yield
def test_timer_timing():
timer = Timer()
assert timer.stop... |
from tests.test_base import TestFlask
from app.controllers import vote as vote_controller
from app.session.user_session import set_session_user
from app.models.PostVote import PostVote
from app.models.AnswerVote import AnswerVote
from app.models.User import User
from app.models.Post import Post
from app.models.Answer i... |
a = input() ## 입력의 기본은 문자열이다.
sum = 0
for n in range(0, len(a)): ##범위는 0부터 시작하여 a-1이다.
if (a[n] == 'A' or a[n] == 'B' or a[n] == 'C'):
sum+=3
elif (a[n] == 'D' or a[n] == 'E' or a[n] == 'F'):
sum+=4
elif (a[n] == 'G' or a[n] == 'H' or a[n] == 'I'):
sum+=5
elif (a[n] == 'J... |
#!/usr/bin/env python3
"""
https://adventofcode.com/2021/day/6
Day 6: Lanternfish
"""
import sys
from collections import Counter, deque
def main():
test()
data = get_input()
print(part_1(data), 'lanternfish')
print(part_2(data), 'lanternfish')
def get_input(file='./input'):
with open(file, 'r') ... |
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'target_defaults': {
'conditions': [
['use_aura==1', {
'sources/': [ ['exclude', '_win... |
# coding: utf-8
"""
IBM Application Gateway Configuration Specification (OpenAPI)
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.12
Generated by: https://openapi-generator.tech
"""
impo... |
# Copyright 2015 Oursky Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import re
import json
import time
import logging
import requests
import datetime
from flask import Response as FlaskResponse
from requests.models import Response
from six.moves.urllib_parse import urljoin
from moto.apigateway.models import apigateway_backends
from localstack.utils import common
from localstack.config i... |
from netapp.netapp_object import NetAppObject
class SnapvaultSoftlockInfo(NetAppObject):
"""
Structure of the snapvault softlock.
"""
_softlock_name = None
@property
def softlock_name(self):
"""
Name of the softlock. This field will be empty if
softlock-name is not ... |
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
import mmcv
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
from mmcv.utils import print_log
from mmdet.core import auto_fp16
from mmdet.utils import get_root_logger
class BaseDetector(nn.Module, metac... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pandas as pd
import torch.optim as optim
import torchvision
from torchvision import transforms
from torch.optim.lr_scheduler import StepLR
import random
import ns.distributedml as dml
import time
from model import TaskB... |
# AUTOGENERATED! DO NOT EDIT! File to edit: 42-initial-model.ipynb (unless otherwise specified).
__all__ = ['model_meta_training', 'get_ner_df', 'get_corrects_df', 'get_fns_df', 'get_fps_df']
# Cell
#export
#data structure imports
import pandas as pd
import numpy as np
#python imports
import random
#modeling import... |
# coding:utf-8
# Type: Private Author: BaoChuan Wang
'''
FIXME ddpg 需要全为负的reward,waypoints环境暂时没有提供!
描述:
和local模型相同,训练得不到较好的结果
'''
import numpy as np
from ReinforcementLearning.Modules.Agents.DDPG_Agent import DDPG_Agent_GAL_v1
from ReinforcementLearning.Modules.Environments.Environments_waypointTarget import Carl... |
from .knights_archers_zombies.knights_archers_zombies import env, raw_env, parallel_env, manual_control
|
"""This module contains the general information for AaaEpFsmTask ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class AaaEpFsmTaskConsts():
COMPLETION_CANCELLED = "cancelled"
COMPLETION_COMPLETED = "com... |
from __future__ import print_function
import time
import unwired
from unwired.rest import ApiException
from pprint import pprint
# create an instance of the API class
api_instance = unwired.GEOLOCATIONApi()
#wifi Schema
w1=unwired.WifiSchema(bssid="00:17:c5:cd:ca:aa",channel=11,frequency=2412,signal=-51)
w2=unwired.W... |
import models.Encoders
import models.Decoders
import models.AttnLayers
import models.Models
__all__ = [
models.Encoders,
models.Decoders,
models.AttnLayers,
models.Models
]
|
import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
# Create the genesis block
self... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from collections import OrderedDict
from torch.nn import init
import math
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
... |
# -*- coding: utf-8 -*-
from django.db import models
import random
from django.conf import settings
from ckeditor.fields import RichTextField
from ckeditor_uploader.fields import RichTextUploadingField
from mptt.models import MPTTModel, TreeForeignKey
import datetime
import mptt
from mptt.fields import TreeForeignKey
... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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,... |
# coding: utf-8
"""
tweak-api
Tweak API to integrate with all the Tweak services. You can find out more about Tweak at <a href='https://www.tweak.com'>https://www.tweak.com</a>, #tweak.
OpenAPI spec version: 1.0.8-beta.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
... |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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... |
# -*- coding: utf-8 -*-
"""
Make beautiful, interactive maps with Python and Leaflet.js
"""
from __future__ import (absolute_import, division, print_function)
import os
import time
from branca.colormap import StepColormap
from branca.element import CssLink, Element, Figure, JavascriptLink, MacroElement
from branca... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the wallet backup features.
Test case is:
4 nodes. 1 2 and 3 send transactions between each other... |
"""A trivia cog that uses Open Trivia Database."""
import os
import html
import asyncio
import time
import datetime
import random
import math
import aiohttp
import discord
from discord.ext import commands
from __main__ import send_cmd_help
from .utils import checks
from .utils.dataIO import dataIO
SAVE_FILEPATH = "da... |
def implement_each(folder, each):
folder['tags'] = each['tags'] + folder['tags']
for key, tags in each['folders'].items():
folder['folders'][key] = {'tags': tags, 'folders': {}}
return folder
|
import argparse
def main():
args = parse_args()
args.func(args)
def parse_args():
parser = argparse.ArgumentParser()
commands = parser.add_subparsers(dest="command")
commands.required = True
init_parser = commands.add_parser("init")
init_parser.set_defaults(func=init)
return parse... |
def is_it_5(self, chromosome):
"""A very simple case test function - If the chromosome's gene value
is equal to 5 add one to the chromosomes overall fitness value.
"""
# Overall fitness value
fitness = 0
for gene in chromosome:
# Increment fitness is the gene's value is 5
if g... |
#!/usr/bin/env python
# Code snippet from https://stackoverflow.com/a/16630719/4986615
from django.utils.crypto import get_random_string
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
print(get_random_string(50, chars))
|
weather_api_key = "ac49bddb9ef30bf7a28ee80e2a41f581"
gkey = "AIzaSyBjlP7HnFtr2dxIIBUeDQ4tJAjcBvu_WNA" |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import logging
import configparser
import telebot
import pymongo
import urllib3
import json
import os
from datetime import datetime
# Go to directory
directory = os.path.dirname(os.path.realpath(__file__))
os.chdir(directory)
# Request to API data
def requestAPI(argUrl):
... |
from django.utils.translation import ugettext_lazy as _
from rest_framework import status
from rest_framework.decorators import list_route, detail_route
from rest_framework.response import Response
from rest_framework_mongoengine import viewsets
from mongoextensions import filters
from happ.models import User, City, ... |
# Copyright Bruno da Silva de Oliveira 2003. Use, modification and
# distribution is subject to the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http:#www.boost.org/LICENSE_1_0.txt)
import exporters
from Exporter import Exporter
from declarations import *
from settings i... |
# coding=utf-8
import os
from utils.shortcuts import get_env
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'HOST': get_env('POSTGRES_HOST', '127.0.0.1'),
'PORT': get_env('POSTGRES_PORT',... |
#!/usr/bin/env python3
import os
from datetime import datetime
import TEST
class bcolors:
RED = "\033[1;31m"
GREEN = "\033[1;32m"
BLUE = "\033[1;34m"
RESET = "\033[0;0m"
def setup_log(test_name):
if not os.path.isdir(TEST.log_dir):
os.mkdir(TEST.log_dir)
if TEST.log_dir[-1] != "/":... |
#!/usr/bin/env python
# This software is Copyright (c) 2018, Dhiru Kholia <kholia at kth.se> and it
# is hereby released to the general public under the following terms:
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted.
#
# All credit goes to "Android backup extracto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.