text stringlengths 2 999k |
|---|
import json
import os
from django.conf import settings
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.core.files.uploadedfile import SimpleUploadedFile
from nose.tools import eq_
from kitsune.questions.tests import QuestionFactory
from kitsune... |
# source code
import random, os, time, sys, msvcrt
# main code
def main():
# main screen 1
os.system('mode con: cols=60 lines=25')
os.system('color 1f')
print('\n'*10)
print('T I C T A C T O E'.center(60))
time.sleep(2)
# main screen 2
os.system('cls')
os.system('color 3f')
... |
# pylint: disable=missing-docstring
import getpass
import os
from celery.schedules import crontab
from readthedocs.core.settings import Settings
try:
import readthedocsext # noqa
ext = True
except ImportError:
ext = False
_ = gettext = lambda s: s
class CommunityBaseSettings(Settings):
"""Com... |
from rasa_nlu_examples.common import NotInstalled
try:
from .fasttext_featurizer import FastTextFeaturizer
except ImportError:
FastTextFeaturizer = NotInstalled("fasttext", "fasttext")
from .bpemb_featurizer import BytePairFeaturizer
from .gensim_featurizer import GensimFeaturizer
__all__ = ["BytePairFeatu... |
from datetime import timedelta
from django.utils.timezone import now
from telegram import ParseMode, Update
from telegram.ext import CallbackContext
from . import static_text
from tgbot.models import User
from bookmarks.models import Bookmark
import re
URL_REGEX = r"[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\... |
import requests
from proxypool.setting import TEST_URL
PROXY_POOL_URL = 'http://localhost:5555/random'
def get_proxy():
try:
response = requests.get(PROXY_POOL_URL)
if response.status_code == 200:
return response.text
except ConnectionError:
return None
proxy = get_proxy(... |
# -*- coding: utf-8 -*-
#==========================================
# Title: probability.py
# Author: Binxin Ru and Ahsan Alvi
# Date: 20 August 2019
# Link: https://arxiv.org/abs/1906.08878
#==========================================
"""
Created based on
https://jeremykun.com/2013/11/08/adversarial-bandits-and-t... |
# Imports
import torch
from itertools import count
from torch.autograd import Variable
import numpy as np
from utils import *
USE_CUDA = torch.cuda.is_available()
dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor
def deep_Q_learning(env, architecture, optimizer_spec,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'walker_lee'
from config import APP_MODE
def is_dev_mode():
"""是否开发环境"""
if APP_MODE == 'DEV':
return True
return False
def filter_same_element(to_filter_list):
return list(set(to_filter_list))
|
from __future__ import print_function
from __future__ import absolute_import
import gym
import gym.envs
import gym.spaces
from gym.monitoring import monitor
import os
import os.path as osp
from rllab.envs.base import Env, Step
from rllab.core.serializable import Serializable
from rllab.spaces.box import Box
from rllab... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from modules import ImageDownloader
import configparser
config_ini = configparser.ConfigParser()
config_ini.read('config.ini', encoding='utf-8')
Keys = {
"API_KEY" : config_ini.get('Env','API_KEY'),
"API_SECRET" : config_ini.get('Env','A... |
from setuptools import setup, find_packages
setup(
name="aws-keLP",
version="0.0.3",
author="LamarrD",
author_email="henry.773@osu.edu",
description="Serverless IAM least privilege automation",
entry_points={
"console_scripts": ["kelp=kelp.__init__:main"],
},
include_package_dat... |
from itertools import chain, combinations
from typing import Iterable, List
def powerset(iterable: Iterable[str]) -> List[List[str]]:
s = list(iterable)
return list(
map(
lambda x: list(x),
chain.from_iterable(list(combinations(s, r)) for r in range(len(s) + 1)),
)
... |
import pytest
import ptf.packet as scapy
import ptf.testutils as testutils
from ptf.mask import Mask
from collections import defaultdict
import time
import json
import itertools
import logging
from tests.common.errors import RunAnsibleModuleFail
from tests.common.fixtures.ptfhost_utils import copy_arp_responder_py ... |
from extract import Extract |
# -*- mode: python; coding: utf-8 -*
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""Tests for uvcal object.
"""
from __future__ import absolute_import, division, print_function
import nose.tools as nt
import os
import numpy as np
import copy
from pyuvdata import UVC... |
from collections.abc import Mapping
from fipy import PhysicalField
from fipy.tools import numerix as np
from .base import ModelData
class SnapshotModelData(ModelData):
"""
Class that encapsulates the model data stored in snapshot :class:`dict`
"""
def check_store(self, obj):
return i... |
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from django.contrib import admin
from website.views import *
from django.conf.urls.static import static
from django.views import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf impo... |
# Copyright 2015 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 zulip
import re
from datetime import datetime
from repeater import Repeater
from enum import Enum
from ctf_type import *
from notion_sync import *
client = zulip.Client(config_file="./zuliprc")
with open("token_v2", "r") as f:
token_v2 = str(f.read()).strip()
ctfs = {}
def get_ctf(name):
global ctfs
tmp = ... |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Indictrans and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('Industry')
class TestIndustry(unittest.TestCase):
pass
|
# Copyright 2016 PerfKitBenchmarker 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 appli... |
import json
import logging
import random
import uuid
from typing import Dict
from great_expectations.data_context.store import (
ConfigurationStore,
GeCloudStoreBackend,
)
from great_expectations.data_context.types.base import CheckpointConfig
from great_expectations.data_context.types.resource_identifiers imp... |
"""
Class Coverage
==============
.. autosummary::
:toctree: generated/
Coverage.creategrid
Coverage.cover
Coverage.sinr
Coverage.best
Coverage.show
"""
from pylayers.util.project import *
#from pylayers.measures.mesuwb import *
from pylayers.simul.radionode import *
import pylayers.util.pyu... |
import Processor
import numpy as np
import cPickle as pickle
from nltk.corpus import stopwords
from sklearn.cross_validation import KFold
from sklearn.feature_extraction.text import TfidfVectorizer as Tfidf
from sklearn.metrics import precision_recall_fscore_support as prfs
from sklearn.preprocessing import scale
from ... |
"""STIX 2.0 Cyber Observable Objects.
Embedded observable object types, such as Email MIME Component, which is
embedded in Email Message objects, inherit from ``_STIXBase20`` instead of
_Observable and do not have a ``_type`` attribute.
"""
from collections import OrderedDict
import itertools
from ..custom import _c... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v6/errors/date_error.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection ... |
from population import *
from individual import *
import math
def crossoverSinglePoint(a, b):
cut = math.floor(np.random.rand()*PROBLEM_SIZE)
offspring = Individual(PROBLEM_SIZE, MAX_GRADE)
offspring.chromosome = np.concatenate((a.chromosome[:cut], b.chromosome[cut:]))
return offspring
def crossoverU... |
from settings import *
def setup(bot):
bot.add_cog(PiCam(bot))
class PiCam(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.logging_channel = db["BOT_LOG_CHANNEL"]
self.rotation = 180
self.auto_upload = True
self.path = os.path.join(os.path.dir... |
print("Mary had a little lamb.")
print("Its fleece was white as {}.".format('snow'))
print("And everywhere that Mary went.")
print("." * 10)
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
print(end1 + end2 + end3 + end4 + end5 + ... |
import sys
sys.path += ["../"]
import pandas as pd
#from transformers import glue_compute_metrics as compute_metrics, glue_output_modes as output_modes, glue_processors as processors
from transformers import glue_output_modes as output_modes, glue_processors as processors
from transformers import (
AdamW,
Rober... |
#!/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', 'django_dynamodb_cache_example.settings')
try:
from django.core.management import execute_from_comman... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the XFS attribute."""
import unittest
from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver import context
from dfvfs.vfs import xfs_attribute
from dfvfs.vfs import xfs_file_syst... |
'''
hint:
the lowest is irrelevent to th others
'''
class Solution:
def reconstructQueue(self, people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
# sort the list by from heighest to lowest
# if with the same height, the one with the smaller index... |
# coding: utf-8
import json
import nuwe_pyeccodes
import numpy as np
from scipy.interpolate import RegularGridInterpolator
from PIL import Image
from porter.grib_tool.base.grib_tool import GribTool
from porter.grib_tool.base.regular_lonlat_grid import RegularLonLatGrid
class GribToImageConverter(GribTool):
def... |
GUILDS = """CREATE TABLE IF NOT EXISTS guilds (
id NUMERIC PRIMARY KEY
)"""
COUNTING_CHANNELS = """CREATE TABLE IF NOT EXISTS counting_channels (
id NUMERIC PRIMARY KEY,
current BIGINT DEFAULT 0,
last NUMERIC NOT NULL,
guild_id NUMERIC NOT NULL,
FOREIGN KEY (guild_id) REFERENCES guilds (id)
... |
"""Tests for the categorical random variable."""
import string
import numpy as np
import pytest
from probnum import randvars, utils
NDIM = 5
all_supports = pytest.mark.parametrize(
"support",
[
None,
np.arange(NDIM),
np.array(list(string.ascii_lowercase)[:NDIM]),
np.random.... |
import sys
import math
positions = [int(x) for x in sys.stdin.readline().strip().split(",")]
mean = sum(positions) / len(positions)
mUpper = math.ceil(mean)
mLower = math.floor(mean)
cost = {mUpper: 0, mLower: 0}
for pos in positions:
for m in [mUpper, mLower]:
diff = abs(pos - m)
cost[m] += (dif... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
def readData(path):
with open(path) as data:
yield from map(str.strip, data)
def timeIt(func):
def timed(*args, **kwargs):
from time import time
st = time()
result = func(*args, **kwargs)
print("%s took %0.2fs" % (func.__name__, round(time() - st, 2)))
return r... |
import sys
from pathlib import Path
import click
from beet.util.service_groups import all_groups, services_for_groups
async def async_stop(root_path: Path, group: str, stop_daemon: bool) -> int:
from beet.daemon.client import connect_to_daemon_and_validate
daemon = await connect_to_daemon_and_validate(root... |
from typing import Optional, Union
from aioworkers.core.base import (
AbstractConnector,
AbstractNestedEntity,
LoggingEntity,
)
from aioworkers.core.config import ValueExtractor
from aioworkers.core.formatter import FormattedEntity
from redis.asyncio import Redis
DEFAULT_HOST = 'localhost'
DEFAULT_PORT =... |
'''
>>> from bienstman5_ext import *
>>> m = M(1j)
'''
def run(args = None):
import sys
import doctest
if args is not None:
sys.argv = args
return doctest.testmod(sys.modules.get(__name__))
if __name__ == '__main__':
print "running..."
import sys
sys.exit(run()[0... |
from urllib.request import urlopen
from urllib.parse import urlparse
import re
import sys
LINK_REGEX = re.compile("<a [^>]*href=['\"]([^'\"]+)['\"][^>]*>")
class LinkCollector:
def __init__(self, url):
self.url = "http://+" + urlparse(url).netloc
self.collected_links = set()
self.visited_... |
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
INCLUDES = """
#include <string.h>
"""
TYPES = """
typedef struct {
char *password;
int length;
int called;
int error;
... |
# -*- coding: utf-8 -*-
import os
class Util:
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
reverse = dict((value, key) for key, value in enums.items())
enums['reverse_mapping'] = reverse
return type('Enum', (), enums)
def file... |
from django.contrib import admin
from .models import Cat, Dog
class DogAdmin(admin.ModelAdmin):
list_display = ('id', 'name', 'birthday')
fields = ('name', 'birthday')
ordering = ('name', 'birthday')
list_editable = ('name', 'birthday')
search_fields = ('name', 'birthday')
list_per_page = 20
... |
from collections import OrderedDict
import numpy as np
import pytest
import theano
import theano.tensor as tt
from tests import unittest_tools as utt
from theano.tensor.nnet import bn
def test_BNComposite():
try:
orig = theano.config.compute_test_value
theano.config.compute_test_value = "raise"... |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/cefiro_customizations"
# docs_base_url = "https://[org_name].github.io/cefiro_customizations"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.br... |
from setuptools import setup
import pylint_report
setup(
name=pylint_report.__name__,
version=pylint_report.__version__,
description='Generates an html report summarizing the results of pylint.',
url='https://github.com/drdv/pylint-report',
author='Dimitar Dimitrov',
author_email='mail.mitko@gm... |
from __future__ import absolute_import
from __future__ import print_function
from .utils import (
check_connection,
get_arg_parser,
get_config_from_args,
get_db_list,
get_membership,
get_shard_allocation,
indent,
)
from six.moves import map
def print_shard_table(shard_allocation_docs):
... |
from django.http import HttpResponse
def index(request):
return HttpResponse("<body background=\"https://png.pngtree.com/element_pic/16/05/24/0057432e09b9f62.jpg\"><h2 style=\"background-color:Cyan;\"><center>Welcome to Django & Python First page</center></h2></body></html>")
|
import logging
from colorama import Fore
from TwitchChannelPointsMiner import TwitchChannelPointsMiner
from TwitchChannelPointsMiner.logger import LoggerSettings, ColorPalette
from TwitchChannelPointsMiner.classes.Telegram import Telegram
from TwitchChannelPointsMiner.classes.Settings import Priority, Events, Followers... |
# Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and
# Technical University of Darmstadt.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source ... |
import pytest
from flashgeotext.lookup import load_data_from_file
from flashgeotext.lookup import LookupData
from flashgeotext.lookup import LookupDataPool
from flashgeotext.lookup import LookupDuplicateError
from flashgeotext.settings import DEMODATA_CITIES
from flashgeotext.settings import SCRIPTS
def test_lookup_... |
# Copyright (C) 21/10/19 RW Bunney
# 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 3 of the License, or
# (at your option) any later version.
# This program is distributed in th... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
"""
Django settings for mwradio project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
#... |
# Copyright (c) 2021 Qianyun, Inc. All rights reserved.
from cloudify import ctx
from abstract_plugin.platforms.common.network import CommonNetwork
from .base import Base
from cloudify.exceptions import NonRecoverableError
class Network(Base, CommonNetwork):
def __init__(self):
super(Network, self).__ini... |
__author__ = 'Rafa Haro <rh@athento.com>'
__all__ = ['parser']
|
from discord.ext import commands
import os
class Dev(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=['rld','rl'])
@commands.is_owner()
async def reload(self, ctx, extension):
"""`reload <extension>` reloads a loaded extension"""
try:... |
#!/usr/bin/env python3
import pytest
from aiospamc.connections import ConnectionManager
def test_instantiates():
conn_man = ConnectionManager()
assert 'conn_man' in locals()
def test_new_connection_not_implemented():
conn_man = ConnectionManager()
with pytest.raises(NotImplementedError):
... |
"""
WSGI config for UniNeuroLab project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_S... |
# coding: utf-8
"""
OpsGenie REST API
OpsGenie OpenAPI Specification # noqa: E501
OpenAPI spec version: 2.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from opsgenie_swagger.models.recipient import Recipient # noqa... |
import asyncio
from aiokafka import AIOKafkaProducer
from common.kafka.producer import send as kafka_send
from common.logging import logger
from source.checks import Check
from source.client import HttpClientLike
async def schedule(client: HttpClientLike, kafka_config: dict, kafka_p: AIOKafkaProducer, check: Check,... |
"""
This module contains the `Mesh` class.
"""
from __future__ import absolute_import
from pyaedt.generic.general_methods import aedt_exception_handler, generate_unique_name, MethodNotSupportedError
from pyaedt.generic.DataHandlers import _dict2arg
from collections import OrderedDict
meshers = {
"HFSS": "MeshSet... |
# coding=utf8
#
# (c) Simon Marlow 2002
#
import io
import shutil
import os
import re
import traceback
import time
import datetime
import copy
import glob
import sys
from math import ceil, trunc
from pathlib import Path, PurePath
import collections
import subprocess
from testglobals import config, ghc_env, default_te... |
"""
Data Generator
"""
import os
import numpy as np
import cv2
from tensorflow.keras.utils import Sequence
def parse_image(img_path, image_size):
image_rgb = cv2.imread(img_path, 1)
h, w, _ = image_rgb.shape
if (h == image_size) and (w == image_size):
pass
else:
image_rgb = cv2.resize(i... |
#----------------------------------------------------------------------
# This file was generated by encode-bitmaps.py
#
from wx.lib.embeddedimage import PyEmbeddedImage
Exit = PyEmbeddedImage(
b'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0'
b'RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VS... |
"""
This file offers the methods to automatically retrieve the graph Streptomyces bikiniensis.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--prote... |
from cereal import car
from selfdrive.car import apply_std_steer_torque_limits
from selfdrive.car.hyundai.hyundaican import create_lkas11, create_clu11, create_lfa_mfa
from selfdrive.car.hyundai.values import Buttons, SteerLimitParams, CAR
from opendbc.can.packer import CANPacker
VisualAlert = car.CarControl.HUDContro... |
# Copyright 2019 IBM Corporation
#
# 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, ... |
#!/usr/bin/env python
"""The blob store abstraction."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import abc
from future.utils import with_metaclass
from typing import Dict, Iterable, List, Optional
from grr_response_core.lib.util import precondit... |
import random
from django.http import Http404
from django.shortcuts import get_object_or_404
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.views import APIView
from ..pagination import ProductListResultsSetPagination
from ..serializer import ProductSerializer, Pr... |
#!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... |
import operator
import pickle
import shelve
import tempfile
import unittest
from time import sleep
from typing import Any
import cloudpickle
import fungraph
from tests.utils import timeonce
def _slow_identity(x: Any, waitseconds: float = 1) -> Any:
sleep(waitseconds)
return x
def _add_xy(x: int, y: int):
... |
import cv2
import numpy as np
def imnormalize(img, mean, std, to_rgb=True):
"""Normalize an image with mean and std.
Args:
img (ndarray): Image to be normalized.
mean (ndarray): The mean to be used for normalize.
std (ndarray): The std to be used for normalize.
to_rgb (bool): ... |
# Generated by Django 3.2.6 on 2021-08-26 16:31
from django.db import migrations, models
import tagulous.models.models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='MoveList',
fields... |
'''
@description 2019/9/29 22:03
'''
# id函数:返回对象在内存中存储的标识值。
# 1.定义类必须使用class关键字,然后继承自object类
# 2.在类中定义方法,第一个参数必须是self,self代表的是当前这个对象
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
print('*'*30)
print(id(self))
print('*'*30)
d... |
# BridgeDB by Nick Mathewson.
# Copyright (c) 2007-2012, The Tor Project, Inc.
# See LICENSE for licensing information
from ipaddr import IPv6Address, IPv4Address
import logging
funcs = {}
def filterAssignBridgesToRing(hmac, numRings, assignedRing):
#XXX: ruleset should have a key unique to this function
# ... |
__version__ = '0.2.7.dev'
|
"""
=================================================================
Permutation t-test on source data with spatio-temporal clustering
=================================================================
This example tests if the evoked response is significantly different between
two conditions across subjects. Here jus... |
from django.contrib import admin
from .models import Credential, Spreadsheet, SpreadsheetField
admin.site.register(Credential)
admin.site.register(Spreadsheet)
admin.site.register(SpreadsheetField)
|
import pytest
from saleor.product.models import (
AttributeChoiceValue, Product, ProductAttribute)
from saleor.product.utils.attributes import (
generate_name_from_values, get_attributes_display_map,
get_name_from_attributes)
@pytest.fixture()
def product_with_no_attributes(product_type, default_category... |
import ast, re, sys, os, json
from collections import defaultdict
# I used this program to generate spirv.json, this is a throwaway program
# here so it might not be up-to-date at all times.
# This program retrieves SPIR-V tables from glslang -project and translates
# them to JSON. It does so using some regular expre... |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... |
import types
import random
import time
from toontown.catalog import CatalogItem, CatalogItemList
from toontown.catalog.CatalogFurnitureItem import CatalogFurnitureItem, nextAvailableCloset, getAllClosets, get50ItemCloset, getMaxClosets, get50ItemTrunk, nextAvailableBank
from toontown.catalog.CatalogAnimatedFurnitureIte... |
import re
import shlex
import asyncio
import warnings
from datetime import datetime
from functools import partial, update_wrapper
from typing import (Tuple, Union, Callable, Iterable, Any, Optional, List, Dict,
Awaitable, Pattern, Type)
from aiocqhttp import Event as CQEvent
from aiocqhttp.message ... |
# 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)
# ----------------------------------------------------------------------------
# If you submit this package back to Spack ... |
# maze example
import collections
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import sys
from collections import defaultdict
import random
import math
import torch
from statistics import mean
import torch.nn.functional as F
class GridWorld:
""" Grid World environment
there... |
"""retrieverdash URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
"""
# Django imports
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
# Examples:
# url(r'^blo... |
#!/bin/python3
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
# Write Your Code Here
number_of_swaps = 0
while True:
for i in range(n - 1):
if a[i + 1] < a[i]:
a[i + 1], a[i] = a[i], a[i + 1]
number_of_swaps += 1
break
else:
break
pri... |
import cv2
import numpy as np
import png
import os
import pydicom
def get_png_filename(row):
""" 'D1-0000_L_A-R_mass_malignant|triple negative.png'
"""
fname = get_filename(row)
fname += ".png" # if not row['PatientName'] in PIDS_TO_CHECK else '-wrong.png'
return fname
def get_filename(row):
... |
def findNegativeCycles(times, i, j, cost, visited):
if (cost + times[j][i]) < 0:
print "Cycle", visited
return True
bunnies = len(times)
for k in range(bunnies):
if (k != j):
if k not in visited:
cost += times[j][k]
visited.append(... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""An example functional test
The module-level docstring should include a high-level description of
what the t... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
from selenium.common.except... |
import pytest
from .....webhook.event_types import WebhookEventAsyncType
from .....webhook.models import Webhook
@pytest.fixture
def subscription_webhook(webhook_app):
def fun(query, event_type, name="Subscription"):
webhook = Webhook.objects.create(
name=name,
app=webhook_app,
... |
_base_ = [
'./_base_/models/cascade_mask_rcnn_r50_fpn_word.py',
'./_base_/datasets/word_bbox_instance.py',
'./_base_/schedules/schedule_1x.py', './_base_/default_runtime.py'
]
model = dict(
backbone=dict(
type='DetectoRS_ResNet',
conv_cfg=dict(type='ConvAWS'),
sac=dict(type='SAC... |
# Generated by Django 3.1.7 on 2021-03-02 08:53
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('backoffice', '0014_auto_20210301_1748'),
]
operations = [
migrations.RemoveField(
model_name='p... |
"""
WSGI config for django_check_constraint project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.