text stringlengths 2 999k |
|---|
''' PQ implementation using binary heap where binary heap
is implemented using array (python list) '''
class PriorityQueue:
# To compare if element is of right or left subtree
LEFT = -1
RIGHT = 1
def __init__(self):
self.heap = []
# For iteration purposes
self.index = 0
... |
"""
To understand why this file is here, please read:
http://cookiecutter-django.readthedocs.io/en/latest/faq.html#why-is-there-a-django-contrib-sites-directory-in-cookiecutter-django
"""
from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site d... |
# This an autogenerated file
#
# Generated with SIMAWorkspace
from typing import Dict,Sequence,List
from dmt.entity import Entity
from dmt.blueprint import Blueprint
from .blueprints.simaworkspace import SIMAWorkspaceBlueprint
from typing import Dict
from sima.sima.moao import MOAO
from sima.sima.scriptablevalue impor... |
import json
import re
from openstackinabox.services.cinder.v1 import base
class CinderV1Volumes(base.CinderV1ServiceBase):
# Note: OpenStackInABox's Keystone Service doesn't have support
# right now for inserting the tenant-id into the URL when
# generating the service catalog. So the service URL he... |
#!/usr/bin/env python3
# -*- coding: utf8 -*-
from __future__ import print_function
import json
# By John-Lin
colors = [
'\033[90m',
'\033[91m',
'\033[92m',
'\033[93m',
'\033[94m',
'\033[95m',
'\033[96m',
]
end_color = '\033[0m'
num_colors = len(colors)
def print_topo(switches=[], links=... |
import ctypes, win32ui, win32process, win32api
if __name__ == "__main__":
PROCESS_ALL_ACCESS = 0x1F0FFF
HWND = win32ui.FindWindow(None, "Settings").GetSafeHwnd()
print("Handle Windows: ", HWND)
PID = win32process.GetWindowThreadProcessId(HWND)[1]
print("Process ID: ", PID)
PROCESS = win32api.Op... |
# Copyright 2012 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 a... |
import swapper
from django.db import models
from accelerator_abstract.models.accelerator_model import AcceleratorModel
from accelerator_abstract.models.base_base_profile import USER_TYPES
DURATION_HELP_TEXT = ('Default deferment duration. Format: '
'days hours:minutes:seconds e.g 1 00:00:00')
... |
# NAME
#
# med2image
#
# DESCRIPTION
#
# 'med2image' converts from medical image data files to
# display-friendly formats (like png and jpg).
#
# HISTORY
#
# 23 February 2015
# o Initial design and coding.
#
# System imports
import os
import glob
import numpy as np
import re
# System dependency i... |
from behave import *
from tests.features.roman import RomanNumerals
@given('create class with number 1')
def step_impl(context):
context.number = RomanNumerals(1)
@when('roman number is generated')
def step_impl(context):
context.new_number = context.number.roman()
@then('roman number should be equal I')
... |
import RPi.GPIO as GPIO
import time
import numpy as np
from motor import *
import csv
import math
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
Kp = 1
Kd = 0.8
Ki = 0.01
desired_x_position = 0
desired_y_position = 0
baseSpeed = 5
maxMotorSpeed = 10
minMotorSpeed = 0
desired_angle = 0
interCounter = 0
interCounter2 ... |
import logging
import jwt
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import Group
from django.core.exceptions import ImproperlyConfigured, PermissionDenied, ObjectDoesNotExist
from django_auth_adfs import signals
from django_aut... |
with open("input.txt") as x:
p1, p2 = x.read().splitlines()
p1 = int(p1[28:]) - 1
p2 = int(p2[28:]) - 1
track = [x for x in range(1, 11)]
p1_score = 0
p2_score = 0
dice_state = 0
def roll():
global dice_state
steps = (dice_state) % 100 + 1
dice_state += 1
return steps
def step(p1_playin... |
#!/usr/bin/env python3
"""
@author:Harold
@file: displayTriangulation.py
@time: 27/09/2019
"""
import numpy as np
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from utils.utils import load_3d_pt_cloud_data_with_delimiter, set... |
import logging
from typing import Dict, Optional, List, Any
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.data import Vocabulary
from allennlp.models.model import Model
from allennlp.modules import FeedForward, Seq2SeqEncoder, MatrixAttention, InputVariationalDropout
from allennlp.mo... |
from datetime import datetime, timedelta
from flask import render_template, flash, redirect, url_for, request, current_app
from flask_login import current_user, login_required
from app import db
from app.main.forms import EditProfileForm, CreateEventForm, AddCoordinatesForm
from app.models import User, Event, Location
... |
#!/usr/bin/env python2
# license removed for brevity
import time
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import Header
from visualization_msgs.msg import Marker
from pythonAPI.mycobot import MyCobot
def talker():
pub = rospy.Publisher('joint_states', JointState, queue_size=10)
... |
#https://leetcode.com/problems/find-the-duplicate-number/
|
# Lint as: python3
# Copyright 2018, The TensorFlow Federated 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 ... |
import logging
import logging.handlers
def CreateLogger(logger_name, filename):
# Create Logger
logger = logging.getLogger(logger_name)
# Check handler exists
if len(logger.handlers) > 0:
return logger # Logger already exists
logger.setLevel(logging.DEBUG)
logger.propagate = False
... |
import npyscreen
from models.artist import Artist, Material
class SearchMaterial(npyscreen.ActionForm):
def create(self):
self.value = None
self.wgMaterial = self.add(npyscreen.TitleSelectOne,
name="Material:",
values=Material.get_a... |
#
# This file is part of Python Client Library for the LCCS Web Service.
# Copyright (C) 2019-2020 INPE.
#
# Python Client Library for the LCCS Web Service is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
from .test_lccs import TestLCC... |
# coding: utf-8
from collections import Counter
lettters = [chr(ord('A')+i) for i in range(26)] + [chr(ord('a')+i) for i in range(26)]
s = Counter(input())
t = Counter(input())
yay = 0
whoops = 0
tmp = Counter()
for lettter in lettters:
tmp[lettter] = min(s[lettter],t[lettter])
s -= tmp
t -= tmp
yay += sum(tmp.val... |
import pyvisa, logging, unittest
from . import BaseTests
from .context import SCTA
from SCTA.System import Mode, LocalOscillator, Transponder
from SCTA.Instrumentation import BTC
# Setup debug logging
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)
class BTC_Test(BaseTests.BaseModulat... |
import logging
from datetime import datetime
from datetime import timedelta
from pytz import timezone
from pytz import utc
from yelp_beans.models import MeetingSpec
from yelp_beans.models import User
from yelp_beans.models import UserSubscriptionPreferences
def get_specs_for_current_week():
week_start = datetime... |
# ============================================================== #
# Unet train #
# #
# #
# Train fusnet with processed dataset in tfrecords f... |
from cryptography.fernet import Fernet
from loadkey import load_key
import os
def decrypt(filename,key):
f = Fernet(key)
with open(filename,"rb") as content:
content = content.read()
decrypted_data = f.decrypt(content)
with open(filename+".dec","wb") as content:
content.wr... |
#!/usr/bin/env/ python
import jsonrpclib
from pprint import pprint as pp
import pyeapi
#ip = '50.76.53.27'
#port = '8443'
#username = 'eapi'
#password = 'ZZteslaX'
#switch_url = 'https://{}:{}@{}:{}'.format(username, password, ip, port)
#switch_url = switch_url + '/command-api'
py3 = pyeapi.connect_to('pynet-sw3')... |
import smart_open
import pandas as pd
import pickle
from im_tutorials.data.s3_transfer import load_df_pkl
def patents_10k():
'''patents_10k
Gets a pre-selected sample of 10,000 patents from ONS.
'''
bucket='innovation-mapping-tutorials'
patents_10k_key='ons/ONS_y02_sample_10000.pkl.bz2'
retur... |
# Copyright (c) 2017-present, Facebook, 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... |
'''
Generator classes
A collections of classes that generate random data of
different types
'''
import datetime
import random
import string
import uuid
from abc import ABC, abstractmethod
from decimal import Decimal
class AbstractGenerator(ABC):
'''
An abstract base class for generator classes
Methods... |
"""Base class for fritzbox_callmonitor entities."""
from datetime import timedelta
import logging
import re
from fritzconnection.lib.fritzphonebook import FritzPhonebook
from homeassistant.util import Throttle
from .const import REGEX_NUMBER, UNKOWN_NAME
_LOGGER = logging.getLogger(__name__)
# Return cached result... |
def test():
assert nlp.meta["name"] == "core_web_sm", "你有读取正确的模型吗?"
assert "print(nlp.pipe_names)" in __solution__, "你有打印组件名字了吗?"
assert "print(nlp.pipeline)" in __solution__, "你有打印流程了吗?"
__msg__.good(
"干得漂亮!当你不确定当前流程的时候,你可以随时打印nlp.pipe_names或者"
"nlp.pipeline来检查下。"
)
|
import os
from gym.envs.registration import register
register(
id='DuckHunt-v0',
entry_point='gym_duckhunt.envs:DuckHuntEnv',
)
ASSETS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "envs", "assets")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import getopt
import sys
import os
import math
import time
import argparse
from visdom import Visdom
sys.path.insert(0, os.path.join('..', '..'))
import torch as T
from torch.autograd import Variable ... |
# Generated by Django 2.2.6 on 2019-10-07 12:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('project_core', '0022_role_to_name'),
]
operations = [
migrations.RenameField(
model_name='geographicalarea',
old_name='area'... |
import lyricsgenius as genius
from Logger import Logger
from Music_metadata import MusicMetadata
api = genius.Genius('jMBPEUpYtfpxRiLxuAkrl_qkD_yOnwYOogk0lQcRmGAJCQE3PfE-UPkfe4tJqyls')
def get_lyric(track_address):
track_data = MusicMetadata(track_address)
track_metadata = track_data.metadata()
artist =... |
#!/opt/local/bin/python
# Physics Equation Graph
# Ben Payne <ben.is.located@gmail.com>
import yaml # used to read "config.input"
import os.path
import sys
lib_path = os.path.abspath('../lib')
sys.path.append(lib_path) # this has to proceed use of physgraph
import lib_physics_graph as physgraf
input_stream=file('conf... |
import math
from PIL import Image
import torch.nn.functional as F
import torch
def unpadding(image, padding):
b, c, h ,w = image.shape
image = image[...,padding:h-padding, padding:w-padding]
return image
def preprocess(image:Image, padding=32, patch_size=1024, transform=None, cuda=True, square=False):
... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'testing_school.settings')
try:
from django.core.management import execute_from_command_line
exce... |
import math
import numpy as np
from .math import *
from .opengl import *
from .objmesh import ObjMesh
# Map of color names to RGB values
COLORS = {
'red' : np.array([1.0, 0.0, 0.0]),
'green' : np.array([0.0, 1.0, 0.0]),
'blue' : np.array([0.0, 0.0, 1.0]),
'purple': np.array([0.44, 0.15, 0.76]),
... |
"""
创建一个应用程序 https://bgm.tv/dev/app/create
Bangumi OAuth 用户授权机制文档 https://github.com/bangumi/api/blob/master/docs-raw/How-to-Auth.md
"""
import json.decoder
import pathlib
import datetime
from os import path
from urllib import parse as url_parse
import requests
from flask import Flask, jsonify, redirect, request, ren... |
'''
Methods that will be used to process and prepare ids event data, before being sent to
Kafka cluster.
'''
import json
import logging
import re
import sys
import tempfile
from datetime import datetime
EPOCH = datetime(1970, 1, 1)
def convert(jsonfile, tmpdir, opts='', prefix=None):
'''
Convert JSO... |
# Copyright 2018 The TensorFlow Probability 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 o... |
# Copyright 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.
"""Presubmit script for changes affecting tools/perf/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about th... |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
import copy
import numpy as np
import pytest
import torch
import torch.nn as nn
from mmcv.utils import _BatchNorm
from mmaction.models import (ResNet, ResNet2Plus1d, ResNet3d, ResNet3dSlowFast,
ResNet3dSlowOnly, ResNetTSM)
from mmaction.models.backbones.resnet_tsm import NL3DWrapper
def... |
# Copyright 2020, The TensorFlow Federated 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 o... |
#!/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu>
License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html)
"""
import base64
import cPickle
import datetime
import thread
import logging
import sys
import glob
import os
impo... |
import json
import scrapy
from kingston.items import *
class ManufacturerSpider(scrapy.Spider):
"""
Get all compatible memory for all motherboards from certain manufacturer
"""
name = 'manufacturer'
allowed_domains = [
'kingston.com',
'www.kingston.com',
]
start_urls = [
... |
from abc import ABC, abstractmethod
from ImpressoraJatoDeTinta import JatoFactory
from ImpressoraLaser import LaserFactory
class IFabricaDeImpressora(ABC):
@abstractmethod
def make_impressora_laser(self) -> object:
pass
@abstractmethod
def make_impressora_jato(self) -> object:
pass
... |
"""central.parse: Parseing and checking.
A library of data definitions and support for comparing and parsing different types of information.
Aim is to provide a large Library of multiple different data formats,
and support for parsing, checking and formatting these datatypes
"""
import re
import bs4
import errno
fro... |
# Copyright 2018 The TensorFlow Probability 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 o... |
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
'target_name': 'gn_lib',
'type': 'static_library',
'dependencies': [
'../../base/base.gyp:base',
],
'sources': [
'action_target_generator.cc',
'action_target_generator.h',
'action_values.cc... |
"""Count the Number of Dialogs you have in your Telegram Account
Syntax: .stat"""
from datetime import datetime
from uniborg.util import admin_cmd
@borg.on(admin_cmd(pattern="stat"))
async def _(event):
if event.fwd_from:
return
start = datetime.now()
u = 0 # number of users
g = 0 # number of ... |
# DO NOT MODIFY THIS FILE DIRECTLY. THIS FILE MUST BE CREATED BY
# mf6/utils/createpackages.py
from .. import mfpackage
from ..data.mfdatautil import ListTemplateGenerator
class ModflowMvr(mfpackage.MFPackage):
"""
ModflowMvr defines a mvr package. This package can only be used to move
water between two ... |
"""The tests for script recorder."""
from __future__ import annotations
import pytest
from homeassistant.components import script
from homeassistant.components.recorder.models import StateAttributes, States
from homeassistant.components.recorder.util import session_scope
from homeassistant.components.script import (
... |
from rest_framework import status
from rest_framework.exceptions import APIException
class NoAuthToken(APIException):
status_code = status.HTTP_401_UNAUTHORIZED
default_detail = "No authentication token provided"
default_code = "no_auth_token"
class InvalidAuthToken(APIException):
status_code = stat... |
import pytest
from mypy_boto3_builder.type_annotations.type_literal import TypeLiteral
class TestTypeLiteral:
def setup_method(self) -> None:
self.result = TypeLiteral("test", ("a", "b"))
def test_init(self) -> None:
assert self.result.children == {"a", "b"}
assert hash(self.result)
... |
from lib.Map import OSMWay, OSMNode
from lib import settings
import lib.trigonometry as trig
import numpy as np
import random
import math
import logging
import pyclipper
import lib.helper as helper
def new_node(lon, lat, color="black"):
n = OSMNode()
n.id = settings.id_counter
settings.id_counter += 1
... |
#add parent dir to find package. Only needed for source code build, pip install doesn't need it.
import os, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0,parentdir)
import gym, logging
from mp... |
lista = [ ]
maior = menor = 0
for c in range(0, 5):
lista.append(int(input(f'Digite um valor na posição {c}: ')))
if c == 0:
maior = menor = lista[c]
else:
if lista[c] > maior:
maior = lista[c]
cmaior = c
if lista[c] < menor:
menor = lista[c]
... |
"""
Classes for the ticks and x and y axis
"""
from __future__ import division, print_function
from matplotlib import rcParams
import matplotlib.artist as artist
from matplotlib.artist import allow_rasterization
import matplotlib.cbook as cbook
import matplotlib.font_manager as font_manager
import matplotlib.lines as... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010-2011 OpenStack Foundation.
# 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... |
"""
This is a wrapper file. It contains no actual implementation
"""
from panda3d.lui import LUIRoot as __LUIRoot
LUIRoot = __LUIRoot
|
'''
Configuration of the alternatives system
========================================
Control the alternatives system
.. code-block:: yaml
hadoop-0.20-conf:
alternatives.install:
- name: hadoop-0.20-conf
- link: /etc/hadoop-0.20/conf
- path: /opt/hadoop/conf
- priority: 30
hadoop-0.2... |
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
print dir_path |
# -*- coding: utf-8 -*-
# SPDX-License-Identifer: Apache-2.0
"""
:Author: FMR LLC
:Email: mabwiser@fmr.com
This module provides a number of constants and helper functions.
"""
from typing import Dict, Union, NamedTuple, NewType, NoReturn
Arm = NewType('Arm', Union[int, float, str])
"""Arm type is defined as integer... |
import os
import cv2
import numpy as np
import tensorflow as tf
import time
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
gpus = tf.config.list_physical_devices('GPU')
print("Devices: ", gpus)
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, False)
img = cv2.imread("imgs/test-img.jpeg")
img = cv2.cvtCo... |
#!/usr/bin/env python3
"""
The game itself!
Much credit goes to the pygame maintainers for their wonderful, many-exampled library.
"""
#Change this stuff as you desire
SCREEN_WIDTH=550
SCREEN_HEIGHT=480
DELAY_FACTOR=3.0
FONT_SIZE=24
DRAG_START_MILLIS=150
DRAG_START_PX=15
# How many lines to /sync at a time. This can... |
"""
This file offers the methods to automatically retrieve the graph Candidatus Yanofskybacteria bacterium RIFCSPHIGHO2_01_FULL_41_26.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019strin... |
from __future__ import unicode_literals
import re
from collections import OrderedDict
INDENT = ' '
ATTR_ESCAPES = {
'<': 'lt',
'>': 'gt',
'&': 'amp',
'"': 'quot',
"\n": '#10'
}
ATTR_ESCAPE_RE = re.compile('|'.join(ATTR_ESCAPES.keys()))
TEXT_ESCAPES = {
'<': 'lt',
'>': 'gt',
'&': 'a... |
import pyvista as pv
data = {"cube": pv.Cube(), "empty": pv.PolyData()}
blocks = pv.MultiBlock(data)
blocks.clean(empty=True)
blocks.keys()
# Expected:
## ['cube']
|
# 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 agre... |
from concurrent.futures import ThreadPoolExecutor
from itertools import count, islice
from collections import deque
import logging
from typing import Iterator, Literal
from gogettr.capabilities.base import Capability
from gogettr.errors import GettrApiError
from gogettr.utils import b36decode, b36encode, extract, merg... |
# Copyright 2020 Google LLC
#
# 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, s... |
from functools import wraps
from flask import flash, url_for, redirect, request, abort
from flask_login import current_user
from mongoengine.connection import MongoEngineConnectionError
from .models import Permission
def permission_required(permission):
def decorator(f):
@wraps(f)
def decorated_fu... |
TOKEN = "TOKEN FROM BOTFATHER"
DB_URI = "POSTGRES DATABASE URI"
|
# https://ktaivle-ai.moducoding.com/Question/1796/View/1
# 지방선거
import sys
from collections import defaultdict
n = int(sys.stdin.readline())
n_dict = defaultdict(int)
for _ in range(n):
a = int(sys.stdin.readline())
n_dict[a] += 1
n_dict = sorted(n_dict.items(), key=lambda x:(-x[1], x[0]))
print(n_dict[0][0... |
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from django.db import models
from django.utils import timezone
from django.db.models.signals import pre_save
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.dispatch import receiver
from django.db.models.signals import post_save
# from authen.models import... |
#!/usr/bin/python
#
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
#
"""See docstring for ChefAttributeHash class."""
from __future__ import absolute_import
from autopkglib import Pr... |
import os.path as op
import re
import numpy as np
from numpy.testing import (assert_array_almost_equal, assert_equal,
assert_allclose, assert_array_equal,
assert_array_less)
from scipy import sparse
import pytest
import copy
import mne
from mne.datasets import te... |
try: # mDebugOutput use is Optional
from mDebugOutput import ShowDebugOutput, fShowDebugOutput;
except ModuleNotFoundError as oException:
if oException.args[0] != "No module named 'mDebugOutput'":
raise;
ShowDebugOutput = lambda fx: fx; # NOP
fShowDebugOutput = lambda x, s0 = None: x; # NOP
def cFileSystem... |
#!/usr/bin/env python
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*-
# ex: set expandtab softtabstop=4 shiftwidth=4:
#
# Copyright (C) 2011,2012,2013,2014,2015,2016,2017,2018 Contributor
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the ... |
# Copyright 2020 - 2021 MONAI Consortium
# 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... |
# Copyright 2012 the V8 project authors. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... |
from .main import parse
|
# Copyright (c) Facebook, Inc. and its affiliates.
import abc
import array as ar
import builtins
import functools
from dataclasses import dataclass
from typing import Optional
import numpy as np
import torcharrow.dtypes as dt
from .icolumn import IColumn
# ------------------------------------------------------------... |
import inspect
import os
import platform
import subprocess as sp
import sys
import re
import traceback
import importlib.util
import types
from .config import file_writer_config, args
from .utils import cfg_subcmds
from .scene.scene import Scene
from .utils.sounds import play_error_sound
from .utils.sounds import play_... |
# Autogenerated file. ANY CHANGES WILL BE OVERWRITTEN
from to_python.core.types import FunctionType, \
FunctionArgument, \
FunctionArgumentValues, \
FunctionReturnTypes, \
FunctionSignature, \
FunctionDoc, \
FunctionData, \
CompoundFunctionData
DUMP_PARTIAL = [
CompoundFunctionData(
... |
import unittest
from bs4 import BeautifulSoup
from acl.conference import Conference
class TestConference(unittest.TestCase):
def test_set_anthology(self):
element = BeautifulSoup(PAGE.strip(), "html.parser")
c = Conference("http://dummy")
c.set_anthology(element)
self.assertEqual... |
# Geographic geometry utility functions
# I tested geo-py but precision was inferior(?).
# I'd love to user pyturf but it does not have all function I need
# and it loads heavy packages.
# So I made the functions I need.
#
import math
import json
# Geology constants
R = 6371000 # Radius of third rock from t... |
# most important extractor are in spikeinterface.core
from spikeinterface.core import (BinaryRecordingExtractor,
NpzSortingExtractor, NumpyRecording, NumpySorting)
# sorting/recording/event from neo
from .neoextractors import (
MEArecRecordingExtractor, MEArecSortingExtractor, read... |
from django.conf.urls import url
from . import views
app_name = "users"
urlpatterns = [
url(
regex=r'^explore/$',
view=views.ExploreUsers.as_view(),
name="explore_users"
),
url(
regex=r'^(?P<user_id>[0-9]+)/follow/$',
view = views.FollowUser.as_view(),
name='... |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "Amazon CloudWatch Synthetics"
prefix = "synthetics"
class Action(BaseAction):
def __init__(self, action: str = None) -... |
import unittest
from deepml.train import Learner
from deepml.losses import RMSELoss
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset
import torchvision
class TestDataSet(torch.utils.data.Dataset):
""" Class useful for reading images from a dataframe.
... |
# -*- coding: utf-8 -*-
import re
import pytest
from mimesis import Business
from mimesis.data import (
CRYPTOCURRENCY_ISO_CODES,
CRYPTOCURRENCY_SYMBOLS,
CURRENCY_ISO_CODES,
CURRENCY_SYMBOLS,
)
from . import patterns
class TestBusiness(object):
@pytest.fixture()
def _business(self):
... |
#!/usr/bin/env python3
#
# Author: Vincent Perricone <vhp@fastmail.fm>
# Date: 5/2014
# Title: SUBTASK
# Description: Todo list manager with subtasks
# License: Released under "Simplified BSD License" see LICENSE file
import json
from subtask.config import Configuration
from subtask.task import Task
from subt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.