content stringlengths 5 1.05M |
|---|
"""
This module is for alternative 3D rotation formalisms besides the Quaternion, Matrix, and Euler representations provided
by the `mathutils` library. They must implement the ``to_quaternion`` method, which returns a `mathutils.Quaternion`
instance, in order to be compatible with the rest of this library. A ``from_ot... |
import pdb
a = "aaa"
pdb.set_trace()
b = "bbb"
c = "ccc"
final = a + b + c
print(final) |
import datetime
import sqlalchemy as sa
import sqlalchemy.orm as orm
from pypi.data.modelbase import SqlAlchemyBase
from pypi.data.releases import Release
class Package(SqlAlchemyBase):
__tablename__ = 'packages'
id = sa.Column(sa.String, primary_key=True)
created_date = sa.Column(sa.DateTime, default=d... |
# -*- coding: utf-8 -*-
import glob
import json
import os
import re
from jsonschema import validate, ValidationError
# 禁止ファイル
prohibited_file_names = ["data.json", "schema.json", "misc.json", "static.json", "private.json", "include.json", "sitepolicy.json"]
# ファイル名パターン
file_name_pattern = "^[0-9a-zA-Z\-_]+\.json$"
fil... |
import time
import datetime
import schedule
import requests
from Utils.health_report_api import health_report
# 自定义参数(请填写)
USERNAME = '' # 统一身份认证账号
PASSWORD = '' # 统一身份认证密码
N = 1 # 你要打卡的天数,1为只打今天,2为打昨天和今天.....以此类推
webhook = ''
dingding_patern = "【每日打卡信息:】"
def job():
a = health_report(USERNAME, PASSWORD, N)... |
# -*- coding: utf-8 -*
from __future__ import annotations
from Core import Console
from Core import converter as Converter
from colorama import Fore
from typing import cast
class UserConfig:
def __init__(self, version: str, token: str, prefix: str, debug: bool, timestamp: bool, cache: bool, cache_time_delta: int)... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import pytest
from packaging.version import Version
from pants.backend.plugin_development import pants_requirements
from pants.backend.plugin_development.pants_requirements import (
G... |
# GPLv3 License
#
# Copyright (C) 2020 Ubisoft
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is dis... |
"""
Distance and Similarity Measures
Different measures of distance or similarity for different types of analysis.
"""
|
"""Test module for stack.py"""
import unittest
from random import randrange
from stack import Stack
class TestStack(unittest.TestCase):
def setUp(self):
self.stack = Stack()
def test_push(self):
self.stack.push(randrange(10))
self.assertEqual(len(self.stack), 1)
self.stack.p... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import csv
import sys
fund_symbols = {
'73935A104': 'QQQ'
}
def import_transactions(paths):
rows = []
for p in paths:
with open(p) as f:
reader = csv.reader(f)
x = [[col.strip() for col in row] for row in reader
... |
import logging
import inspect
import os
log = logging.getLogger( __name__ )
import galaxy.jobs.rules
from .rule_helper import RuleHelper
DYNAMIC_RUNNER_NAME = "dynamic"
DYNAMIC_DESTINATION_ID = "dynamic_legacy_from_url"
class JobMappingException( Exception ):
def __init__( self, failure_message ):
self... |
#!/usr/bin/python
import os
import sys
run = os.system
def extract(line):
p1 = line.find(">")
p2 = line.rfind("<")
return line[p1+1:p2].strip()
def sgm2plain(src_plain, trg_sgm):
"Converse sgm format to plain format"
fin_src_plain = file(src_plain , "r")
fout = file(trg_sgm, "w")
#he... |
from datetime import date
from dateutil.relativedelta import relativedelta
START_DATE = date(2018, 11, 1)
MIN_DAYS_TO_COUNT_AS_MONTH = 10
MONTHS_PER_YEAR = 12
def calc_months_passed(year, month, day):
"""Construct a date object from the passed in arguments.
If this fails due to bad inputs reraise the exc... |
# This is a fork of waf_unit_test.py supporting BDE-style unit tests.
from __future__ import print_function
import fnmatch
import os
import sys
import time
from waflib import Utils
from waflib import Task
from waflib import Logs
from waflib import Options
from waflib import TaskGen
from bdebuild.common import sysut... |
from numba import njit
from seam.add.generic import addOneColumnWithEnergyProvided
from seam.energy.energy import computeDeepEnergy
from seam.seamfinding.gencol import generateColumn
from seam.utils import transposeImg, transposeGray
@njit(parallel=True,nogil=True)
def deepAddOneColumn(npimg,npgray, npnew, pos, gdra... |
import unittest
from check_solution import check_solution
class Test_Case_Check_Solution(unittest.TestCase):
def test_check_solution(self):
self.assertTupleEqual(check_solution('RGBY', 'GGRR'), (1,1)) |
from django.urls import path
from django.contrib.auth import views as auth_views
from .views import ProdutoList, ProdutoDetail, CategoriaList, CategoriaDetail, \
UserList, UserDetail
urlpatterns = [
# Produtos
path('produtos/', ProdutoList.as_view(), name='produto-list'),
path('produtos/<int:pk>/', P... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import codecs
try:
from setuptools import setup, Command
except ImportError:
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup, Command # noqa
from distutils.command.install import INSTALL_SCHEMES
os.en... |
import math
import os.path
import pygame
import random
main_dir = os.path.split(os.path.abspath(__file__))[0]
resource_path = main_dir + os.path.sep + "resources" + os.path.sep
def norm(x, y):
"""Calculates norm of vector (x, y)."""
return math.sqrt(x ** 2 + y ** 2)
def vector_to(speed, from_x, from_y, tar... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/9/9 11:02 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : argsparser.py
# @Project : pypi_seed
import getopt
import os
import sys
from pypi_seed.setting import VERSION
def print_error(msg):
print("\033[0;31;40m%s\... |
import subprocess
#from selenium import webdriver
#from selenium.webdriver.common.by import By
class BrowserHelper(object):
def __init__(self):
option = webdriver.ChromeOptions()
option.add_argument("--start-maximized")
# start of headless mode config
option.add_argument("--headless")
... |
## Program: VMTK
## Language: Python
## Date: January 10, 2018
## Version: 1.4
## Copyright (c) Richard Izzo, Luca Antiga, All rights reserved.
## See LICENSE file for details.
## This software is distributed WITHOUT ANY WARRANTY; without even
## the implied warranty of MERCHANTABILITY or FITNES... |
# -*- coding: utf-8 -*-
"""Example for GAM with Poisson Model and PolynomialSmoother
This example was written as a test case.
The data generating process is chosen so the parameters are well identified
and estimated.
Created on Fri Nov 04 13:45:43 2011
Author: Josef Perktold
"""
from __future__ import print_function... |
import torch
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA
def PCA_sklearn(X):
"""Обчислення PCA за допомогою sklearn"""
pca = PCA(n_components=2)
pca.fit(X)
print('sklearn')
print(pca.components_)
print(pca.explained_variance_)
print(pca.mean_)... |
from __future__ import absolute_import
from __future__ import unicode_literals
import os
from datetime import datetime
from django.test import SimpleTestCase
from corehq.apps.app_manager.tests.util import TestXmlMixin
from corehq.form_processor.interfaces.processor import FormProcessorInterface
from corehq.form_proc... |
import unittest
from unittest.mock import Mock
# ATS
from ats.topology import Device
from genie.metaparser.util.exceptions import SchemaEmptyParserError, \
SchemaMissingKeyError
from genie.libs.parser.iosxe.show_static_routing import ShowIpStaticRoute, \
... |
#!/usr/bin/env python3
# Write a program that simulates random read coverage over a chromosome
# Report min, max, and average coverage
# Make variables for genome size, read number, read length
# Input values from the command line
# Note that you will not sample the ends of a chromosome very well
# So don't count the ... |
"""
The Help class, containing the custom help command.
"""
import logging
from discord.ext import commands
from botforces.utils.discord_common import (
create_general_help_embed,
create_stalk_help_embed,
create_user_help_embed,
create_problem_help_embed,
create_upcoming_help_embed,
create_du... |
from typing import List
import pytest
from yarl import URL
from tests.conftest import HttpRequest, wait_for_website_stub_requests
from website_monitor.website_checker import WebsiteChecker
@pytest.mark.asyncio
async def test_website_checker_sends_request_to_target(
website_checker: WebsiteChecker,
website_s... |
# importing module
import logging
import logging.handlers
import sys
def getLogger(logger_name, test=None):
""" The method generates a logger instance to be reused.
:param logger_name: incoming logger name
:return: logger instance
"""
logger = logging.getLogger(str(logger_name))
log_level =... |
"""
Logger.py: CogRIoT console message log application
"""
__author__ = "Daniel Mazzer"
__copyright__ = "Copyright 2016, CogRIoT Project"
__credits__ = "Inatel - Wireless and Optical Convergent Access Laboratory"
__license__ = "MIT"
__maintainer__ = "Daniel Mazzer"
__email__ = "dmazzer@gmail.com"
import logging
c... |
DAY4_DRAWS = (
"1,76,38,96,62,41,27,33,4,2,94,15,89,25,66,14,30,0,71,21,48,44,87,73,60,50,"
"77,45,29,18,5,99,65,16,93,95,37,3,52,32,46,80,98,63,92,24,35,55,12,81,51,"
"17,70,78,61,91,54,8,72,40,74,68,75,67,39,64,10,53,9,31,6,7,47,42,90,20,19,"
"36,22,43,58,28,79,86,57,49,83,84,97,11,85,26,69,23,59,82,8... |
# You are using Python
class Node() :
def __init__(self, value=None) :
self.data = value
self.next = None
class LinkedList() :
def __init__(self) :
self.head = None
self.tail = None
def insertElements(self, arr) :
"""
Recieves an array of inte... |
#! /usr/bin/env python3
import os.path
from setuptools import setup, find_packages
import magictag
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='magictag',
version=magictag.__version__,
d... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'CrearClub.ui'
#
# Created by: PyQt4 UI code generator 4.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):... |
import pytest
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
from openslides.assignments.models import Assignment, AssignmentPoll
from openslides.cor... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
class Subscribe(models.Model):
firstName = models.CharField(
_("First Name"), max_length=225, blank=True, null=True, )
lastName = models.CharField(
_("Last Name"), max_length=225, blank=True, null=True, )
... |
from models.instructions.shared import Instruction
class CreateCol(Instruction):
def __init__(self, column_name, type_column, properties):
self._column_name = column_name
self._type_column = type_column
self._properties = properties
self._tac = ''
def __repr__(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 26 16:02:47 2018
@author: Ian-A
torch project
"""
from __future__ import print_function
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import pyqtgraph as pg
import torch
import torch.nn as nn #import torch neural network library
import torch.nn.... |
import pexpect
from climatic.CoreCli import CoreCli
from climatic.connections.Ssh import Ssh
from climatic.connections.Ssh import PTY_WINSIZE_COLS as SSH_PTY_WINSIZE_COLS
from climatic.connections.Ser2Net import Ser2Net
from climatic.connections.Ser2Net import PTY_WINSIZE_COLS as SER2NET_PTY_WINSIZE_COLS
from typing i... |
'''/*---------------------------------------------------------------------------------------------
* Copyright (c) VituTech. All rights reserved.
* Licensed under the Apache License 2.0. See License.txt in the project root for license information.
*------------------------------------------------------------------... |
from os import path
from pathlib import Path
from time import time
from docutils import io
from docutils.core import Publisher, publish_parts
from docutils.frontend import OptionParser
from docutils.io import NullOutput, StringOutput
from sphinx.application import ENV_PICKLE_FILENAME, Sphinx
from sphinx.builders impor... |
from typing import List
def reverse_string(s:List[str]) -> None:
"""
To practice use of recursion
"""
def helper(start, end):
if start < end:
s[start], s[end] = s[end], s[start]
helper(start + 1, end - 1)
print("before", s)
n = len(s)
if n > 1: helper(0, n - ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
# EXIT CODE
NON_RESTART_EXIT_CODE = 64 # If a container exited with the code 64, do not restart it.
KILL_ALL_EXIT_CODE = 65 # If a container exited with the code 65, kill all containers with the same job_id.
|
#!/usr/bin/python
##############################################
###Python template
###Author: Elizabeth Lee
###Date: 4/27/14
###Function: plot zOR vs. CFR & proxies (supp figure)
### lab-confirmed hospitalization rates per 100,000 in US population (CDC data)
### proportion of P&I deaths of all-cause mortality vs. IL... |
'''
Made possible thanks to http://www.danielhall.me/2014/09/creating-rr-records-in-route53-with-ansible/
In Ansible lots of things take lists (or comma seperated
strings), however lots of things return dicts. One
example of this is the hostvars and groups variable.
'groups' returns a list of machines in a group, and... |
from .client import Client
from .parser import Parser
# devices
from .devices.binary_device import BinaryDevice
from .devices.normalized_device import NormalizedDevice
from .devices.sequence_device import SequenceDevice
from .devices.value_device import ValueDevice |
import csv
import datetime
from .constants import MAX_NUMBER, MIN_NUMBER, \
MAX_YEAR, MIN_YEAR, \
PERIODS_ABBR, \
START_DATE
class Params:
def __init__(self, year, month):
if year >= MIN_YEAR and year <= MAX_YEAR:
self.year = year
else:
raise ValueError('year m... |
import time
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common import utils
chrome_options = Options()
chrome_options.add_argument("nwapp=" + os.path.dirname(os.path.abspath(__file__)))
testdir = os.path.dirname(os.path.abspath(__file__))
os.... |
from trading.exchanges.websockets_exchanges.implementations.binance_websocket import BinanceWebSocketClient
from .abstract_websocket import AbstractWebSocket
|
import io
from os import path
from setuptools import setup
import isdayoff
here = path.abspath(path.dirname(__file__))
def long_description():
with io.open(file=path.join(here, "README.md"), encoding="utf-8") as file:
return file.read()
def requirements():
with io.open(file=path.join(here, "requi... |
# ----------------- BEGIN LICENSE BLOCK ---------------------------------
#
# Copyright (C) 2018-2019 Intel Corporation
#
# SPDX-License-Identifier: MIT
#
# ----------------- END LICENSE BLOCK -----------------------------------
"..."
import Globs
from qgis.gui import QgsMapToolEmitPoint
from qgis.core import QgsField... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-11-08 19:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auditGroupResults', '0007_auto_20181030_2223'),
]
operations = [
migrations... |
from .framework import (
selenium_test,
SeleniumTestCase,
UsesHistoryItemAssertions,
)
class UploadsTestCase(SeleniumTestCase, UsesHistoryItemAssertions):
@selenium_test
def test_upload_simplest(self):
self.perform_upload(self.get_filename("1.sam"))
self.history_panel_wait_for_hi... |
from math import sin as s
|
from django.apps import AppConfig
class SelfServiceConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apps.self_service'
|
import requests
from bs4 import BeautifulSoup
import urllib.request
stories = []
def getTheGoodStuff(newsstories):
global stories
for data in newsstories:
htmlatag = data.find("h2", class_="title").find("a")
headline = htmlatag.getText()
url = htmlatag.get("href")
d = {"headli... |
import time
from ui import GridWorldWindow
from mdp import GridMDP, value_iteration, policy_extraction, policy_evaluation, policy_iteration, values_converged, policy_converged
class ViewController(object):
def __init__(self, metadata):
self.gridworld = GridWorldWindow(metadata=metadata)
self.mdp =... |
#%%
import itertools
import os
import pandas as pd
#import csv
import olefile
#%%
def combine_paths(directory, files):
return (os.path.join(directory, filename) for filename in files)
def get_excel_for_district(district_path):
files = os.walk(district_path)
files_per_directory = [combine_paths(... |
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, **kwargs):
super(ConvBlock, self).__init__()
self.relu = nn.ReLU()
self.conv = nn.Conv1d(in_channels, out_channels, **kwargs)
self.batchnorm = nn.BatchNorm1d(out_channels)
def forward(self, x):
... |
#!/usr/bin/python3
import platform
import subprocess as sp
import threading
import time
import vrep
class SimHelper(object):
def __init__(self):
if platform.system() != 'Darwin':
self.start_vrep()
self.setup_vrep_remote()
if platform.system() != 'Darwin':
self.che... |
import time
import re
def process_data():
txt = load_txt() # 加载文件
sen_list = phrasing(txt) # 分句
gen_used_input(sen_list) # 生成json
def load_txt():
txt = ''
with open('data/lianyin.txt', 'r', encoding='utf8') as ly:
txt = ly.read()
return txt
def phrasing(par):
sentences = re.... |
# coding=utf-8
from typing import Tuple
from .passenger import (
Passenger,
AdultPsg,
TeenPsg,
ChildPsg,
BabyPsg,
SeniorPsg,
DisabilityAPsg,
DisabilityBPsg,
)
class Discount:
title = ""
disc_code = ""
max_cnt = 0
min_cnt = 0
allow_psg = dict()
def __init__(... |
from scipy.spatial.kdtree import KDTree
from heapq import heappush, heappop
from collections import namedtuple
from .utils import INF, elapsed_time, get_pairs, random_selector, default_selector
from .smoothing import smooth_path
import time
import numpy as np
Metric = namedtuple('Metric', ['p_norm', 'weights'])
Node... |
import argparse
import sys
from typing import Callable
# import the code from this package
import shell_command_logger
from shell_command_logger import print_color
from shell_command_logger.backports import TimeParseException
from shell_command_logger.config import InvalidConfigException
from shell_command_logger.cli i... |
#!/usr/bin/env python3
import argparse
import glob
import numpy as np
import os.path
np.seterr(invalid='ignore') # don't care if we divide by zero in this script
DATA_DIR = '../data'
STATS_FILES = glob.glob(os.path.join(DATA_DIR, 'olim*.txt'))
def get_problem_shape(header):
return tuple(int(s.split('=')[1]) for... |
"""Python Cookbook
Chapter 13, recipe 4 settings
"""
class Configuration:
"""
Generic Configuration
"""
url = {
'scheme': 'http',
'netloc': 'forecast.weather.gov',
'path': '/shmrn.php'
}
class Bahamas(Configuration):
"""
Weather forecast for Offshore including the Bahama... |
import string
import hashlib
import random
password2hash = b"REDACTED"
hashresult = hashlib.md5(password2hash).digest()
sha1 = hashlib.sha1(hashresult)
sha224 = hashlib.sha224(sha1.digest())
for i in range(0, 10):
sha1 = hashlib.sha1(sha224.digest())
sha224 = hashlib.sha224(sha1.digest())
output = sha224.hexdigest()... |
"""Virtual cameras compliant with the glTF 2.0 specification as described at
https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#reference-camera
Author: Matthew Matl
"""
import abc
import numpy as np
import six
import sys
from .constants import DEFAULT_Z_NEAR, DEFAULT_Z_FAR
@six.add_metaclass(abc.AB... |
#!/usr/bin/env python
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import math
from math import factorial
import tf
data1 = np.loadtxt("vicon.txt", skiprows=2)
time1 = data1[:,0] - data1[0,0]
vx_vicon = data1[:,1]
vy_vicon = data1[:,2]
# yaw = data1[:,3]
# qx = data1[:,4]
# qy = data1[:,5]
... |
import re
import sys
from . import PIL_class
from .DNA_nupack_classes import group
from ..utils import error, match
def load_spec(filename):
"""Load a PIL style input specification."""
f = open(filename, "r")
# Create new specification object ...
spec = PIL_class.Spec()
# ... and populate it with the co... |
# -*- coding: utf-8 -*-
"""
@author : Wang Meng
@github : https://github.com/tianpangji
@software : PyCharm
@file : urls.py
@create : 2020/9/9 20:07
"""
from django.urls import path, include
from drf_admin.utils import routers
from monitor.views import users, service, error, ip, crud
router = routers.Admi... |
"""
Implementation of attack methods. Running this file as a program will
apply the attack to the model specified by the config file and store
the examples in an .npy file.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import ... |
# -*- coding: utf-8 -*-
__all__ = ["Base_cir", "Orig_cir", "Elev_cir", "Slope_cir", "Tpi_cir"]
from .base_cir import Base_cir
from .orig_cir import Orig_cir
from .elev_cir import Elev_cir
from .slope_cir import Slope_cir
from .tpi_cir import Tpi_cir
|
"""Add TranslationSyncLogs
Revision ID: 21e927fdf78c
Revises: 44d704928d8c
Create Date: 2015-04-20 23:34:51.724151
"""
# revision identifiers, used by Alembic.
revision = '21e927fdf78c'
down_revision = '44d704928d8c'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by ... |
#! /usr/local/bin/python2.7
# -*- coding: utf-8 -*-
import sys
import os.path
import random
reload(sys)
sys.setdefaultencoding('utf-8')
def load_voc_list(filename):
voc = []
with open(filename, 'r') as fd:
for line in fd:
voc.append(line.strip())
return voc
if __name__ == "__main__" :
... |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from unittest import TestCase
from uw_sws.util import fdao_sws_override
from uw_pws.util import fdao_pws_override
from uw_sws.registration import get_schedule_by_regid_and_term
from uw_sws.term import get_current_term
@fdao_sws_ov... |
"""
Basic statistics calculations on binary classification rank order arrays.
Following https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers
"""
import numpy as np
#combinatorics_helpers as ch
class Stat:
"abstract superclass for shared behavior"
def default_curve(self):
return AreaUnderCu... |
import os
import json
import numpy as np
import concurrent.futures
from MolRep.Utils.config_from_dict import Config
from MolRep.Evaluations.DataloaderWrapper import DataLoaderWrapper
from MolRep.Utils.utils import *
class KFoldAssessment:
"""
Class implementing a sufficiently general framework to do model ... |
import requests
from models.web_page_status import WebPageStatus
class WebPage:
KEY_LOCATION = 'Location'
UA_TYPE_PC = "PC"
UA_TYPE_SP = "SP"
USER_AGENT = {
UA_TYPE_PC: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36",
UA_TYPE_S... |
import argparse
import os
import shutil
import time
from models import GraphModel, edge_loss
from dataset import HungarianDataset
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import logging
from torch_geometric.data ... |
from stacks.daily_temperatures import daily_temperatures, daily_temperatures_brute_force
def test_daily_temperatures_brute_force():
assert daily_temperatures_brute_force([73, 74, 75, 71, 69, 72, 76, 73]) == [1, 1, 4, 2, 1, 1, 0, 0]
def test_daily_temperatures():
assert daily_temperatures([73, 74, 75, 71, 69... |
from pathlib import Path
import logging
from .logger import Logger
from .log_formatter import LogFormatter
class FileLogger(Logger):
fmt = LogFormatter(use_colour=False, output_ts=False)
logger = None
def __init__(self, folder, format=None):
if format is None:
format = ("%(asctime)s|... |
class Solution:
def projectionArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
M, N = len(grid), len(grid[0])
rowMax, colMax = [0] * M, [0] * N
xy = sum(0 if grid[i][j] == 0 else 1 for i in range(M) for j in range(N))
xz = sum(list(map... |
import json
from typing import Iterator, Dict
def load_json(file_path: str) -> Iterator[Dict]:
with open(file_path, 'r') as handle:
return json.load(handle)
|
# coding=utf-8
import argparse
from configparser import ConfigParser
import codecs
class NonExistedProperty(BaseException):
def __init__(self, msg):
self.args = msg
# Note that Config class is NOT thread-safe
class Config:
__instance = None
def __init__(self):
pass
def __new__(cls,... |
#!/usr/bin/env python
# coding=utf-8
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = 'FUCKTHEGRADEPOINT'
import index
|
from setuptools import setup, find_packages
setup(
name="discopyro-bpl",
version="0.2",
packages=find_packages(),
# Project uses reStructuredText, so ensure that the docutils get
# installed or upgraded on the target machine
install_requires=["docutils>=0.3"],
# metadata to display on PyPI... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
### Require Anaconda3
### ============================
### 3D FSC Software Package
### Analysis Section
### Written by Yong Zi Tan and Dmitry Lyumkis
### Downloaded from https://github.com/nysbc/Anisotropy
###
### See Paper:
### Addressing preferred specimen orientation i... |
# -*- coding: utf-8 -*-
from . import geo
class CountryMiddleware(object):
"""
This is a middleware that parses a request
and decides which country the request came from.
"""
def process_request(self, request):
request.COUNTRY_CODE = geo.get_country_from_request(request)
|
#!/usr/bin/env python
# encoding=utf-8
from __future__ import print_function
import threading
from .models import Wxgroups,Wxfriends
import sys
import time
import json
import re
import hashlib
reload(sys)
sys.setdefaultencoding("utf-8")
class GroupsThread(threading.Thread):
def __init__ (self, gitem):
... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import absolute_import, unicode_literals, division
# fix import path
import sys
import os
os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
sys.path.append(os.getcwd())
from puls.tasks import suppliers
import codecs
def runtest(cls, fixtur... |
#
# 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... |
from pathlib import Path
def test_dynamic_configuration(notes: Path) -> None:
import pytz
from types import SimpleNamespace as NS
from my.core.cfg import tmp_config
with tmp_config() as C:
C.orgmode = NS(paths=[notes])
# TODO ugh. this belongs to tz provider or global config or someti... |
"""
Hessian tool for neural networks based on pytorch 0.4.1
"""
name = 'Hessian Flow'
from .eigen import *
|
{
'includes': [
'common.gypi',
],
'target_defaults': {
'conditions': [
['skia_os != "win"', {
'sources/': [ ['exclude', '_win.(h|cpp)$'],
],
}],
['skia_os != "mac"', {
'sources/': [ ['exclude', '_mac.(h|cpp)$'],
],
}],
['skia_os != "linux"', {
... |
# -*- coding: utf-8 -*-
"""
Extract slides from course video
Method: detect frame difference
Pckage need to be installed:
opencv:
opt 1: conda install -c menpo opencv
opt 2: conda install -c conda-forge opencv
Zhenhao Ge, 2020-04-15
"""
import os
import cv2
from PIL import Image
import numpy as np
import ... |
"""
voltLib: Load fontFeatures objects from Microsoft VOLT
======================================================
This module is experimental and incomplete.
"""
import logging
import re
from io import StringIO
from fontTools.ttLib import TTFont, TTLibError
from fontTools.voltLib import ast as VAst
from fontTools.vol... |
import zlib
class StateManager:
def __init__(self):
self.saved = True
self.undo_stack = []
self.undo_ptr = -1
def compress_text(self, text):
return zlib.compress(text.encode())
def decompress_text(self, text):
return zlib.decompress(text).decode()
def push_sta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.