text stringlengths 2 999k |
|---|
import time
from multiprocessing.pool import Pool
t = time.time()
def cal_prime(num):
for i in range(2, int(num**0.5+1)):
if num % i == 0:
return None
return num
def is_permutation(num1, num2):
return sorted(list(str(num1))) == sorted(list(str(num2)))
num_range= range(2000,5000)
... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
#
#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... |
import unittest
import warnings
from django.utils.deprecation import RemovedInDjango20Warning
with warnings.catch_warnings():
warnings.filterwarnings(
'ignore', 'django.utils.checksums will be removed in Django 2.0.',
RemovedInDjango20Warning)
from django.utils import checksums
class TestUti... |
import matplotlib.pyplot as plt
import cv2
def show_original_and_result(image, result, cmap_result = 'viridis', result_type='BGR'):
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(24, 9))
f.tight_layout()
img = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
ax1.imshow(img)
ax1.set_title('Original Image', fonts... |
# Copyright 2017 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... |
"""
The main module of job schedulers.
"""
import glob
import os
import shutil
import signal
import time
from math import ceil
from typing import List, Tuple, Optional
from ..logger import get_eval_logger
from ..result import Job, Result
from ..util import copy_dir
class Scheduler():
"""The base class of job sch... |
#
# Copyright (c) 2018 Intel Corporation
#
# SPDX-License-Identifier: Apache-2.0
#
from django.conf import settings
from openstack_dashboard.api import base
def get_request_page_size(request, limit=None):
default_limit = getattr(settings, 'API_RESULT_LIMIT', 1000)
try:
return min(int(limit), default_... |
"""Generating problems related to fractions"""
from random import randint, choice
import sympy
class FractionProblemGenerator:
"""This class implements a problem generator for fractions"""
def __init__(self, params):
self.number_of_fractions = int(params[0])
self.max_nominator = int(params[1]... |
# Copyright (C) 2018-2019 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import argparse
import json
import sys
from os import getcwd
from ext_gen.caffe_extractor_descr import MOExtractorDescr
from ext_gen.tf_extractor_descr import MOTFExtractorDescr
from ext_gen.mxnet_extractor_descr import MOMXNetExtracto... |
import json
GLOVE_PATH = "../data/glove.6B.300d.txt"
word_list = []
with open(GLOVE_PATH) as f:
i = 1
for line in f:
values = line.split()
word = values[0]
print(i, word)
i += 1
word_list.append(word)
with open("../data/word_list.json", "w") as f:
json.dump(word_li... |
"""Template helper methods for rendering strings with HA data."""
# pylint: disable=too-few-public-methods
import json
import logging
import re
import jinja2
from jinja2.sandbox import ImmutableSandboxedEnvironment
from homeassistant.const import (
STATE_UNKNOWN, ATTR_LATITUDE, ATTR_LONGITUDE, MATCH_ALL)
from hom... |
import numpy as np
import pytest
from skits.preprocessing import (
ReversibleImputer,
DifferenceTransformer,
LogTransformer,
HorizonTransformer,
)
class TestReversibleImputer:
def test_transform(self):
ri = ReversibleImputer()
X = np.array([1, 1, 100, 0, 2], dtype=np.float64)[:, n... |
import pymysql
def connection():
conn = pymysql.connect(host='localhost',
database='database',
user='root',
password='mysqlpwd')
c = conn.cursor()
return c, conn
# CREATE TABLE tests (test_id VARCHAR(50), test_name VARCHAR(5... |
from flask import Request
class BaseValidator:
'''
The `BaseValidator` class contains a common validation functionality. All
specific validators should inherit from the `BaseValidator`.
'''
def _is_json(self, request: Request) -> bool:
return request.get_json(silent=True) != None
|
import math
from cobra.core.gene import parse_gpr, ast2str
def get_compound_references(model):
compounds_to_refs = {}
for m in model.metabolites:
if not m.id in compounds_to_refs:
compounds_to_refs[m.id] = '~/modelcompounds/id/' + m.id
return compounds_to_refs
def convert_to_kbase(id, ... |
# system imports
import logging
import time
import string
import secrets
import os
# third party imports
from invoke.exceptions import UnexpectedExit
# project imports
import utils
class Polis:
def __init__(self, connection, target_directory):
self.connection = connection
self.target_directory =... |
# coding: utf-8
"""
API v1
DocSpring is a service that helps you fill out and sign PDF templates. # noqa: E501
OpenAPI spec version: v1
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class CreateFolderData(object):
"""NOTE: This class is au... |
from http.server import HTTPServer, BaseHTTPRequestHandler
from datetime import datetime
from threading import Thread
import requests
import json
import urllib.parse
class handler(BaseHTTPRequestHandler):
def do_POST(self):
status = False
try:
length = int(self.headers.get('content-length', 0))
... |
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework import viewsets, mixins, status
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from core.models import Tag, Ingredient, Recipe
from recipe... |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('greet', views.greeting, name='greeting'),
]
|
######################################
# Add this after line "from app.serializers import ApplicationSerializer, LogSerializer"
######################################
from jaeger_client import Config
from flask_opentracing import FlaskTracing
def initialize_tracer():
config = Config(
config={'sampler': {'... |
# -*- coding: utf-8 -*-
# @Author: Theo Lemaire
# @Date: 2022-02-11 14:35:21
# @Last Modified by: Theo Lemaire
# @Last Modified time: 2022-05-11 14:12:19
from turtle import back
import numpy as np
import random
from scipy.signal import welch, butter, filtfilt, find_peaks
from scipy.ndimage.filters import maximum_f... |
from sqlalchemy.orm.session import Session
from sqlalchemy import exc, insert, select, update, delete, asc
from stockprophet.db.model.stock_type import stock_type_table
from stockprophet.db.log import get_logger
logger = get_logger(__name__)
def create_api(s: Session, data_list: list = None) -> bool:
"""依據資料清單... |
from __future__ import absolute_import
from __future__ import print_function
'''
Module implementing the C++ "standalone" device.
'''
import os
import shutil
import subprocess
import sys
import inspect
import struct
from collections import defaultdict, Counter, Mapping
import itertools
import numbers
import tempfile
fr... |
import typing as T
from dataclasses import dataclass
from enum import Enum
import requests
class AutogradeStatus(Enum):
NONE = "NONE"
IN_PROGRESS = "IN_PROGRESS"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
class GraderType(Enum):
AUTO = "AUTO"
TEACHER = "TEACHER"
class ExerciseStatus(Enum):... |
from django.urls import path
from .views import general_search
app_name = 'search'
urlpatterns = [
path('', general_search, name='general_search'),
]
|
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
from typing import Type, Union
import pytest
import yahp as hp
from composer.callbacks.callback_hparams_registry import callback_registry
from composer.core import Callback
from composer.loggers import ObjectStoreLogger
from composer.lo... |
import ctypes
import numpy as np
from PIL import Image
from d3dshot.capture_output import CaptureOutput
class NumpyCaptureOutput(CaptureOutput):
def __init__(self):
pass
def process(self, pointer, pitch, size, width, height, region, rotation):
image = np.empty((size,), dtype=np.uint8)
... |
import logging.config
import os
from pathlib import Path
import torch
from transformers import set_seed as hf_set_seed
# global variable: cache_root
cache_root = Path(os.getenv("FLAIR_CACHE_ROOT", Path(Path.home(), ".flair")))
# global variable: device
if torch.cuda.is_available():
device = torch.device("cuda:0"... |
class Config:
def __init__(self):
self.haarcascade_frontalface_url = "https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_alt2.xml"
self.haarcascade_frontalface_cache = "weights/vision/face_detection/haarcascade/cv2/haarcascade_frontalface_alt2.xml"
... |
from .env import get_root_logger, init_dist, set_random_seed
from .train import batch_processor, build_optimizer, train_detector
# from .inference import init_detector, inference_detector, show_result
__all__ = [
"init_dist",
"get_root_logger",
"set_random_seed",
"train_detector",
"build_optimizer... |
class MerchantService:
def merchant_id_exist(self, merchant_id):
pass |
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.gateway import unwrap_spec, interp2app
from pypy.interpreter.typedef import TypeDef, make_weakref_descr
from pypy.module._cffi_backend import cdataobj, ctypeptr, ctypearray
from pypy.module._c... |
import sys
sys.path.append('waveglow/')
# import glow
from flask import Flask, render_template, redirect, url_for, request, send_from_directory
import numpy as np
import os
from pydub import AudioSegment
from hparams import create_hparams
from train import load_model
import torch
from denoiser import Denoiser
from text... |
from sys import argv
# from the sys module suite -> import argv module
script, user_name, timeStamp = argv
prompt = '> '
print(f"The current time is: {timeStamp}.")
print(f"Hi {user_name}, I'm the {script}.")
print("I'd like to ask you a few questions.")
print(f"Do you like me {user_name}?")
likes = input(prompt)
pr... |
# --------------------------------------------------------
# SiamMask
# Licensed under The MIT License
# Written by Qiang Wang (wangqiang2015 at ia.ac.cn)
# --------------------------------------------------------
import numpy as np
import math
from .bbox_helper import center2corner, corner2center
class Anchors:
... |
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from wagtail.images import get_image_model
from wagtail.images.tests.utils import get_test_image_file
from wagtail.tests.utils import WagtailTestUtils
Imag... |
from setuptools import setup, find_packages
setup(
name = "Boids",
version = "0.1.0",
description = 'Simulate flocking birds',
author = 'Tamara Kohler',
author_email = 'tamara.kohler.16@ucl.ac.uk',
license = 'MIT',
packages = find_packages(exclude=['\test']),
include_package_data=True,
... |
from __future__ import print_function
import os
import shutil
import socket
import subprocess
import time
import unittest
from sysadmin import FetchAllValues
from sysadmin import LazySysAdmin
from sysadmin import SysAdminClient
from sysadmin import SysAdminMigrator
from sysadmin import UnpackFromProto
from sysadmin.g... |
##############################################################################
## This file is part of 'L2SI Core'.
## It is subject to the license terms in the LICENSE.txt file found in the
## top-level directory of this distribution and at:
## https://confluence.slac.stanford.edu/display/ppareg/LICENSE.html.
## No... |
import bpy
import bmesh
import gpu
from .op_mesh import *
from .qpyramid import *
# box create op new
class PyramidCreateOperator(MeshCreateOperator):
bl_idname = "object.pyramid_create"
bl_label = "Pyramid Create Operator"
drawcallback = draw_callback_cube
objectType = 1
# create... |
algorithm = "fourier"
potential = {}
potential["potential"] = "x/4"
T = 6.5
dt = 0.01
eps = 0.1
f = 2.0
ngn = 4096
basis_size = 64
P = 1.0j
Q = 1.0
S = 0.0
parameters = [ (P, Q, S, 0.0, 2.0) ]
coefficients = [[(0, 1.0)]]
write_nth = 2
|
"""Generated message classes for binaryauthorization version v1beta1.
The management interface for Binary Authorization, a system providing policy
control for images deployed to Kubernetes Engine clusters.
"""
# NOTE: This file is autogenerated and should not be edited by hand.
from apitools.base.protorpclite import ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) Camille Scott, 2019
# File : maf.py
# License: MIT
# Author : Camille Scott <camille.scott.w@gmail.com>
# Date : 11.12.2019
import pandas as pd
import numpy as np
from .base import ChunkParser, next_or_raise, convert_dtypes
class MafParser(ChunkParser):
... |
"""added profile_picture_thumbnail_key to user model
Revision ID: ac32c8706044
Revises: 20849c301848
Create Date: 2020-09-29 21:55:12.307753
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ac32c8706044'
down_revision = '20849c301848'
branch_labels = None
depen... |
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from torchvision.extension import _lazy_import
from ._utils import convert_boxes_to_roi_format
class _RoIAlignFunction(Function):
@staticmethod
... |
from django.shortcuts import render
from establishment.webapp.state import State
from establishment.webapp.base_views import single_page_app, global_renderer
def render_single_page_app(request):
return render(request, "{{project_main_app}}/app.html", {})
global_renderer.render_single_page_app = render_single_pa... |
import numpy as np
import opensimplex as simplex
default_num = 100000
class Benchmark:
def __init__(self):
# Randomized coordinate arrays that will supply the noise funcs.
self.x = np.random.random_sample(default_num)
self.y = np.random.random_sample(default_num)
self.z = np.rand... |
# -*-coding:utf-8-*-
import json
import os
import re
import sys
import subprocess
from getpass import getpass
from copy import deepcopy
from apps.configs.config import CONFIG
from apps.configs.sys_config import PROJECT_PATH
from apps.core.logger.web_logging import web_start_log
__author__ = "Allen Woo"
def copy_confi... |
print('''
#include<stdio.h>
int main(){
int tom[2][3];
int i, j;
for(i=0; i<2; i++) {
for(j=0;j<3;j++) {
printf("Enter value for tom[%d][%d]:", i, j);
scanf("%d", &tom[i][j]);
}
}
printf("Two Dimensional array elements:\n");
for(i=0; i<2; i++) {
for(j=0;j<3;j+... |
import sys
import os
def check_path(path):
if not os.path.exists(path):
os.makedirs(path)
def check_var(tensor, tag=None, exit=True):
print('[CHECK_VAL]----------> {}'.format(tag))
print('[CHECK_VAL] Content:\n{}'.format(tensor))
print('[CHECK_VAL] Type: {}'.format(type(tensor)))
if isinst... |
# -*- coding: UTF-8 -*-
import random
import logging
from wechat.content import hitokoto
from wechat.content import iciba
log = logging.getLogger('apscheduler.executors.default')
# 随机选择文库
def get_content(num=0):
if not num:
num = random.randint(0, 2)
if num and num == 1:
content = hitokoto.g... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch
from .kernel import Kernel
from ..lazy import ToeplitzLazyTensor, KroneckerProductLazyTensor
from .. import settings
class GridKernel(Kernel):
r"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Retrieve files from the debuggee's filesystem. Useful when
debugging a remote process over SSH or similar, where e.g.
/proc/FOO/maps is needed from the remote system.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import prin... |
# -*- coding: utf-8 -*-
# @Time : 2018-12-31 18:35
# @Author : play4fun
# @File : QR_Scaner1.py
# @Software: PyCharm
"""
QR_Scaner1.py:
"""
from pyzbar.pyzbar import decode
# from PIL import Image
import cv2
def main():
fp = 'macbookPro.jpg'
# image = Image.open(fp)
# image.show()
image = cv2... |
#
# @lc app=leetcode.cn id=215 lang=python3
#
# [215] 数组中的第K个最大元素
#
# https://leetcode-cn.com/problems/kth-largest-element-in-an-array/description/
#
# algorithms
# Medium (55.90%)
# Total Accepted: 19.3K
# Total Submissions: 34.2K
# Testcase Example: '[3,2,1,5,6,4]\n2'
#
# 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k ... |
import torch
from allennlp.modules.transformer.transformer_module import TransformerModule
class LayerNorm(torch.nn.LayerNorm, TransformerModule):
_pretrained_mapping = {"gamma": "weight", "beta": "bias"}
|
#!/usr/bin/python
# This script plots up the Nusselt number for both the 24x24 and 48x48 cases:
import pylab
from fluidity_tools import stat_parser as stat
# Stafiles:
statfile24="stokes-sc-Ra1e5-24.stat"
statfile48="stokes-sc-Ra1e5-48.stat"
# First plot 24x24 case:
pylab.plot(stat(statfile24)["CoordinateMesh"]["nod... |
# -*- mode: python; coding: utf-8; indent-tabs-mode: nil; python-indent: 2 -*-
#
# $Id$
"""Output image to the file system.
"""
from __future__ import absolute_import, division, print_function
__version__ = "$Revision$"
import logging
import os
from xfel.cxi.cspad_ana import common_mode
from xfel.cxi.cspad_ana imp... |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Copyright 2020 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
#
... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
#
"""
Classes and functions used by L{twisted.trial.test.test_util}
and L{twisted.trial.test.test_loader}.
"""
from __future__ import division, absolute_import
import sys
import os
from twisted.python.compat import _PY3
from twisted.trial impor... |
# Use this animation to show that the
# bin reaches its peak when the input
# signal reaches the bin frequency.
# When you're between bin frequencies,
# the energy spills between adjacent bins
# and the amplitude of the two adjacent
# bins is lower.
from scipy.fft import fft, fftfreq
import numpy as np
from scipy impor... |
"""
OpenAPI Petstore
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
import re # noq... |
from django.conf.urls import url
from .views import site_search
urlpatterns = [
url(r'^search/', site_search, name='site_search'),
]
|
from Processor import Processor
from IO import IO
from Frcnn_Model import Frcnn_Model
from ImageStruct import ImageStruct
class Pipeline:
def __init__(self):
self.io = IO()
self.path = "./input_images/input.zip"
self.preprocessor = Processor()
self.model = Frcnn_Model()
self... |
import pyglet
from pyglet.gl import *
from pyglet import clock, window, image
Width = 640
Height = 480
angle = 0
frame_num = 0
def update(dt):
global angle
angle += 1
angle %= 360
win = window.Window(fullscreen=False, vsync=True, resizable=True, height=Height,
width=Width)
@win.event... |
# Copyright 2022 The AI Flow Authors
#
# 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... |
#!usr/bin/env python
# simulation.py
# Kyle Dewsnap
# July 5th
from typing import Dict
import itertools
import cell
import sys
class Simulation:
def __init__(self, parameters: Dict, log: str):
self._all_cells = [x for x in itertools.product(
*list(parameters.values()))]
# Log can take t... |
# Copyright 2012 OpenStack Foundation
#
# 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... |
# Copyright 2003 by Bartek Wilczynski. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Parsing AlignACE files: AlignAceParser
"""
from Bio.Motif import Motif
from Bio.Alphab... |
"""MH interface -- purely object-oriented (well, almost)
Executive summary:
import mhlib
mh = mhlib.MH() # use default mailbox directory and profile
mh = mhlib.MH(mailbox) # override mailbox location (default from profile)
mh = mhlib.MH(mailbox, profile) # override mailbox and profile
mh.error(format, ...)... |
"""
Writes a Graph to different data formats. The graph can be a KnitNetwork or a
graph prepared for GraphViz / Gephi.
---
Code for writing graph to dot file by Anders Holden Deleuran.
Inputs:
Toggle: Set to True to write the file.
{item, boolean}
Graph: A graph to write to the file.... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import pointfly as pf
import tensorflow as tf
def xconv(pts, fts, qrs, tag, N, K, D, P, C, C_pts_fts, is_training, with_X_transformation, depth_multiplier,
sorting_method=None, with_glob... |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
""" :mod:`telliot_core.dtypes.float_type`
"""
from dataclasses import dataclass
from decimal import Decimal
from typing import Any
from telliot_core.dtypes.value_type import ValueType
@dataclass
class UnsignedFloatType(ValueType):
"""Unsigned Float Type
This class specifies the a floating point value
u... |
"""
xpath mapping from xml file, with convertion functions
"""
from datetime import datetime
import numpy as np
from scipy.interpolate import RectBivariateSpline, interp1d
from shapely.geometry import box
import pandas as pd
import xarray as xr
import warnings
import geopandas as gpd
from shapely.geometry import Polyg... |
#!/usr/bin/env python3
from ctf_gameserver.checkerlib import BaseChecker, CheckResult
from ctf_gameserver import checkerlib
import logging
import random
import nclib
values = [
"Normal",
"Critical",
"Needs investigation"
]
def random_sensor_data():
width = random.randint(10, 20)
height = random.randint(10, 20)
... |
import base64
import os
from Plugin import PluginManager
from Crypt import CryptBitcoin
from lib.pybitcointools import bitcoin as btctools
import CryptMessage
@PluginManager.registerTo("UiWebsocket")
class UiWebsocketPlugin(object):
def encrypt(self, text, publickey):
encrypted = CryptMessage.encrypt(te... |
from __future__ import print_function
import sys
import csv
import cx_Oracle
import os
import time
total = len(sys.argv)
script_name = str(sys.argv[0])
if total != 2:
print ('Script usage: python ', script_name, ' dblist_filename > logfile/log_filename 2>&1')
exit ()
str(sys.argv[1])
dblist = open(str(sys.argv... |
# Created: 10/26/2019
# Author: Emiliano Jordan,
# Project: sejings
from sejings import Sejings
def test_initial(settings):
assert settings.one() == 'one'
assert settings.two() == 'two'
settings.one = 'uno'
settings.two = 'dos'
assert settings.one() == 'uno'
assert settings.two() == 'dos'
|
"""Tests for the SoCoSingletonBase and _ArgsSingleton classes in core."""
import pytest
from pysonos.core import _SocoSingletonBase as Base
class ASingleton(Base):
def __init__(self, arg):
pass
class AnotherSingleton(ASingleton):
pass
class ThirdSingleton(Base):
_class_group = "somegroup"
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import functools
from collections import Counter
from prettytable import PrettyTable
import torch
import torch.nn as nn
from torch.nn.utils.rnn import PackedSequence
from nni.compression.pytorch.compressor import PrunerModuleWrapper
__all__ = ... |
from json import dump, load
from pathlib import Path
from copy import copy as c
from collections import defaultdict
from logging import getLogger
from datetime import date, datetime
from shutil import copy, rmtree
from bidso.utils import replace_extension
from PyQt5.QtSql import QSqlQuery
from ..api import list_subje... |
import unittest
import dynet_config
import dynet as dy
from xnmt.attender import MlpAttender
from xnmt.bridge import CopyBridge
from xnmt.decoder import MlpSoftmaxDecoder
from xnmt.embedder import SimpleWordEmbedder
import xnmt.events
from xnmt.input_reader import PlainTextReader
from xnmt.lstm import UniLSTMSeqTrans... |
#
# PySNMP MIB module DNOS-DHCPCLIENT-PRIVATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DNOS-DHCPCLIENT-PRIVATE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:51:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
from pytrigno import TrignoOrientation
import time
sensors_number = 1
acc_channels = 3*sensors_number
emg_channels = sensors_number
orientation_channels = 4*sensors_number #for quaternion
orientation = TrignoOrientation(channel_range=(0,orientation_channels-1),samples_per_read=100)
orientation.is_paired(1)
time.sleep(... |
#!/usr/bin/env python3
#
# Copyright (c) 2019 Roberto Riggio
#
# 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 applicabl... |
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name='index'),
path('mapa', views.mapa, name='mapa'),
path('ancestries', views.ancestries, name='ancestries'),
path('common', views.c... |
with open('09.txt', 'r') as file:
data = [int(n) for n in file.read().splitlines()]
# Part 1
preamble = 25
for k in range(preamble, len(data)):
exists = False
for i in range(k - preamble, k):
for j in range(i, k):
if data[i] + data[j] == data[k]:
exists = True
if exis... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
# coding=utf-8
# Copyright 2020 The TF-Agents Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... |
#
# @author Pukoa
# @created Fri Jan 04 2019 00:58:07 GMT-0500 (Eastern Standard Time)
# @copyright 2018 - 2022
# @license CC BY-NC-ND 3.0 US | https://creativecommons.org/licenses/by-nc-nd/3.0/us/
# @last-modified Tue Mar 05 2019 02:11:47 GMT-0500 (Eastern Standard Time)
import discum
import time
import sys
... |
# Copyright 2016 Red Hat, 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 agreed to in writing... |
import os, json
import tensorflow as tf
import numpy as np
def get_stats(result_dir, tag_names):
eventFile = [f for f in os.listdir(result_dir) if os.path.isfile(os.path.join(result_dir, f)) and 'events' in f][0]
stats = { key: [] for key in tag_names }
try:
for events in tf.train.summary_iterato... |
"""This module contains observables on a given SpaceTime. Here, observable is defined
to be a function of the SpaceTime, that typically returns a scalar, though there are
some exceptions, like volume profiles.
"""
import numpy
from cdtea import space_time
def volume_profile(st: space_time.SpaceTime) -> numpy.ndarray... |
from django.contrib.auth.models import Group
from django import forms
#
class GroupForm(forms.ModelForm):
class Meta:
model = Group
fields = ('__all__')
|
# -- DATABASE CREATION AND QUERIES -------------------------
# ----------------------------------------------------------
# # -- IMPORTS ---------------------------------------------
# # --------------------------------------------------------
# the sql library
import sqlite3
# TODO - look into using 'sqlcipher'
#... |
#!/usr/bin/env python
import asyncio
from async_timeout import timeout
from collections import OrderedDict
import functools
from hexbytes import HexBytes
import logging
import time
from typing import (
Dict,
List,
Optional
)
from web3 import Web3
from web3.datastructures import AttributeDict
from web3.exce... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import json
import frappe
from frappe import _, throw
from frappe.model.workflow import get_workflow_name, is_transition_condition_satisfied
from frap... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.