text stringlengths 2 999k |
|---|
"""
WSGI config for proyectointegrador1 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/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('... |
from api.db import PostgresPoolWrapper, update_course_sections
import os
import sys
from api.parser.sis import SIS
from api.parser.registrar import Registrar
if len(sys.argv) == 1:
print("Pass semester ids to import as command line arguments")
exit(1)
postgres_pool = PostgresPoolWrapper(
postgres_dsn=os.e... |
class Seed(object):
pass
|
import torch
from torchvision.models.segmentation import fcn_resnet50
from torchvision.utils import draw_segmentation_masks
from PIL import Image
import io
from torchvision.transforms import transforms
from torchvision.utils import save_image
import torchvision.transforms.functional as F
def get_model():
model = f... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
"""
This module defines the classe to handle handle close
encounters between particles.
It is used by the multiples module.
"""
from amuse.datamodel import Particle
from amuse.datamodel import Particles
from amuse.datamodel import ParticlesSuperset
from amuse.datamodel import trees
from amuse.units import constants
... |
"""
ESPNet for image segmentation, implemented in PyTorch.
Original paper: 'ESPNet: Efficient Spatial Pyramid of Dilated Convolutions for Semantic Segmentation,'
https://arxiv.org/abs/1803.06815.
"""
__all__ = ['ESPNet', 'espnet_cityscapes']
import os
import torch
import torch.nn as nn
from common import ... |
from django.contrib import admin
from django.db import models
from pagedown.widgets import AdminPagedownWidget
from .models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'pub_date')
list_filter = ['pub_date']
formfield_overrides = {
models.TextField: {
... |
# Copyright (c) 2015-2020 Vector 35 Inc
#
# 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, ... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
import os
import json
import cv2
import copy
from tqdm import tqdm
from torch.utils.data import Dataset
class JsonDataset(Dataset):
def __init__(self, cfg):
assert cfg.img_mode in ['RGB', 'BGR', 'GRAY']
self.ignore_tags = cfg.ignore_tags
self.data_list = self
def load_data(self, pat... |
#!/usr/bin/env python
import os, sys, subprocess
import platform
from clckwrkbdgr import xdg, fs
import clckwrkbdgr.jobsequence.context
context = clckwrkbdgr.jobsequence.context.init(
working_dir=xdg.XDG_CONFIG_HOME/'lib',
)
lock = fs.CrossHostFSMutex(xdg.save_state_path('dailyupdate')/'dotfiles_lib_unittest.lock'... |
from __future__ import annotations
import dataclasses
import inspect
import re
import typing
import warnings
from loguru import logger
from vkquick.chatbot.base.cutter import (
CommandTextArgument,
InvalidArgumentConfig,
)
from vkquick.chatbot.base.filter import BaseFilter
from vkquick.chatbot.base.handler_c... |
from flask import Flask, request, jsonify, json
from datetime
from flask_jwt_extended import (create_access_token, create_refresh_token, jwt_required, get_jwt_identity, get_jwt,
set_access_cookies, unset_jwt_cookies)
from flask_jwt_extended import JWTManager
app = Flask(__name__)
app.config['SECRET_KEY'] = ... |
# Copyright 2020, Digi International Inc.
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIM... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 16:47:21 2020
@author: liudm
"""
from time import sleep
import plot_TT
from TimeTagger import createTimeTagger, freeAllTimeTagger, HistogramLogBins
# create a Time Tagger instance
tagger = createTimeTagger()
tagger.reset()
# measure FCS by start... |
# Author: Robin Ru @ University of Oxford
# This is an implementation of zero-cost estimators based on:
# https://github.com/BayesWatch/nas-without-training (Jacov)
# and https://github.com/gahaalt/SNIP-pruning (SNIP)
import numpy as np
import torch
import logging
import gc
from naslib.predictors.predictor import Pre... |
Very Short Questions and Answers
#33. Explain how if else works along with an example.
# Find out if a number is even and odd using if and else.
num = int(input("Enter a number"))
if num % 2 == 0:
print( str(num) + " is an Even number")
else:
print( str(num) + " is an Odd number")
#35. Exp... |
import abc, json, re
from .yaml_parser import SimpleRegex, NestedRegex, ParamsRegex, Dictionary, List
class CodeWriter:
def __init__(self, name):
self.name = name
@abc.abstractmethod
def write(self):
pass
class DefaultWriter(CodeWriter):
def __init__(self, name, definition... |
from flask import Flask, jsonify, request
import boto3
from openapi_core import create_spec
from openapi_core.contrib.flask.decorators import FlaskOpenAPIViewDecorator
import yaml
with open('example.yaml') as infile:
spec_dict = yaml.load(infile.read())
spec = create_spec(spec_dict)
openapi = FlaskOpenAPIVie... |
# Copyright 2020-2021 Canonical 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 in writi... |
from setuptools import setup
setup(name='quickPdf',
version='0.1',
description='',
author='Guilherme Silva',
license='MIT',
packages=['minuteToPdf'],
install_requires=[
'graphviz',
'requests',
'pypandoc'
],
scripts=["scripts/quickPdf"]) |
################################################################################
# * The contents of this file are Teradata Public Content and have been released
# * to the Public Domain.
# * Please see license.txt file in the package for more information.
# * Alexander Kolovos and Tim Miller - May 2021 - v.2.0
# * Cop... |
import tensorflow as tf
@tf.function
def transform_targets_for_output(y_true, grid_size, anchor_idxs, classes):
# y_true: (N, boxes, (x1, y1, x2, y2, class, best_anchor))
N = tf.shape(y_true)[0]
# y_true_out: (N, grid, grid, anchors, [x, y, w, h, obj, class])
y_true_out = tf.zeros(
(N, grid_s... |
from .BaseShaper import BaseShaper
from fontFeatures.shaperLib.Buffer import BufferItem
import unicodedata
LBase = 0x1100
VBase = 0x1161
TBase = 0x11A7
LCount = 19
VCount = 21
TCount = 28
SBase = 0xAC00
NCount = (VCount * TCount)
SCount = (LCount * NCount)
def isCombiningL(u):
return LBase <= u <= LBase+LCount-1
... |
"""The module describes the ``cpuinfo`` job metrics plugin."""
import logging
from . import InstrumentPlugin
from .. import formatting
log = logging.getLogger(__name__)
class HostnameFormatter(formatting.JobMetricFormatter):
def format(self, key, value):
return key, value
class HostnamePlugin(Instrum... |
# coding: utf-8
import pprint
import re
import six
class KeystoneCreateUserOption:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from typing import Dict
from jina.executors.crafters import BaseDocCrafter
class TextExtractor(BaseDocCrafter):
def craft(self, text: str, *args, **kwargs) -> Dict:
*_, s = text.split('[SEP]')
r... |
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .costvolume_regularization import CostRegularization
from .feature_extraction import FeatureExtraction
from .icospherical_sweeping import IcoSphericalSweeping
class IcoSweepNet(nn.Module):
def __init__(self,... |
# BSD 3-Clause License
#
# Copyright (c) 2019, Elasticsearch BV
# 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, t... |
import os
from configparser import ConfigParser, NoSectionError, NoOptionError
import pydmrs
CONFIG_DIR = os.path.normpath(os.path.join(pydmrs.__file__, '../__config__'))
def get_config_option(config, section, option, opt_type=None, default=None):
"""
Safe read of config option that returns default va... |
from test_suit.test_utils import RetryableError, NonRetryableError
import json
class TestNativeStringJsonWithoutSchema:
def __init__(self, driver, nameSalt):
self.driver = driver
self.fileName = "travis_correct_native_string_json_without_schema"
self.topic = self.fileName + nameSalt
d... |
import context
import matplotlib.pyplot as plt
from modules.grid_search import grid_search
from modules.forecast_models import ModelConfig
from test_sequence import sale
# grid search
data = sale.to_numpy().flatten()
n_test = 7 # number of observation used for test
max_length = len(data) - n_test # max length used ... |
import logging
import os
from os import truncate
import pickle
from multiprocessing import Pool
from typing import Tuple
from tqdm.auto import tqdm
import pandas as pd
import torch
from tokenizers.implementations import ByteLevelBPETokenizer
from tokenizers.processors import BertProcessing
from torch.utils.data impor... |
###############################################################
# npytest -v --capture=no tests/test_strdb..py::Test_strdb.test_001
# pytest -v --capture=no tests/test_strdb.py
# pytest -v tests/test_strdb.py
###############################################################
import os
import pytest
from tempfile import... |
import collections
import logging
import os
import re
from sys import getsizeof
from threading import Event, RLock
from typing import Any, Callable, Dict, Hashable, Tuple, TypeVar, Union
import numpy as np
from cachetools import Cache
from humanize import naturalsize
CachedItemType = TypeVar("CachedItemType")
logger... |
"""new dbs added
Revision ID: 3a3be47e06c5
Revises: 31b11ad806a9
Create Date: 2020-05-09 13:09:01.516942
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '3a3be47e06c5'
down_revision = '31b11ad806a9'
branch_labels = None
depends_on = None
def upgrade():
# ... |
#!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://ge... |
"""Config flow for integration."""
import logging
import voluptuous as vol
from homeassistant import config_entries, core
from homeassistant.const import CONF_TIMEOUT
from .const import DOMAIN, CONF_TTY # pylint:disable=unused-import; pylint:disable=unused-import
LOG = logging.getLogger(__name__)
DATA_SCHEMA = vo... |
from security import authenticate
from flask import Flask, request
from flask_restful import Resource, Api
from flask_jwt import JWT, jwt_required
from security import authenticate, identity
app = Flask(__name__)
app.secret_key = 'rowa'
api = Api(app)
jwt=JWT(app, authenticate, identity)
items= [] #dict of items
... |
from Server import Server
def main():
server = Server('Cartographic.pdf', bytes('abcdefghijklmnop', 'utf-8'))
server.start_server()
if __name__ == '__main__':
main()
|
from rest_framework import status
from django.test import TestCase, Client
from rest_framework.test import APIClient
from django.urls import reverse
from app.serializers import ContentSerializer, BookSerializer, ContentShallowSerializer, BookDeepSerializer
from app.models import *
from creators.models import *
client =... |
import autoarray as aa
import numpy as np
class TestVoronoiMagnification:
def test__number_of_pixels_setup_correct(self):
pixelization = aa.pix.VoronoiMagnification(shape=(3, 3))
assert pixelization.shape == (3, 3)
def test__sparse_grid_from__returns_same_as_computed_from_grids_m... |
import pytest
import json
import os
import demistomock as demisto
from CrowdStrikeFalconIntel_v2 import *
from CommonServerPython import DBotScoreType, Common, DemistoException
with open(os.path.normpath(os.path.join(__file__, '..', './test_data/indicator_resource.json'))) as f:
INDICATOR_RESOURCE = json.load(f)
... |
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from django.urls import reverse
class AdminSiteTests(TestCase):
def setUp(self):
self.client = Client()
self.admin_user = get_user_model().objects.create_superuser(
email='super@mail.com',
... |
# app/accounts/signals.py
# Django modules
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.contrib.auth.models import User
# Locals
from .models import Profile
# Step 4: Real live using Signals
# Create a new user --> a new user's profile will
# also be c... |
from statistics import mean, stdev
import time
import click
import torch
from torch_sparse import SparseTensor
import numpy as np
import scipy.sparse as sparse
import torch_sparse
import aggfuse_cpu
import aggfuse_gpu
from torch_geometric.data import Batch
from torch_geometric.datasets import (
Planetoid,
Red... |
# Generated by Django 3.0.5 on 2020-09-27 03:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('vehicle', '0005_mechanic_skill'),
]
operations = [
migrations.AlterField(
model_name='mechanic',
name='skill',
... |
"""
The calculate test module verifies that calculate() calculates
Model quantities correctly.
"""
import nose.tools
from pycalphad import Database, calculate
import numpy as np
try:
# Python 2
from StringIO import StringIO
except ImportError:
# Python 3
from io import StringIO
from pycalphad.tests.da... |
from linebot.models import *
def create_customer_template():
bubble = BubbleContainer(
direction='ltr',
body=BoxComponent(
layout='vertical',
contents=[
# title
TextComponent(text='信用卡優惠查詢', weight='bold', size='xl'),
# info
... |
# Copyright (c) Mathias Kaerlev 2012.
# This file is part of Anaconda.
# Anaconda 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.
# ... |
# Generated by Django 2.2.13 on 2020-06-29 15:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('membership', '0010_robot_and_regions'),
]
operations = [
migrations.AddField(
model_name='addresslink',
name='clien... |
import argparse
import binascii
import collections
import re
import sys
import webbrowser
import wcwidth
from .main import available_fonts_for_codepoint
from .preview_server import FontPreviewServer
__RE_GET_NAME__ = re.compile(r'"\.?([^"]+)"')
__RE_UNICODE_HEX__ = re.compile(r'^U\+[0-9a-fA-F]{4,6}$')
def parser_a... |
import ast
import pathlib
import re
import sys
CODE_ROOT = pathlib.Path(__file__).resolve().parent.parent
EXECUTION_MODULES_PATH = CODE_ROOT / "src" / "saltext" / "vcenter" / "modules"
def check_cli_examples(files):
"""
Check that every function on every execution module provides a CLI example
"""
er... |
import sys
import unittest
sys.path.append('../')
from broadband_api import *
from FRNConversionsAPI import *
from block_conversion_api import *
class TestBroadbandAPI (unittest.TestCase):
def setUp(self):
self.bb = BroadbandApi()
self.frnapi = FRNConversionsAPI()
#Sweep across the US and compare to ... |
# -*- coding: utf-8 -*-
import re
import logging
from ..utils.crawler import Crawler
from ..utils.cleaner import cleanup_text
logger = logging.getLogger(__name__)
search_url = 'https://allnovel.org/search?keyword=%s'
RE_VOLUME = r'(?:book|vol|volume) (\d+)'
class AllNovelCrawler(Crawler):
base_url = [
'... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Procedure to touch and copy softlinks
"""
import os
import os.path as op
import logging
import sys
from jcvi.apps.base import OptionParser, ActionDispatcher, get_abs_path
def main():
actions = (
('touch', 'touch all the symlinks'),
('cp', 'cp a... |
# from Preprocessor import Preprocessor |
import numpy as np
import cv2
import matplotlib.pyplot as plt
from math import pi
from skimage.color import rgb2gray
# functions
def load_image(filename):
image = cv2.imread(filename, 0)
print(image)
return image
def pipe_convert_normalize(image):
gray_image = rgb2gray(image)
normalized = cv2.n... |
import unittest
from bdflib import reader
import charset
class JISTest(unittest.TestCase):
def test_jis(self):
with open('bdf/jiskan24-2003-1.bdf', 'rb') as f:
bdf = reader.read_bdf(f)
cconv = charset.JIS()
single_cp = 0
multi_cp = 0
for cp in bdf.codepoints(... |
# wykys 2019
import numpy as np
from numpy import array, uint8
from bin_print import bin_print
FREQ_L = 2200
FREQ_H = 1200
SAMPLE_RATE = 9600
DATA_RATE = 1200
BIT_SIZE = SAMPLE_RATE/DATA_RATE
def find_data_bytes(s):
l_cnt = 0
h_cnt = 0
flag_frame_start = False
flag_change_from_l = False
flag_ch... |
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from product.models import *
from django.contrib import messages
from product.forms import ReviewForm
from django.views.generic.edit import FormMixin
from checkout.models import O... |
# https://www.postgresql.org/docs/current/datatype.html
# The following types (or spellings thereof) are specified by SQL:
# bigint, bit, bit varying, boolean, char, character varying, character, varchar,
# date, double precision, integer, interval, numeric, decimal, real, smallint,
# time (with or without time zone), ... |
"""
Function stubs for linear algebra functions (Extension).
NOTE: This file is generated automatically by the generate_stubs.py script. Do
not modify it directly.
See
https://github.com/data-apis/array-api/blob/master/spec/API_specification/linear_algebra_functions.md
"""
from __future__ import annotations
from ._... |
import torch
import random
def bce_loss(input, target):
"""
Numerically stable version of the binary cross-entropy loss function.
As per https://github.com/pytorch/pytorch/issues/751
See the TensorFlow docs for a derivation of this formula:
https://www.tensorflow.org/api_docs/python/tf/nn/sigmoid_... |
from unit.applications.proto import TestApplicationProto
class TestApplicationPerl(TestApplicationProto):
application_type = "perl"
def load(self, script, name='psgi.pl'):
script_path = self.current_dir + '/perl/' + script
self._load_conf(
{
"listeners": {"*:7080"... |
from __future__ import print_function
from byteblower.byteblowerll import byteblower
try:
instance = byteblower.ByteBlower.InstanceGet()
print("ByteBlower API version: " + instance.APIVersionGet())
except Exception as e:
print("Caught Exception: " + str(e))
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import math
import operator
from pycket import values
from pycket import vector as values_vector
from pycket.arity import Arity
from pycket.error import... |
""" run with
nosetests -v --nocapture test_cm.py
"""
from __future__ import print_function
from cloudmesh_base.util import HEADING
from cloudmesh_base.logger import LOGGER, LOGGING_ON, LOGGING_OFF
log = LOGGER(__file__)
import sys
import os
if os.path.isdir(os.path.expanduser("~/.cloudmesh")):
print("ERROR", ... |
# Copyright 2017 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,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 18 11:22:17 2021
@author: tobraun
"""
import numpy as np
import scipy.stats as stats
import scipy.optimize as opt
from .recurrence_plot import RP
class Boxcount(RP):
def __init__(self, x, boxes, glide = False, gridpos = 0, compute_rp = ... |
liste = [1, 2 , 5, 3, 6, 4]
print (sorted(liste))
print ("\n")
print (liste)
print("\n")
liste.sort()
print (liste)
print ("\n")
liste.reverse()
print (liste)
|
import pickle
from flask import Flask, request, jsonify, session
from flask_cors import CORS, cross_origin
import sklearn
from sklearn.decomposition import TruncatedSVD
import pandas as pd
import numpy as np
ranks = []
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
class Model:
... |
from selenium import selenium
import unittest, time, re
class ColumnResize(unittest.TestCase):
def setUp(self):
self.grid = "EditorsGrid"
self.state_host = "http://localhost/gitcui/samples/client/grid/asp/editors/index.html"
self.verificationErrors = []
self.selenium = selenium("loc... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
#!/usr/bin/python
#
# Test suite for Optik. Supplied by Johannes Gijsbers
# (taradino@softhome.net) -- translated from the original Optik
# test suite to this PyUnit-based version.
#
# $Id: test_optparse.py 63512 2008-05-20 21:35:26Z benjamin.peterson $
#
import sys
import os
import re
import copy
import unittest
f... |
# coding=utf-8
# Copyright 2022 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 ... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
# Source : https://leetcode.com/problems/simplify-path/
# Author : William Heryanto
# Date : 2021-02-05
###############################################################################
#
# Given a string `path`, which is an absolute path (starting with a slash
# `'/'`) to a file or directory in a Unix-style file syst... |
import tkinter as tk
import json
from plugin import Plugin
GREET_FONT = ('Helvetica', 80)
class Greeter(tk.Frame, Plugin):
"""Greeter module class.
Greeter class inherits from tkinter's Frame class and abstract
Plugin class. This modules displays greetings message when face is
detected and recogniz... |
from pymongo import MongoClient
import pymongo
from PIL import Image
import io
import base64
class myMongo(object):
conn = MongoClient(host='127.0.0.1',port=27017,username='admin',password='123456')
db = conn['gameInfo']
@classmethod
def get_state(cls):
return cls.conn is not None and cls.... |
import paddle.fluid as fluid
from paddle.fluid.param_attr import ParamAttr
from paddle.fluid.regularizer import L2Decay
from paddle.fluid.dygraph.nn import Conv2D, BatchNorm
from paddle.fluid.dygraph.base import to_variable
class ConvBNLayer(fluid.dygraph.Layer):
def __init__(self,
name_scope,
... |
#!/usr/bin/env python3
# Copyright (c) 2015-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.
"""Test transaction signing using the signrawtransaction* RPCs."""
from test_framework.address import che... |
import dataclasses
NEIGHBORS = ((-1, 0), (1, 0), (0, -1), (0, 1))
Board = list[list[str]]
@dataclasses.dataclass(frozen=True)
class Point:
x: int
y: int
def value(self, board: Board) -> str:
return board[self.y][self.x]
def set_value(self, board: Board, value: str) -> None:
board[s... |
#!/usr/bin/env python3
# Requires: https://github.com/LordGolias/sqf
import fnmatch
import os
import sys
import argparse
from sqf.parser import parse
import sqf.analyzer
from sqf.exceptions import SQFParserError
def analyze(filename, writer=sys.stdout):
warnings = 0
errors = 0
with open(filename, 'r') a... |
from numbers import Number
import torch
from torch.distributions import constraints
from torch.distributions.distribution import Distribution
from torch.distributions.utils import broadcast_all, probs_to_logits, logits_to_probs, lazy_property
from torch.nn.functional import binary_cross_entropy_with_logits
class Geo... |
# /usr/bin/env python3
import pathlib
from setuptools import setup, find_packages
# The directory containing this file
HERE = pathlib.Path(__file__).parent
# The text of the README file
README = (HERE / "README.md").read_text()
setup(
author="Savino Piccolomo",
author_email="piccolomo@gmail.com",
name='... |
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
import orjson
from django.db import connection
from django.db.models.query import Q, QuerySet
from sqlalchemy import Text
from sqlalchemy.sql import ColumnElement, column, func, literal
from zerver.lib.request import REQ
from zerver.mod... |
import torch
from torch import nn
from torchvision.ops import MultiScaleRoIAlign
from ._utils import overwrite_eps
from ..._internally_replaced_utils import load_state_dict_from_url
from .faster_rcnn import FasterRCNN
from .backbone_utils import resnet_fpn_backbone, _validate_trainable_layers
__all__ = [
"Keyp... |
import ir_datasets
from ir_datasets.util import DownloadConfig
from ir_datasets.formats import TrecQrels, TrecDocs, TrecQueries
from ir_datasets.datasets.base import Dataset, YamlDocumentation
NAME = 'trec-arabic'
QREL_DEFS = {
1: 'relevant',
0: 'not relevant',
}
QTYPE_MAP = {
'<num> *(Number:)? *AR': '... |
# Testing module instance_type.m5ad
import pytest
import ec2_compare.internal.instance_type.m5ad
def test_get_internal_data_instance_type_m5ad_get_instances_list():
assert len(ec2_compare.internal.instance_type.m5ad.get_instances_list()) > 0
def test_get_internal_data_instance_type_m5ad_get():
assert len(ec2_comp... |
from bs4 import BeautifulSoup
import pandas as pd
import requests
class OdessaNewsScrapper():
def __init__( self, first_page:int = 1, last_page:int = 2, link:str = "https://on.od.ua/category/news/2-odessa/page/", csv_file:str = "odessa_news.csv" ) -> None:
titles = []
dates =... |
import FWCore.ParameterSet.Config as cms
L1SubsystemKeysOnlineExt = cms.ESProducer("L1SubsystemKeysOnlineProdExt",
onlineAuthentication = cms.string('.'),
tscKey = cms.string('dummy'),
rsKey = cms.string('dummy'),
onlineDB = cms.string('oracle://CMS_OMDS_LB/CMS_TRG_R'),
forceGeneration = cms.bool(... |
import unittest
import pyrtl
from pyrtl import transform
class NetWireNumTestCases(unittest.TestCase):
def setUp(self):
pyrtl.reset_working_block()
def assert_num_net(self, num, block=None):
block = pyrtl.working_block(block)
self.assertEqual(len(block.logic), num)
def assert_num... |
import logging
import uuid
from datetime import datetime
import architect
from django.contrib.auth.models import AnonymousUser, User
from django.db import models
from django.utils.functional import cached_property
from dimagi.utils.web import get_ip
from corehq.apps.domain.utils import get_domain_from_url
from core... |
"""Support for Transport NSW (AU) to query next leave event."""
from datetime import timedelta
import logging
import voluptuous as vol
from TransportNSW import TransportNSW
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import ... |
from __future__ import print_function, division, absolute_import
import sys
import numpy as np
import ctypes
from numba import jit, numpy_support, types
from numba import unittest_support as unittest
from numba.compiler import compile_isolated
from numba.itanium_mangler import mangle_type
from numba.utils import IS_P... |
from flask import abort, url_for, session
from typing import List, Optional
from uuid import uuid4
class ArcadeSession:
def __init__(self):
self.id = uuid4().hex
self.url = url_for("arcade.arcade_give_prize", uuid=self.id)
class ArcadeAdapter:
"""
Adapts the shop checkout system to use a... |
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
from fontTools.misc.transform import Transform
import ufo2ft.util
from ufo2ft.filters import BaseFilter
class DecomposeComponentsFilter(BaseFilter):
def filter(self, glyph):
if not glyph.components:
return False
ufo2ft.util.deepCopyContours(self.context.glyphSet, glyph, glyph, Transfo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.