text stringlengths 1 927k |
|---|
# Copyright 2018 The Cirq Developers
#
# 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 law or agreed to in ... |
import os, glob
def get_last_timestamped_dir_path(data_dir_path):
glob_path = os.path.join(os.path.expanduser(data_dir_path), '2*')
date_paths = glob.glob(glob_path)
date_paths.sort()
return date_paths[-1] if date_paths else None
if __name__ == '__main__':
print(get_last_timestamped_dir_path('~/fake_scraper... |
#!/usr/bin/env python3
# Copyright (c) 2010 ArtForz -- public domain half-a-node
# Copyright (c) 2012 Jeff Garzik
# Copyright (c) 2010-2019 The Bitcoin Core Developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Bitcoin test... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
"""
---
title: CIFAR10 Experiment to try Group Normalization
summary: >
This trains is a simple convolutional neural network that uses group normalization
to classify CIFAR10 images.
---
# CIFAR10 Experiment for Group Normalization
"""
import torch.nn as nn
from labml import experiment
from labml.configs import ... |
#!/usr/bin/env python
import base_filters
COPY_GOOGLE_DOC_KEY = '1QOOhihZdUwdAJcUgkeokbx7YaDSkSGWtlXHvKXhHW3E'
USE_ASSETS = False
# Use these variables to override the default cache timeouts for this graphic
# DEFAULT_MAX_AGE = 20
# ASSETS_MAX_AGE = 300
JINJA_FILTER_FUNCTIONS = base_filters.FILTERS |
from nca47.db import api as db_api
from nca47.db.sqlalchemy.models import Proximity as ProximityModel
from nca47.objects import base
from nca47.objects import fields as object_fields
class ProximityInfo(base.Nca47Object):
VERSION = '1.0'
fields = {
'tenant_id': object_fields.StringField(),
's... |
#!/usr/bin/env python
# kktmat.py -- KKT matrix from Laplacian matrix
#
# Copyright (C) <2016> <Kevin Deweese>
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
import scipy
def kktmat(L):
mat=scipy.sparse.coo_matrix(s... |
from SimpleCV import *
import time
"""
This is an example of HOW-TO use FaceRecognizer to recognize gender
of the person.
"""
def identifyGender():
f = FaceRecognizer()
cam = Camera()
img = cam.getImage()
cascade = LAUNCH_PATH + "/" + "Features/HaarCascades/face.xml"
feat = img.findHaarFeatures(ca... |
# pylint: disable=missing-docstring
import getpass
import os
from celery.schedules import crontab
from readthedocs.core.settings import Settings
from readthedocs.projects.constants import CELERY_LOW, CELERY_MEDIUM, CELERY_HIGH
try:
import readthedocsext # noqa
ext = True
except ImportError:
ext = Fals... |
#
# Copyright (c) 2015 Red Hat
# Licensed under The MIT License (MIT)
# http://opensource.org/licenses/MIT
#
import django_filters
from django.db.models import Q
from django_filters import FilterSet
from pdc.apps.common.filters import MultiValueFilter, MultiValueRegexFilter, value_is_not_empty
from . import models
fr... |
import sys
n, r = map(int, sys.stdin.readline().split())
def main():
res = r + 100 * max(10 - n, 0)
return res
if __name__ == '__main__':
ans = main()
print(ans) |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
from django.conf.urls import include, url
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register('courses', views.CourseViewSet)
urlpatterns = [
url(r'^subjects/$', views.SubjectListView.as_view(), name='subject_list'),
url(r'^subjects/(?P<pk>\d+)/$', views.Su... |
import importlib
import logging
from zygoat.constants import Phases, Projects
from zygoat.components import Component
from zygoat.config import yaml
from . import resources
log = logging.getLogger()
file_name = 'docker-compose.yml'
class DockerCompose(Component):
def _dump_config(self, data):
with open(... |
#!/usr/bin/python3
import argparse
from os.path import isfile
from pathlib import Path
from re import compile, findall, split as re_split, sub, search, match
from utils import error
def parse_buffer(encode_detail_buffer, shellcode, numberbefore=0, numberafter=0):
"""
parse le buffer et renvoie un tuple comm... |
# -*- coding: utf-8 -*-
import iso8601
def to_days(date):
timedelta = iso8601.parse_date(date) - iso8601.parse_date("1970-1-1")
return timedelta.days
class Series(object):
__slots__ = ('series_id', 'title', 'release_date', 'series_info')
def __init__(self, series_id, title, release_date, series_inf... |
"""
I want to know, whether the imitation process leads to equal return rates in both sectors.
Parameters that this could depend on are
1) the rate of exploration (random changes in opinion and rewiring),
2) also, the rate of rewiring could have an effect.
This should only work in the equilibrium condition where the ... |
# version code 80e56511a793+
# Please fill out this stencil and submit using the provided submission script.
# Some of the GF2 problems require use of the value GF2.one so the stencil imports it.
from GF2 import one
## 1: (Problem 2.14.1) Vector Addition Practice 1
#Please express each answer as a list of numbers
... |
import argparse
import sys
from collections import Counter
from tqdm import tqdm
from transformers import AutoTokenizer
def read_and_preprocess(file:str):
subword_len_counter = 0
with open(file, "rt") as f_p:
for line in f_p:
line = line.rstrip()
if not line:
y... |
import argparse
import csv
import torch
import transformers
def parse_arguments():
parser = argparse.ArgumentParser(description="MiniConf Portal Command Line")
parser.add_argument("papers", default=False, help="papers file to parse")
return parser.parse_args()
if __name__ == "__main__":
args = par... |
from distutils.core import setup, Extension
import sys
major_version = '4'
minor_version = '0'
cpplmodule = Extension('cppl_cpp_python_bridge',
define_macros = [('MAJOR_VERSION', major_version),
('MINOR_VERSION', minor_version)],
include_dir... |
import os
class Config:
SECRET_KEY = os.environ.get('SECRET_KEY')
SQLALCHEMY_TRACK_MODIFICATIONS = False
UPLOADED_PHOTOS_DEST = 'app/static/photos'
# email configurations
MAIL_SERVER = 'smtp.googlemail.com'
MAIL_PORT = 587
MAIL_USE_TLS = True
MAIL_USERNAME = os.environ.get("MAIL_USER... |
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "lice... |
import torch
from algorithms.single_model_algorithm import SingleModelAlgorithm
from models.initializer import initialize_model
class GroupDRO(SingleModelAlgorithm):
"""
Group distributionally robust optimization.
Original paper:
@inproceedings{sagawa2019distributionally,
title={Distribu... |
import numpy
from matplotlib import pyplot
import gdal
from skimage import io,exposure
from skimage.segmentation import slic,mark_boundaries
import os
from PIL import Image
import shelve
import sys
sys.path.append('..')
from Config import config
def seg(path,n_segments=500, compactness=20):
i=io.imread(path)[:,... |
import maya.cmds as mc
class UserInputError(Exception): pass
class Spaces(object):
def __init__(self):
'''
Initializer for Spaces class object
'''
self.allChannels = ['t','tx','ty','tz','r','rx','ry','rz','s','sx','sy','sz']
self.channels = self.allChannels[0:8]
self.transform = ['transform','joint']
... |
try:
from django.urls import path
from django.contrib import admin
urlpatterns = [path('admin', admin.site.urls)]
except ImportError:
# django < 2.0
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [url(r'^admin/', include(admin.site.urls))] |
# Copyright 2021 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... |
#
# PySNMP MIB module ZYXEL-BRIDGE-CONTROL-PROTOCOL-TRANSPARENCY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-BRIDGE-CONTROL-PROTOCOL-TRANSPARENCY-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:43:05 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Bitcash documentation build configuration file, created by
# sphinx-quickstart on Mon Feb 20 15:41:44 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# au... |
import geopandas as gpd
# Networkx werkt erg traag
gdf = gpd.read_file(r"C:\Users\bruno\Downloads\snelwegen_provincie.geojson")
gdf |
import socket
import sys
ESP_IP = '192.168.7.1'
PORT = 10000
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('try to connect')
sock.connect((ESP_IP, PORT))
print('connected...')
data = sock.recv(255)
print('msg: ', data.decode())
sock.close() |
# Copyright 2017 FUJITSU LIMITED
#
# 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 writ... |
#!/usr/bin/env python3
import rospy
import cv2
from sensor_msgs.msg import Image
from cv_bridge import CvBridge
import numpy as np
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5, 5))
kernel1= cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3, 3))
aratio = 1.0
def nothing(x):
pass
# ********************... |
'''
Openstack App for Splunk
Copyright (c) 2017, Great Software Laboratory Private Limited.
All rights reserved.
Contributor: Vikas Sanap [vikas.sanap@gslab.com], Basant Kumar [basant.kumar@gslab.com]
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the f... |
#line = r'''execute if score waveGlowTimer glowTimer matches %s run tag @e[type=!player,type=!dolphin,distance=%s,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}] add madeGlowing'''
#type=!player,type=!dolphin,distance=16..20,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}
line =... |
import os
import re
import secrets
import string
import pulumi
from pulumi import ResourceOptions
from pulumi_kubernetes.apps.v1 import Deployment
from pulumi_kubernetes.core.v1 import Service
from azure.keyvault import KeyVaultClient, KeyVaultAuthentication, KeyVaultId
from azure.common.credentials import ServicePri... |
#!/usr/bin/env python
import argparse
from .database import YamlDatabase as DB
from . import utils
def cli():
parser = argparse.ArgumentParser()
parser.add_argument('-S', '--scope', default='directory', help="flag scope")
parser.add_argument('-F', '--output-format', default='yaml', dest='format', help="outp... |
# coding: utf-8
from __future__ import unicode_literals
from spacy.lang.da import Danish
import pytest
@pytest.fixture(scope="session")
def da_nlp():
return Danish()
@pytest.mark.parametrize(
"string,lemma",
[
("affaldsgruppernes", "affaldsgruppe"),
("detailhandelsstrukturernes", "detai... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libcircle(AutotoolsPackage):
"""libcircle provides an efficient distributed queue on a clu... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Copyright (c) 2018-2019 NVIDIA CORPORATION. All rights reserved.
"""Centralized catalog of paths."""
import os
class DatasetCatalog(object):
DATA_DIR = os.environ['DATA_DIR']
DATASETS = {
"coco_2017_train": {
"img_d... |
import tensorflow.compat.v1 as tf
#from tensorflow.contrib import slim
import tf_slim as slim
from avod.core.avod_fc_layers import avod_fc_layer_utils
def build(fc_layers_config,
input_rois, input_weights,
num_final_classes, box_rep,
is_training,
end_points_collection):
"... |
from __future__ import division
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
import cv2
from .util import *
from .darknet import Darknet
from .preprocess import prep_image, inp_to_image, letterbox_image
import pandas as pd
import random
import pickle as pkl
im... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2016 Abram Hindle, https://github.com/tywtyw2002, and https://github.com/treedust
#
# 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
#
# ... |
#!/usr/bin/python
########################################################################################################################
#
# Copyright (c) 2014, Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permi... |
from django.contrib.auth.models import User
from django.urls import reverse_lazy
from .models import FakeNews
from ..utils.base_test import AuthenticationTestTemplate
class FakeNewsListTestCase(AuthenticationTestTemplate):
def _get_callable_client_method_http(self):
return self._client.get
def _get_... |
# Ronschool.py
class Student:
def __init__(self,name): # self คือคำพิเศษเพื่อใช้แทนตัวมันเอง / ต้องใส่ทุกฟังชั่นของ class
self.name = name
# student1.name
# self = student1
self.exp = 0
self.lesson = 0
def Hello(self):
print('สวัสดีจ้าาาา ผมชื่อ{}'.format(self.name))
def Coding(self):
print('{}: กำ... |
"""Console script for mspsmc."""
import argparse
import sys
def main():
"""Console script for mspsmc."""
parser = argparse.ArgumentParser()
parser.add_argument("_", nargs="*")
args = parser.parse_args()
print("Arguments: " + str(args._))
print("Replace this message by putting your code into "... |
from scipy import signal
from scipy import misc
from scipy import stats as st
import numpy as np
W = 128
L = 128
Body_Width = 3
Border = Body_Width+1
Points = 10
Noise_Max = 10
Body_Separation = 15
Body_Scale = 30
OvScale = 3
def gkern(kernlen=21, nsig=3):
''' 2D Gaussian Kernel. '''
x = np.linspace(-nsig, n... |
#
# Copyright (c) 2020 Cord Technologies Limited
#
# 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... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""Schema for modules.yaml configuration file.
.. literalinclude:: _spack_root/lib/spack/spack/schema/modules.py
:line... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 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
#
# ... |
import _plotly_utils.basevalidators
class ZValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self, plotly_name="z", parent_name="isosurface.lightposition", **kwargs
):
super(ZValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_nam... |
# (C) Datadog, Inc. 2020-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import pytest
from datadog_checks.base import OpenMetricsBaseCheckV2
from datadog_checks.base.constants import ServiceCheck
from datadog_checks.dev.testing import requires_py3
from .utils import get_chec... |
from datetime import datetime
from pandas import DataFrame
from models.PyCryptoBot import PyCryptoBot
from models.AppState import AppState
from models.helper.LogHelper import Logger
import sys
class Strategy:
def __init__(
self,
app: PyCryptoBot = None,
state: AppState = AppState,
... |
"""
byceps.services.shop.order.actions.ticket
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from typing import Any, Sequence
from uuid import UUID
from .....typing import UserID
from ....ticketing.dbmodels.ticket impor... |
"""
Module defining classes for tracking results from simulations.
The trackers defined in this module are:
.. autosummary::
:nosignatures:
CallbackTracker
ProgressTracker
PrintTracker
PlotTracker
DataTracker
SteadyStateTracker
RuntimeTracker
ConsistencyTracker
MaterialConservationTrack... |
import os
import shutil
from typing import List, Tuple
import unittest
from google.protobuf import json_format
from mir.protos import mir_command_pb2 as mirpb
from mir.tools import data_exporter, hash_utils, mir_storage_ops
from tests import utils as test_utils
class TestArkDataExporter(unittest.TestCase):
# li... |
# apis_v1/documentation_source/sitewide_daily_metrics_sync_out_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def sitewide_daily_metrics_sync_out_doc_template_values(url_root):
"""
Show documentation about sitewideDailyMetricsSyncOut
"""
required_query_parameter_list = [
... |
from django.urls import path
from . import views
from .views import SearchResultsView, HomePageView
urlpatterns = [
path('', views.index, name='index'),
# path('books/', views.BookListView.as_view(), name='books'),
path('search/', SearchResultsView.as_view(), name='search_results'),
path('home/', HomePa... |
#!/usr/bin/env python
try:
from lxml import etree
except ImportError:
try:
import xml.etree.ElementTree as etree
except ImportError:
#try:
# import xml.etree.cElementTree as etree
# commented out because xml.etree.cElementTree is giving errors with dictionary attribute... |
from pyredis import RedisConnection
from pprint import pprint
# 1. Object Creation
# pass everything you would pass to redis.Redis()
redis_args = {
'host': 'localhost',
# 'password': 'redis1234',
# 'port': 1234,
}
with RedisConnection(**redis_args) as my_redis:
my_redis.set('key', 'value')
# 2. Red... |
'''
Created on Jul 17, 2013
@author: Yubin Bai
'''
import time
from multiprocessing.pool import Pool
parallelSolve = False
INF = 1 << 31
def solve(par):
M, pairs = par
pairs.sort()
pairs1 = []
for p in pairs:
if p[0] >= M or p[1] <= 0:
continue
pairs1.append(tuple(p))
i... |
# Copyright (c) 2012 The Khronos Group Inc.
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and /or associated documentation files (the "Materials "), to deal in the Materials without restriction, including without limitation the rights to use, copy, modify, merge, publis... |
from typing import Tuple
from codegen.ast import *
from codegen.sugar import *
from codegen.forms import *
from codegen.precision import *
import scripts.old_arm
import scripts.max_bn_knl
from cursors import *
import architecture
import numpy
def decompose_pattern(k, n, pattern:Matrix[bool], bk:int, bn:int) -> Tup... |
# 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.
# ---------------------------------------------------------------------... |
from moviepy.editor import *
from os import chdir, getcwd, mkdir
from random import randint
import sys
import requests
from concurrent.futures import ThreadPoolExecutor
from requests import get, head
import time
# 自定义
THREAD_NUM=12 # 线程数,默认为12个
HEADER=" "# 请求头,默认为一个空格
class downloader:
def __init__(self, url, nu... |
#
# Copyright 2021 Budapest Quantum Computing Group
#
# 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... |
import sys
import pickle
import typing
import inspect
import pkgutil
import importlib
import ipaddress
import json
import re
from pathlib import Path
from cmd2.ansi import style
from collections import defaultdict
from ..recon.config import defaults
def meets_requirements(requirements, exception):
""" Determine... |
import os
import unittest
from typing import Optional
from django.http import HttpResponse
from django.test import RequestFactory
from request_limiter import request_limiter, LimitedIntervalStrategy, \
LimitStrategy, LimitException, django_request_limiter
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_set... |
import siliconcompiler
############################################################################
# DOCS
############################################################################
def make_docs():
'''
Demonstration target for compiling ASICs with FreePDK45 and the open-source
asicflow.
'''
ch... |
from typing import Set
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
tags: Set[str] = []
@app.post(
"/items/",
response_model=Item,
summary="Create an item",
res... |
#!/usr/bin/env python
# coding=UTF-8
import requests
import json
import datetime
from config.configuration import flower_path, flower_port, flower_server_external, verify_certificate, \
flower_server_internal
def get_task_info(task_id):
flower_request_url = 'http://%s:%s%sapi/tasks' % (flower_server_interna... |
from __future__ import absolute_import
from __future__ import with_statement
import sys
import logging
from tempfile import mktemp
from celery import log
from celery.log import (setup_logger, setup_task_logger,
get_default_logger, get_task_logger,
redirect_stdouts_to_lo... |
# coding: utf-8
# Modify a specific group entry in database
# Created by James Raphael Tiovalen (2021)
import slack
import ast
import settings
import config
from slackers.hooks import commands
conv_db = config.conv_handler
@commands.on("editgroup")
def editgroup(payload):
return |
"""Example of pykitti.odometry usage."""
import itertools
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import pykitti
__author__ = "Lee Clement"
__email__ = "lee.clement@robotics.utias.utoronto.ca"
# Change this to the directory where you store KITTI data
basedir = './da... |
# -*- coding:utf-8 -*-
# @author :adolf
import os
from data.data_utils import order_points_clockwise
from data.data_aug import *
from data.make_labels import *
class CurrentOcrData(object):
def __init__(self, root, pre_processes=None, transforms=None, filter_keys=None, ignore_tags=None, is_training=True):
... |
# -*- coding: utf-8 -*-
"""
二叉树:填充每个节点的下一个右侧节点指针2
https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/
"""
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = ... |
from tinypy.runtime.testing import UnitTest
class MyTest(UnitTest):
def test_lessthan(self):
assert [1, 2] < [2]
assert [1, 2] <= [2]
assert [1] < [2]
assert [1] <= [2]
assert [] < [1]
def test_greaterthan(self):
assert [2] > [1]
assert [1, 2] > [1]
... |
# Generated by Django 3.2.5 on 2022-03-24 15:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('store', '0008_alter_product_product_name'),
]
operations = [
migrations.AlterField(
model_name='product',
name='imag... |
# -*- coding: utf-8 -*-
import fnmatch
import os
from os.path import join as _j
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from django_extensions.management.utils import signalcommand
class Command(BaseCommand):
help = "Removes all python bytecode compiled... |
from config import Configuration
from pymongo import MongoClient
c = Configuration("config.json")
client = MongoClient(c.mongo_uri)
database = client.linkage_agent
results = database.match_groups.aggregate(
[
{
"$group": {
"_id": {"$size": "$run_results"},
"tota... |
from nose.tools import assert_almost_equal, assert_equal, raises
from numpy.testing import assert_allclose
import numpy as np
from SALib.test_functions.Sobol_G import evaluate, total_variance, \
partial_first_order_variance, \
sensitivity_index... |
# 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 ... |
"""Inconsistent spelling.
---
layout: post
source: Intelligent Editing Ltd.
source_url: http://bit.ly/1x3hYj7
title: Inconsistent spelling
date: 2014-06-10 12:31:19
categories: writing
---
Intelligent Editing Ltd. says:
> Some words have more than one correct spelling. American, British, Australia... |
from setuptools import find_packages, setup
if __name__ == "__main__":
setup(
name="manipulathor",
packages=find_packages(),
version="0.0.1",
install_requires=[
"allenact==0.2.2",
"allenact_plugins[ithor]==0.2.2",
"setuptools",
],
) |
# -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2021 Dinesh Pinto
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, ... |
"""
proxy patterns: 代理模式
为其它对象提供一种代理以控制对这个对象的操作
要素:
一个开放的方法集(interface)
实现相应方法集的proxy 对象
实现了相应方法集的类
应用:
远程代理, 为一个对象在不同地址空间提供局部代表, 这样就可以隐藏一个对象存在于不同地址空间的事实
哪么两个进程间, 是否可以通过这样的方式实现数据共享
虚拟代理, 根据需要创建开销很大的对象, 通过它存放实例化需要很长时间的真实对象
安全代理, 用来控制真实对象访问时... |
from datetime import date
from pathlib import Path
from miranda.eccc import aggregate_nc_files, convert_hourly_flat_files
if __name__ == "__main__":
var_names = [
"atmospheric_pressure",
"wind_speed",
"relative_humidity",
"dry_bulb_temperature",
"freezing_rain",
"i... |
# Generated by Django 2.1.2 on 2019-01-28 07:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Email",
fields=[
(
"id",
... |
"""
Writes out hex colors from color scales provided in matplotlib
into JS file
python colors_from_mpl.py >> js/colorscales.js
"""
import itertools
import json
import numpy as np
import matplotlib.colors
import matplotlib.cm
# Have colormaps separated into categories:
# http://matplotlib.org/examples/color/colormap... |
# Copyright 2017 Rodeo FX. All rights reserved.
from .utils import dpiScale
from .utils import toPyObject
from .walterBaseTreeView import ACTIONS
from .walterBaseTreeView import BaseDelegate
from .walterBaseTreeView import BaseItem
from .walterBaseTreeView import BaseModel
from .walterBaseTreeView import BaseTreeView
... |
#!/usr/bin/env python
"""
Example of running a prompt_toolkit application in an asyncssh server.
"""
import asyncio
import logging
import asyncssh
from pygments.lexers.html import HtmlLexer
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.contrib.ssh import PromptToolkitSSHServer, PromptToolkit... |
from .tool.func import *
def login_register_2(conn):
curs = conn.cursor()
if ban_check(None, 'login') == 1:
return re_error('/ban')
ip = ip_check()
admin = admin_check()
if admin != 1 and ip_or_user(ip) == 0:
return redirect('/user')
if admin != 1:
curs.execute(db_cha... |
#!/usr/bin/env python3
# Copyright 2022 joseph
# See LICENSE file for licensing details.
#
# Learn more at: https://juju.is/docs/sdk
import logging
from ops.charm import CharmBase
from ops.framework import StoredState
from ops.main import main
from ops.model import ActiveStatus
from charms.service_discovery_operator.... |
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _
from . import managers
class CustomUser(AbstractUser):
username = models.CharField(
max_length=150, help_text=_("The username of the user."), unique=True
)
email... |
from reml import __version__
def test_version():
assert __version__ == "0.1.0" |
# Generated by Django 4.0 on 2022-01-25 21:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0006_ticketimage_external_url_alter_warehousereply_files'),
]
operations = [
migrations.RemoveField(
model_name='warehouse... |
class ProgressBarStyle(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies the style that a System.Windows.Forms.ProgressBar uses to indicate the progress of an operation.
enum ProgressBarStyle,values: Blocks (0),Continuous (1),Marquee (2)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.