text stringlengths 1 927k |
|---|
# -*- coding: utf-8 -*-
#
# Copyright 2017-2021 AVSystem <avsystem@avsystem.com>
#
# 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 ... |
from Qt import QtCore, QtWidgets
class ComboItemDelegate(QtWidgets.QStyledItemDelegate):
"""
Helper styled delegate (mostly based on existing private Qt's
delegate used by the QtWidgets.QComboBox). Used to style the popup like a
list view (e.g windows style).
"""
def paint(self, painter, opti... |
import os
from unittest import mock
from unittest.mock import Mock, patch
from django.conf import settings
from django.core.management import call_command
from django.db.models import FileField
from django.test import TestCase, SimpleTestCase
from django_test_tools.file_utils import hash_file, temporary_file
from dja... |
import logging
import colorlog
LOG_LEVEL = logging.INFO
LOG_FORMAT = " %(log_color)s%(levelname)-8s%(reset)s | %(name)-7s | %(log_color)s%(message)s%(reset)s"
def setup_logging() -> None:
logging.root.setLevel(LOG_LEVEL)
formatter = colorlog.ColoredFormatter(LOG_FORMAT)
stream = logging.StreamHandler(... |
from django.contrib.auth import views as auth_views
from django.urls import include, path
from oauth2_provider.urls import management_urlpatterns
from auth_app import views
user_list = views.UsersViewSet.as_view({
'get': 'list'
})
user_detail = views.UsersViewSet.as_view({
'get': 'retrieve'
})
urlpatterns = ... |
# -*- coding: utf-8 -*-
#Copyright 2010, Meka Robotics
#All rights reserved.
#http://mekabot.com
#Redistribution and use in source and binary forms, with or without
#modification, are permitted.
#THIS SOFTWARE IS PROVIDED BY THE Copyright HOLDERS AND CONTRIBUTORS
#"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INC... |
"""
Form classes
"""
from django.core.exceptions import ValidationError
from django.utils.copycompat import deepcopy
from django.utils.datastructures import SortedDict
from django.utils.html import conditional_escape
from django.utils.encoding import StrAndUnicode, smart_unicode, force_unicode
from django.utils.safest... |
# Copyright 2019 AstroLab Software
# Author: Julien Peloton
#
# 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 applicabl... |
from datetime import datetime
from django.utils.timezone import make_aware
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from treeckle.common.constants import COMMENTS
from treeckle.common.excepti... |
"""
## CycleISP: Real Image Restoration Via Improved Data Synthesis
## Syed Waqas Zamir, Aditya Arora, Salman Khan, Munawar Hayat, Fahad Shahbaz Khan, Ming-Hsuan Yang, and Ling Shao
## CVPR 2020
## https://arxiv.org/abs/2003.07761
"""
from collections import OrderedDict
import torch
def load_checkpoint(model, weigh... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM 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 wr... |
# -*- coding: utf-8 -*-
'''
Set up the Salt integration test suite
'''
# Import Python libs
from __future__ import print_function
import os
import re
import sys
import time
import errno
import shutil
import pprint
import logging
import tempfile
import subprocess
import multiprocessing
from hashlib import md5
from dat... |
#!/usr/bin/env python
import os
import sys
import requests_futures
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
packages = [
'requests_futures',
]
requires = [
'requ... |
import hashlib as hl
import json
def hash_string_256(string):
return hl.sha256(string).hexdigest()
def hash_block(block):
hashable_block = block.__dict__.copy()
hashable_block['transactions'] = [tx.to_ordered_dict() for tx in hashable_block['transactions']]
return hash_string_256(json.dumps(hashable_b... |
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from typing import Any
OPTIONS: dict[str, Any] = {} |
from abc import ABC, abstractmethod
class Optimizer(ABC):
def __init__(self):
super().__init__()
@abstractmethod
def optimize(self, u_n):
pass |
import os, unittest
from binascii import hexlify
from pure25519_blake2b.basic import encodepoint
from pure25519_blake2b.dh import dh_start, dh_finish
class DH(unittest.TestCase):
def assertElementsEqual(self, e1, e2):
self.assertEqual(hexlify(encodepoint(e1)), hexlify(encodepoint(e2)))
def assertBytesE... |
# coding: utf-8
# Copyright (c) 2016, 2021, 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... |
"""
*nox*
Parameters for nox.
"""
import nox
from nox_poetry import Session
from nox_poetry import session
from pathlib import Path
from textwrap import dedent
import sys
import shutil
package = "{{cookiecutter.package_name}}"
python_versions = [
"3.9",
"3.8",
"3.7",
]
nox.needs_version = ">... |
#! /usr/bin/python
# coding: utf-8
# flake8: noqa
# This file is part of PyRemo. PyRemo is a toolbox to facilitate
# treatment and plotting of REMO or other rotated and non-rotated
# data.
#
# Copyright (C) 2010-2020 REMO Group
# See COPYING file for copying and redistribution conditions.
#
# This program is free softw... |
"""This module contains the GeneFlow Definition class."""
import copy
import pprint
import cerberus
import yaml
from geneflow.log import Log
GF_VERSION = 'v3.0'
WORKFLOW_SCHEMA = {
'v3.0': {
'gfVersion': {
'type': 'string', 'default': GF_VERSION, 'allowed': [GF_VERSION]
},
'... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
SECRET_KEY = 'this-really-needs-to-be-changed'
SQLALCHEMY_DATABASE_URI = 'postgresql://localhost/edbdev'
class ProductionConfig(Config):
DEBUG = False
class... |
from __future__ import division, print_function, absolute_import
from dipy.utils.six.moves import xrange
from dipy.testing import assert_true, assert_false
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_equal, assert_raises)
import numpy as np
from dipy.re... |
from edgeml.python.src.MLEXray.ML_Diff.MLLogReader import MLLogReader
from edgeml.python.src.MLEXray.ML_Diff.TopKAccuracy import get_log_path, TopKAccuracy
from edgeml.python.src.MLEXray.Utils.params import ModelName, ScalarLogKeys, VectorLogKeys
groundtruth_filepath = "data/0_data/imagenet2012/groundtruth_label.txt"
... |
import logging
import pypyodbc
import sys
from pandas import DataFrame, read_sql, concat
from IPython.core import magic_arguments
from IPython.core.magic import magics_class, Magics, line_magic, cell_magic
from dawetsql.widgets import SchemaExplorer
from . import utils
from cryptography.fernet import Fernet
@magics_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: Ampel-core/ampel/config/builder/DistConfigBuilder.py
# License: BSD-3-Clause
# Author: valery brinnel <firstname.lastname@gmail.com>
# Date: 09.10.2019
# Last Modified Date: 14.03.2021
# Last Modified By: va... |
from struct import pack, unpack
import hashlib
import sys
import traceback
from electrum_trc import constants
from electrum_trc import ecc
from electrum_trc.bitcoin import (TYPE_ADDRESS, int_to_hex, var_int,
b58_address_to_hash160,
hash160_to_b58_ad... |
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from .dfx import quant, quant_grad, quant_fb
__all__ = ['QLinear', 'QConv2d', 'QBatchNorm2d']
class QLinear(nn.Linear):
def __init__(self, in_features, out_features, bias=True, weight_copy=True):
super(QLin... |
from .lambda_utils import Utils
__all__ = ['Utils'] |
#!/bin/python3
"""
https://www.hackerrank.com/contests/w24/challenges/happy-ladybugs
"""
import sys
from itertools import groupby
Q = int(input().strip())
for a0 in range(Q):
n = int(input().strip())
b = list(input().strip())
result = []
uniq_b = set(b)
if '_' not in uniq_b:
for x, y in gro... |
from __future__ import annotations
import pathlib
import sys
from typing import TYPE_CHECKING
from installer.destinations import SchemeDictionaryDestination
from installer.exceptions import InvalidWheelSource
from installer.sources import WheelFile as _WheelFile
from pdm import termui
from pdm.exceptions import Unin... |
from Cryptodome.PublicKey import RSA
from django.core.management.base import BaseCommand
from oidc_provider.models import RSAKey
class Command(BaseCommand):
help = "Randomly generate a new RSA key for the OpenID server"
def handle(self, *args, **options):
try:
key = RSA.generate(2048)
... |
"""
Django settings for profiles_project project.
Generated by 'django-admin startproject' using Django 3.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
imp... |
import os
import logging
import importlib
import archinfo
from collections import defaultdict
from ...relocation import Relocation
ALL_RELOCATIONS = defaultdict(dict)
complaint_log = set()
path = os.path.dirname(os.path.abspath(__file__))
l = logging.getLogger('cle.backends.elf.relocation')
def load_relocations():
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from skimage.segmentation import slic
from skimage.feature import peak_local_max
from skimage.morphology import binary_closing
from jsk_recognition_utils.mask import descent_closing
def split_fore_background(depth_img, footprint=None):
if footprin... |
# -*- coding: utf-8 -*-
#
# michael a.g. aïvázis
# orthologue
# (c) 1998-2022 all rights reserved
#
from .length import meter, centimeter, inch, foot, mile
#
# definitions of common area units
# data taken from Appendix F of Halliday, Resnick, Walker, "Fundamentals of Physics",
# fourth edition, John Willey and... |
# 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.
# ---------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""
Copyright 2020 Giuliano Franca
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 agree... |
import torch
import numpy as np
import os
import cv2
from LapNet import LAPNet
from create_dataset import createDataset
from torch.nn import DataParallel
from collections import OrderedDict
from torch.nn.parameter import Parameter
import json
import base64
import numpy as np
from flask import Flask, request, Respons... |
"""
Copyright (c) 2017-2018 Intel 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 i... |
# pylint: disable=missing-docstring
from __future__ import annotations
import pytest
from beancount.query.query import run_query
from fava.core import FavaLedger
from fava.util import excel
def test_to_csv(example_ledger: FavaLedger) -> None:
types, rows = run_query(
example_ledger.all_entries,
... |
from __future__ import print_function
import sys
import os
import shutil
import inspect
from epydoc import docintrospecter
from epydoc.apidoc import RoutineDoc
def Op_to_RoutineDoc(op, routine_doc, module_name=None):
routine_doc.specialize_to(RoutineDoc)
#NB: this code is lifted from epydoc/docintrospecter... |
# -*- coding: utf-8 -*-
def predict(x):
print("?") |
"""
Copyright (c) 2018 Intel 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 wri... |
n1=int(input('primeira nota: '))
n2=int(input('segunda nota: '))
print('a Média é {}'.format(((n1+n2)/2))) |
import _plotly_utils.basevalidators
class CliponaxisValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(self, plotly_name="cliponaxis", parent_name="funnel", **kwargs):
super(CliponaxisValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import numpy as np
plt.title('Un primo plot con Python')
plt.xlabel('x')
plt.ylabel('y')
x = np.linspace(0.0, 5.0, 100)
y = x
plt.plot(x,y,label='y=x')
x, y = np.loadtxt('temp.dat', usecols=(0,2), delimiter=' ', unpack=True)
plt.plot(x,y, 'x',label='Loaded from fil... |
"""
Your task is to implement some basic functions to track live tweets and inspect their content
To complete this task and test it, you MUST have created a twitter account and you should now
your credentials: access_token, access_token_secret, consumer_key, consumer_secret
More info about the Twitter API at: https://... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 23 10:48:58 2019
@author: rocco
"""
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import pandas as pd
import os
"""
Definition function to plot psc, df is a pandas dataframe, i = 0 if Northern Emisphere, i = 1 if Southern Emisphere
title, classifier_type = [... |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
===========================
Many python developers think of registry keys as if they were python keys in a
dictionary which is not the case. The windows registry is broken down into the
following components:
Hives
-----
This is the top level of the registry. T... |
input = """
true.
w :- true.
w :- not w.
"""
output = """
{true, w}
""" |
import logging
from logging.handlers import RotatingFileHandler
import os
from flask import Flask, current_app
from flask_bootstrap import Bootstrap
from flask_babel import Babel
from flask_googlemaps import GoogleMaps
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from flask_migrate import Mig... |
import os
from celery import Celery
from config import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
# Create celery application
CELERY_APP = Celery('dynamic-containment')
# Load Celery config file
CELERY_APP.config_from_object('config.celery_config')
# Add all tasks
CELERY_APP.autodis... |
"""
This code is adapted from the image.py by Kiela et al. (2020) in https://github.com/facebookresearch/mmbt/blob/master/mmbt/models/image.py
and the equivalent Huggingface implementation: utils_mmimdb.py, which can be
found here: https://github.com/huggingface/transformers/blob/8ea412a86faa8e9edeeb6b5c46b08def06aa03e... |
from . import BaseSchema
class Schema(BaseSchema):
PROPERTIES = [('name', '', str, 'Tapis actor name'),
('description', '', str, 'Tapis actor name description'),
('alias', '', str, 'Tapis actor alias'),
('stateless', True, bool, 'Whether actor is stateless'),
... |
# -*- coding: utf-8 -*-
"""
*SUBGROUPS: Interface to special GSAS Bilbao SUBGROUPS & k-SUBGROUPSMAG web pages*
-------------------------------
Extraction of space subgroups for a given space group and a propagation vector
from the GSAS version of SUBGROUPS & k-SUBGROUPSMAG web page on the Bilbao Crystallographic serv... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
Smoke tests to check that basic Python API functionality works and generates an
IR string without errors. These tests are not meant to make detailed assertions
about the generated IR.
"""
from pyqir.generator import BasicQisBuilder, SimpleMo... |
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Jayesh Kariya <jayeshk@saltstack.com>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from salttesting import skipIf, TestCase
from salttesting.mock import (
NO_MOCK,
NO_MOCK_REASON,
MagicMock,
patch
)
fro... |
'''
FILENAME : nftk_modify_hosts_file.py
AUTHORS : Andres Andreu <andres [at] neurofuzzsecurity dot com>
MODIFIED BY : Andres Andreu
DATE : 07/11/2015
LAST UPDATE : 05/18/2016
modifies an /etc/hosts file and then has the ability to reset it
back to its original state
... |
"""
This module provides a set of colormaps specific for solar data.
"""
from __future__ import absolute_import
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from sunpy.cm import color_tables as ct
__all__ = ['get_cmap', 'show_colormaps']
sdoaia94 = ct.aia_color_table(94)
sdoaia131 =... |
"""
Collecting profiling data using ``nvprof``.
.. deprecated:: 1.0.0
We use CUPTI to collect GPU profiling data.
"""
from rlscope.profiler.rlscope_logging import logger
import re
import sys
import os
import csv
import textwrap
import pprint
from io import StringIO
import json
import codecs
from os.path import joi... |
import json
import Globals as g
class PirateMapMaker():
"""Object class for making levels for Wall from JSON files
Contains the keywords for parsing a level JSON into
a data structure representing the game state for the GUI.
"""
###Keys to access JSON data
#Background image for game
... |
import requests
import xmltodict
# TODO: Find out why this occasionally hangs
def request_json(url, **kwargs):
r = requests.get(url.format(**kwargs), timeout=5)
r.raise_for_status()
return r.json()
def request_xml(url, **kwargs):
r = requests.get(url.format(**kwargs), timeout=5)
r.raise_for_stat... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'Countdown.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObj... |
"""Tests for pickaxe.py using pytest."""
# pylint: disable=redefined-outer-name
# pylint: disable=protected-access
import hashlib
import os
import re
import subprocess
from filecmp import cmp
from pathlib import Path
import pymongo
import pytest
from pymongo.errors import ServerSelectionTimeoutError
from rdkit.Chem i... |
import numpy as np
"""
This module contains a variant of the Binary Matrix Decomposition (BMD) algorithm for clustering binary data
as presented in "A General Model for Clustering Binary Data" (Tao Li, 2005) and "On Clustering Binary Data"
(Tao Li & Shenghuo Zhu, 2005). This varient of the BMD algorithm is for data wh... |
from phd.utils.path_tools import LogTime
import numpy as np
log = LogTime(".")
paths = np.array(log.paths)
indx = paths.argsort()
count = 1
for t, p in zip(log.time[indx], paths[indx]):
if (count % 3 == 0):
print(p,t)
count+=1 |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import subprocess
f... |
import unittest
from thrift.transport.TTransport import TTransportException
from sql_assurance.connectors.connection import ConnectionPool
from sql_assurance.connectors.connection import ConnectionFactory
class TestConnectionFactory(unittest.TestCase):
def setUp(self):
self.connection_factory = Connectio... |
"""'pip wheel' tests"""
import os
from os.path import exists
import pytest
from pip.locations import write_delete_marker_file
from pip.status_codes import ERROR, PREVIOUS_BUILD_DIR_ERROR
from tests.lib import pyversion
def test_pip_wheel_fails_without_wheel(script, data):
"""
Test 'pip wheel' fails without w... |
import os
import numpy as np
import mxnet as mx
import fddb_symbol_finetune
from mxnet import optimizer as opt
from mxnet.optimizer import get_updater
import time
batchsize = 4000
start_epoch = 1
end_epoch = 201
num_cls = 10
channel_len = 64
feature_len = 3136 + 8 + num_cls * (num_cls + 1) + num_cls * channel_len
lab... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from typing import Union, Optional, Callable
import numpy as np
from PIL import Image
import matplotlib.cm
from eli5.base import Explanation
def format_as_image(expl, # type: Explanation
resampling_filter=Image.LANCZOS, # type: int
colormap=matp... |
import logging
from detectron2.data import get_detection_dataset_dicts, DatasetFromList, DatasetMapper, MapDataset, \
build_batch_data_loader
from detectron2.data.samplers import TrainingSampler, RepeatFactorTrainingSampler
def build_detection_train_loader(cfg, mapper=None):
"""
A data loader is created b... |
#!/usr/bin/env python
"""Co-add_chi2_values.py.
Create Table of minimum Chi_2 values and save to a table.
"""
import argparse
import warnings
import glob
import os
import sys
import numpy as np
import pandas as pd
import sqlalchemy as sa
import simulators
def parse_args(args):
"""Take care of all the argparse ... |
from __future__ import print_function
import subprocess
from distutils.command.build import build as distutils_build #pylint: disable=no-name-in-module
from setuptools import setup, find_packages, Command as SetupToolsCommand
VERSION = '0.1.dev0'
with open('requirements.txt', 'r') as f:
install_requires = f.readlin... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Dict, List, Optional, Set
import numpy as np
from pytext.common.constants import SpecialTokens, Token
from pytext.config.component import Component, ComponentType
from pytext.config.pytext_config import Con... |
# 表结构模板 |
import random
import functools
import asyncio
_SCENARIO = {}
def get_scenarios():
scenarios = list(_SCENARIO.items())
scenarios.sort()
return [scenario for (name, scenario) in scenarios]
def get_scenario(name):
return _SCENARIO.get(name)
def _check_coroutine(func):
if not asyncio.iscoroutine... |
import numpy as np
import matplotlib.pyplot as plt
import math
import lidar_to_grid_map as lg
from grid_mapping_for_a_star import OccupancyGridMap
from a_star_for_ogm_testing import a_star
f = "mesures.txt"
def read_measures(file):
measures = [line.split(",") for line in open(file)]
angles = []
distances ... |
import json
import os.path as osp
import matplotlib.pyplot as plt
from collections import OrderedDict
from collections import Counter
import numpy
import h5py
import os
"""
处理文本数据,提取出story,并构建词表
"""
base_path = "AREL-data-process/"
train_data = json.load(open(osp.join(base_path, "test.story-in-sequence.json")))
# tra... |
# Copyright The IETF Trust 2017, All Rights Reserved
from __future__ import unicode_literals
import datetime
import debug #pyflakes:ignore
from django import forms
from ietf.doc.fields import SearchableDocAliasesField, SearchableDocAliasField
from ietf.doc.models import RelatedDocument
from ietf.iesg.models import T... |
import os
import logging
import datetime
log_level = logging.DEBUG # Default message level
class UseridFilter(logging.Filter):
'''Default value for the user ID'''
def filter(self, record):
if not hasattr(record, 'userid'):
record.userid = 'Global'
return True
def setup_logger... |
import unittest
import utils
# O(n) time. O(n) space. Iteration.
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
if len(num1) < len(num2):
num1, num2 = num2, num1
result = []
carry = 0
for i in range(len(num1)):
a = ord(num1[len(num1) -... |
"""For-Else, Any."""
from typing import Iterable
def tiene_pares_basico(numeros: Iterable[int]) -> bool:
"""Toma una lista y devuelve un booleano en función si tiene al menos un
número par."""
for numero in numeros:
if numero % 2 == 0:
return True
return False
# NO MODIFICAR - I... |
from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from .views import template_test
urlpatterns = patterns(
'',
url(r'^test/', template_test, name='template_test'),
url(r... |
# -*- coding: utf-8 -*-
import torch
from utils import timer
from data import cfg
@torch.jit.script
def point_form(boxes):
""" Convert prior_boxes to (xmin, ymin, xmax, ymax)
representation for comparison to point form ground truth data.
Args:
boxes: (tensor) center-size default boxes from priorbo... |
from django.db import models
from django.utils import timezone
from django.dispatch import receiver
from django.db.models import signals
class LabCode(models.Model):
"""
Lab Code. This will be used to match the responses to a laboratory session.
"""
code = models.CharField(max_length=50, blank=False, unique=... |
#!/usr/bin/env python
from setuptools import setup, find_packages
from timetable import VERSION
github_url = 'https://github.com/g3rd/django-timetable'
setup(
name='django-timetable',
version='.'.join(str(v) for v in VERSION),
description='An Django app that provides generic calendar functions',
lon... |
import dearpypixl.appitems.values
from dearpypixl.appitems.values import *
from dearpypixl.components.registries import ValueRegistry
__all__ = [
*dearpypixl.appitems.values.__all__,
"ValueRegistry"
] |
# coding:utf-8
import functools
import io
import os
import re
import sys
import time
from abc import abstractmethod
import easyutils
import pandas as pd
from . import exceptions
from . import helpers
from .config import client
from .log import log
if not sys.platform.startswith('darwin'):
import pywinauto
im... |
"""Register WS API endpoints for HACS."""
from __future__ import annotations
from homeassistant.components.websocket_api import async_register_command
from homeassistant.core import HomeAssistant
from ..api.acknowledge_critical_repository import acknowledge_critical_repository
from ..api.check_local_path import check... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
from cProfile import label
from openprompt.data_utils import PROCESSORS
DATA_DIR = "./data/"
SUPERGLUE_TASKS = [
"cb",
"copa",
"multirc",
"stsb",
"wsc",
"rte",
"mnli",
"mrpc",
"sst2",
"wic",
"qqp",
"qnli",
"mnli_mm",
]
SUPERGLUE_SCRIPTS_BASE = {
"boolq": "Supe... |
import time
import datetime as datetime
class BusData:
def __init__(self, number, destination, timeLiteral, operator):
self.number = number
self.destination = destination
self.timeLiteral = timeLiteral
self.operator = operator
self.time = prepare_departure_time(timeLiteral)
def prepare_departure... |
# -*- coding: utf-8 -*-
# fo.py
# classes to scrape and parse footballoutsiders.com
import logging
import time
from bs4 import BeautifulSoup
from sportscraper.scraper import RequestScraper
from sportscraper.utility import merge_two
class Scraper(RequestScraper):
def dl(self, season=""):
"""
Gets... |
import os
import pandas as pd
from tqdm import tqdm
import torch
from torchvision import transforms
from torch.utils.data import DataLoader, Dataset
from torchvision.datasets.folder import pil_loader
from configs.mura_config import mura_config
data_cat = ['train', 'valid'] # data categories
def get_study_level_data(... |
import argparse
import os
import xml.etree.ElementTree as ET
from multiprocessing.pool import ThreadPool
from gutenberg.query import get_metadata
CACHE_PATH = ""
def get_one_title_from_cache(book_id):
return (book_id, get_metadata("title", int(book_id)))
def get_one_title(book_id):
try:
title = (... |
# Copyright (C) 2019 Apple Inc. 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 code must retain the above copyright
# notice, this list of conditions and the f... |
# --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
"""Test a Fast R-CNN network on an imdb (image database)."""
from fast... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.