content stringlengths 5 1.05M |
|---|
#!/usr/bin/python
import networkx as nx
# create Directed Graph called DG
DG = nx.DiGraph()
# create a list of ASNs
ASpath1=[11039, 174, 14743, 13546]
# add edges to directed graph from a list
# new nodes will be created as needed (ie, if they don't exist in DG, they'll be created, existing nodes
# will not be dupl... |
from django.test import TestCase,Client
from django.urls import reverse
class TestReviews(TestCase):
def setUp(self):
self.client=Client()
def test_getReviews(self):
#response = requests.get('http://localhost:8000/Reviews/')
response = self.client.get(reverse('reviews-list'))
... |
from setuptools import setup
setup(name='detector',
version='1.0',
description='Classes implementing detection based processing pipelines.',
author='IVALab',
packages=['detector'],
)
|
from wtforms import StringField, validators
from kaira.app import App
from kaira.response import response
from kaira.wtf import KairaForm
app = App()
class SigninForm(KairaForm):
username = StringField('Username', [validators.Length(min=4, max=25)])
password = StringField('Password', [validators.Length(mi... |
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Login(models.Model):
username = models.CharField(max_length=250)
password = models.CharField(max_length=250) |
import os
import django_cache_url
import raven
from .base import FragDenStaatBase, env
class FragDenStaat(FragDenStaatBase):
DEBUG = False
TEMPLATE_DEBUG = False
CELERY_TASK_ALWAYS_EAGER = False
CELERY_SEND_TASK_ERROR_EMAILS = True
ADMINS = (('FragDenStaat.de', 'mail@fragdenstaat.de'),)
MA... |
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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,... |
#! /usr/bin/env python
import rospy
from ros_boilerplate.boilerplate_class import BoilerPlate
def run():
rospy.init_node('boilerplate')
boilerplate = BoilerPlate()
# NOTE: It's a good idea to sleep a little bit after creating all
# publishers and subscribers. This gives the node time to register with... |
# -*- coding: utf-8 -*-
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
# holder of all proprietary rights on this computer program.
# You can only use this computer program if you have closed
# a license agreement with MPG or you get the right to use the computer
# program from someone who is... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import datetime
import os
from azure.keyvault.keys import KeyClient
from azure.identity import DefaultAzureCredential
from azure.core.exceptions import HttpResponseError... |
# This is a backup from my Kernel for training 37
import torch as th
import torch.utils.data as data
from tqdm import tqdm_notebook as tqdm
import os
import time
import apex
from matplotlib import pyplot as plt # noqa
import numpy as np
import pickle
import cv2
from glob import glob
"""Feature Pyramid Network (FPN) o... |
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import torch
import torch.nn.functional as F
from tests.utils import jitVsGlow
class TestSoftmax(unittest.TestCase):
def test_softmax_basic(self):
"""Basic test of the PyTorch SoftMax Node on Glow."""
... |
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 Volodymyr Turanskyy
# remote:bit is a remote Python execution library for BBC micro:bit
# https://github.com/voltur01/remotebit
from microbit import *
def set_tempo(ticks: int = 4, bpm: int = 120) -> None:
get_mb_link().send(f'music.set_tempo {ticks} {bpm}')
d... |
import six
def get(bs,i):
if six.PY2:
return ord(bs[i])
else:
return bs[i]
def hashCode(s):
bs = s.encode("utf-8")
hash = 0
for i in range(len(bs)):
hash = (31*hash+get(bs,i))&0xFFFFFFFF
return ((hash+0x80000000)&0xFFFFFFFF)-0x80000000
|
# Generated by Django 3.2.5 on 2021-08-13 06:48
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0027_alter_event_description'),
]
operations = [
migrations.Create... |
from ..SaneCard import SaneCard
class Investigators (SaneCard):
def __init__(self):
super().__init__("Investigators",
"When you discard Investigators" +
" during your turn, choose another player and name a number (other" +
" than 1). If that player has that number in their hand, th... |
listabr = ('São Paulo', 'Atlético - MG', 'Flamengo', 'Palmeiras', 'Internacional', 'Grêmio', 'Fluminense', 'Santos', 'Atlético - GO', 'Corinthians', 'Ceará', 'Red Bull Bragantino', 'Fortaleza', 'Athletico Paranaense', 'Sport', 'Bahia', 'Vasco da Gama', 'Coritiba', 'Goiás', 'Botafogo')
for c in range(0, len(listabr)):
... |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
import cohesity_management_sdk.models.entity_proto
import cohesity_management_sdk.models.deploy_v_ms_to_cloud_task_state_proto
import cohesity_management_sdk.models.destroy_clone_app_task_info_proto
import cohesity_management_sdk.models.destroy_cloned_vm_task_info... |
from solver import Solver
import numpy as np
class RidgeRegression(Solver):
"""
Analytically performs ridge regression, where coefficients are regularized by learning rate alpha. This constrains
coefficients and can be effective in situations where over- or under-fitting arise. Parameters `alpha`
is t... |
from railrl.samplers.data_collector import VAEWrappedEnvPathCollector
from railrl.torch.her.her import HERTrainer
from railrl.torch.sac.policies import MakeDeterministic
from railrl.torch.sac.sac import SACTrainer
from railrl.torch.vae.online_vae_algorithm import OnlineVaeAlgorithm
from railrl.visualization.video impo... |
class NotificationPermissions:
RECEIVE_NOTIFICATION_EMAILS = 'RECEIVE_NOTIFICATION_EMAILS'
FOLLOWED_AUTHOR_ARTICLE_CREATED = 'FOLLOWED_AUTHOR_ARTICLE_CREATED'
PROFILE_FOLLOW = 'PROFILE_FOLLOW'
MY_ARTICLE_COMMENTED = 'MY_ARTICLE_COMMENTED'
FAVORITED_ARTICLE_COMMENTED = 'FAVORITED_ARTICLE_COMMENTED'
... |
# https://www.hackerrank.com/contests/w34/challenges/once-in-a-tram
def luckyNumber(num):
sf3 = sum([int(i) for i in str(num)[:3]]);
sl3 = sum([int(i) for i in str(num)[3:]]);
return (sf3 == sl3);
def onceInATram(x):
x = x + 1;
while(True):
if(luckyNumber(x)):
break;
x ... |
# -*- coding: utf-8 -*-
import os
from click import Argument
from groundwork.patterns import GwCommandsPattern, GwRecipesPattern
class GwRecipesBuilder(GwCommandsPattern, GwRecipesPattern):
"""
Provides commands for listing and building recipes via command line interface.
Provided commands:
* reci... |
from typing import List, Set, Tuple
class Solution:
def combinationSum2(self, candidates: List[int],
target: int) -> Set[Tuple[int]]:
self.candidates = candidates
self.size = len(candidates)
self.target = target
self.result = set()
self.combination(0... |
"""proytit1 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
import numpy as np
from scipy.stats import kurtosis, norm
from batchedmoments import BatchedMoments
def test_correctness():
data = norm.rvs(size=1000, random_state=3) # kurtosis = -0.06928694200380558
bm = BatchedMoments(axis=0)(data)
assert np.allclose(kurtosis(data), bm.kurtosis, equal_nan=True)
|
from django.urls import path
from . import views
urlpatterns = [
# API
path('', views.retrieve_all_public_posts_on_local_server, name='post_index'),
path('<str:post_id>/', views.retrieve_single_post_with_id, name='post'),
path('<str:post_id>/comments/', views.comments_retrieval_and_creation_to_post_id,... |
# https://docs.conan.io/en/latest/creating_packages/getting_started.html
from conans import ConanFile
from conan.tools.cmake import CMakeToolchain, CMake
from conan.tools.layout import cmake_layout
class SsfConan(ConanFile):
name = "ssf"
version = "1.0.3"
description = "Simple Socket Functions"
url = ... |
"""
# -*- coding: utf-8 -*-
"""
#@author; Nobu Kim
from flask_login import current_user
import json
import re
import pandas as pd
from dash import Dash, exceptions, no_update, callback_context
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_bootstrap_components as dbc
i... |
import pygame
try:
from _internal import *
except ImportError:
from ._internal import *
DEF_SIZE = 1
class EnemyHead:
cached_colours = {}
def __init__(self, type_str, colour, size=DEF_SIZE):
print(size)
self.type_str = type_str
self.colour = colour
self.size_px = size... |
""" the technique of D&C"""
class DivideConquer:
def __init__(self) -> None:
pass
def recursive_addition(self, array):
if array == []:
return 0
return array[0] + DivideConquer.recursive_addition(array)
def recursive_length(self, array):
if array == []:
... |
# -*- coding: utf-8 -*
"""
:py:class:`ErnieSeqlabelLabelFieldReader`
"""
import paddle
from senta.common.register import RegisterSet
from senta.common.rule import DataShape, FieldLength, InstanceName
from senta.data.field_reader.base_field_reader import BaseFieldReader
from senta.data.util_helper import pad_batch_data... |
# APPARENT MAG -> ABSOLUTE MAG WITH DISTANCE INFO.
#============================================================
import glob
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import ascii, fits
from astropy.table import Table, vstack
from astropy import units as u
def app2abs(m, mer, d, der):
M = m -... |
#!/usr/bin/python3
#
#########################################################################
# nyaa.si auto downloader
# -----------------------
#
# Automatically checks for new episodes from a nyaa.si user RSS,
# adding the download to transmission-daemon and moving to the
# anime library once completed. Does the cl... |
#
# Copyright 2019 The FATE 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... |
from .abstract_car import AbstractCar
class Economy(AbstractCar):
@property
def description(self):
return 'Economy'
@property
def cost(self):
return 12000.00
|
from collections import defaultdict
from sails.ui import App
class CCMappings(object):
def __init__(self):
self.cc_aliases = defaultdict(set)
self.alias_ccs = defaultdict(set)
self.reload()
def reload(self):
App.settings.beginGroup("midi")
try:
source = Ap... |
import csv
import lxml.html as lh
import requests
if __name__ == '__main__':
host = 'https://www.bundesbank.de'
path = '/de/aufgaben/unbarer-zahlungsverkehr/serviceangebot/bankleitzahlen' # Create a handle, page, to handle the contents of the website
page = requests.get(host + path) # Store the contents... |
import csv
import json
import os
from django.core.exceptions import ObjectDoesNotExist
from django.template.defaultfilters import slugify
from indicators.models import (Indicator, CensusVariable, CensusSource,
Subdomain, CensusVariableSource, Table,
VizVar... |
import heapq
input = [ [3,5,7], [0,6], [0, 6, 28] ]
result = []
mergedResult = []
for i in input:
result = result + i
print(result)
heapq.heapify(result)
for _ in range(len(result)):
mergedResult.append(heapq.heappop(result))
print([heapq.heappop(result) for _ in range(len(result))])
""" import heapq
... |
from edi_835_parser.elements import Element, Code
# https://x12.org/codes/claim-adjustment-reason-codes
adjustment_reason_codes = {
'45': 'Charge exceeds fee schedule maximum allowable or contracted/legislated fee arrangement.',
'243': 'Services not authorized by network/primary care providers.',
'29': 'The time li... |
#!/usr/bin/env python3
import sys
import shutil
shutil.copy(sys.argv[1], sys.argv[2])
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import glob
import json
import logging
import os
import tempfile
import io
from builtins import object
from typing import Text
from future.utils import ... |
L = [99,102,89,120,117]
x = 0
for i in range(0,5):
if L[i] > x:
x = L[i]
print(f"\nO maior número da lista é: {x}") |
import datetime
import socket
import requests
from tester.core.singleton import Singleton
from tester import console_log
class ReservationException(Exception):
pass
class ReservationHandler(metaclass=Singleton):
def __init__(self, reservation_ip, port, name="Venctester", to_reserve_ip=None, auto_free=True... |
# Raspberry Pi Relay Controller: ModMyPi Version
from __future__ import print_function
import sys
from flask import Flask
from flask import make_response
from flask import render_template
from flask_bootstrap import Bootstrap
from relay_lib_modmypi import *
error_msg = '{msg:"error"}'
success_msg = '{msg:"success"... |
#!/usr/bin/env python3
"""
extracts the "play recap" and some related info from the YAML-style output of ansible-playbook
"""
# standard library modules
import argparse
import csv
import datetime
import json
import logging
import os
import re
import sys
# third-party modules
#import dateutil
import dateutil.parser
lo... |
import os
import socket
from typing import List, Optional
import paramiko
class SftpServerInfo:
"""
A Structure which has informations for ftp server.
Attributes
----------
host_name : str
Host name for sftp server.
Should not include like "sftp://", "http://", "https://" etc.
... |
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from server import app
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///database.db'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN']=True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=True
db = SQLAlchemy(app)
from events import *
from all_user import *... |
__author__ = 'cyrbuzz'
# 方便扩展,抽象成基类。
from base import (QCursor, QFrame, Qt, QTabWidget, QTextEdit, QLabel, QIcon, QPushButton, QHBoxLayout, QVBoxLayout,
QGridLayout, QTableWidgetItem, PicLabel, ScrollArea, TableWidget, VBoxLayout, HBoxLayout, pyqtSignal)
import addition
class S... |
# Copyright (c) 2018 Cloudify Platform Ltd. 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 ap... |
from gretel_client.transformers.fpe.fpe_prefix_cipher import FpePrefixCipher
KEY1 = bytearray.fromhex(
"2B7E151628AED2A6ABF7158809CF4F3CEF4359D8D580AA4F7F036D6F04FC6A94"
)
KEY2 = bytearray.fromhex(
"1628AED2A6A809CBF7158F4F3CEF4380AA4F7F036D6F059D8D54FC6A942B7E15"
)
def test_fpe_prefix_cipher():
cipher1 ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
"""
import operator
import sys
import re
import codecs
def getSyllablePron(syllable):
pron = u""
hasVowel1 = False
hasVowel2 = False
hasVowel3 = False
if u"a" in syllable or u"ă" in syllable or u"î" in syllable or u"â" in syllable:
hasVo... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-ember-rest',
version='0.1.7',
description='Django Models <> Ember-Data',
author='Mitchel Kelonye',
author_email='kelonyemitchel@gmail.com',
url='https://github.com/kelonye/django-ember-rest',
requires=['D... |
"""Save Variables Exporter"""
import logging
from typing import List
import tensorflow as tf
import pandas as pd
from deepr.exporters import base
from deepr.io.parquet import ParquetDataset
from deepr.io.path import Path
LOGGER = logging.getLogger(__name__)
class SaveVariables(base.Exporter):
"""Save Variabl... |
# Solution 1
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs or len(strs) == 0:
return ""
strs.sort()
res = ""
pair = zip(strs[0], strs[-1])
for x, y in pair:
if x == y:
r... |
from rest_framework.fields import SerializerMethodField
class LinkField(SerializerMethodField):
def __init__(self, method_name, *args, **kwargs):
self.method_name = method_name
super(LinkField, self).__init__(method_name, *args, **kwargs)
|
# (C) Copyright 2010-2020 Enthought, Inc., Austin, TX
# All rights reserved.
from unittest import TestCase
import testfixtures
from pyface.ui.qt4.util.gui_test_assistant import GuiTestAssistant
from force_bdss.core_plugins.base_extension_plugin import BaseExtensionPlugin
from force_wfmanager.plugins.plugin_dialog ... |
#!/usr/bin/env python
from nodes import Node
class Join(Node):
char = "J"
args = 2
results = 1
contents = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
default_sep = "\n"
def prepare(self, stack):
self.args = 2
if hasattr(self, "sep"): delattr(self, ... |
import asyncio
import aioboto3
from async_classes.async_db_connection import db_connection, DBConnection
async def read_from_s3():
bucket = 'bucket'
filename = 'filename'
session = aioboto3.Session()
s3 = await session.client("s3")
s3_ob = await s3.get_object(Bucket=bucket, Key=filename)
str... |
"""
Copyright (c) 2014 Miguel Grinberg
Copyright (c) 2015 Alexandru Ciobanu
"""
from datetime import timedelta
import functools
from time import time
from threading import Thread
from werkzeug.wrappers import Response
from flask import jsonify, url_for, request, make_response, current_app
from flask import g, abort
fro... |
import os
import subprocess
from datetime import datetime, timedelta
from typing import List
import dns.query
import dns.zone
from celery import shared_task
from django.utils import timezone
from desecapi import models
class ReplicationException(Exception):
def __init__(self, message, **kwargs):
super(... |
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch
import numpy as np
from sklearn.metrics import accuracy_score
from art.classifiers import PyTorchClassifier
def flattern(X):
return X.reshape(X.shape[0], -1)
def toOneHot(y):
return np.concatenate((y.reshape(-1, 1)==0, y... |
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
pass
|
# --------------------------------------------------------
# Tensorflow VCL
# Licensed under The MIT License [see LICENSE for details]
# Written by Zhi Hou, based on code from Chen Gao, Zheqi he and Xinlei Chen
# --------------------------------------------------------
from __future__ import absolute_import
from __fut... |
# -*- coding: utf-8 -*-
import socket
import ssl
import datetime
import requests
import sys
from config import DOMAINS, CODEXBOT_NOTIFICATIONS, DAYS_LIMIT, APITOKEN, CHATID
date_fmt = r'%b %d %H:%M:%S %Y %Z'
# tg
def send_message(text):
url = 'https://api.telegram.org/bot{}/sendMessage'.format(APITOKEN)
dat... |
import config
import collections.abc as container_abcs
import errno
import numpy as np
import os
import time
import torch
import torch.nn as nn
import torchvision
from itertools import repeat
from matplotlib import pyplot as plt
from PIL import Image
from torchvision.utils import make_grid
from torchvision.utils import... |
from pycocotools import mask as mask_utils
from collections import defaultdict
import numpy as np
from .data import Data
from . import functions as f
class APDataObject:
"""
Stores all the information necessary to calculate the AP for one IoU and one class.
Note: I type annotated this because why not.... |
# Copyright (c) 2015 Riverbed Technology, Inc.
#
# This software is licensed under the terms and conditions of the MIT License
# accompanying the software ("License"). This software is distributed "AS IS"
# as set forth in the License.
from steelscript.common.exceptions import *
from steelscript.netshark.core import... |
import logging as lg
from . FrameDefault import FrameDefault
from ..scene.Render import Render
from utils import Get, Set
class FrameSketchGeom(FrameDefault) :
@classmethod
def render(cls, i, data) :
tag = 'FrameSketchGeom: render'
Set.runtime('frame', data)
lg.info('{}: runtime/frame/data: {}'.form... |
"""
:mod:`orion.algo.HEBO.hebo -- Orion adapter for the HEBO algorithm.
============================================
The HEBO algorithm implementation can be found at https://github.com/huawei-noah/HEBO
"""
from __future__ import annotations
import contextlib
import copy
import typing
import warnings
from dataclasses... |
from sklearn.preprocessing import StandardScaler
from abc import ABC, abstractmethod
import numpy as np
class DistanceMetric(ABC):
"""Computes distances and defines the optimization model for both
exploration and penalty.
Parameters
----------
-
Attributes
----------
-
"""
... |
'''
Created on 12 jan. 2013
@author: sander
'''
from bitstring import BitArray
from pylisp.utils.afi import read_afi_address_from_bitstream, get_bitstream_for_afi_address
from pylisp.utils.lcaf import type_registry
from pylisp.utils.lcaf.base import LCAFAddress
class LCAFNATTraversalAddress(LCAFAddress):
lcaf_ty... |
''' mbinary
#########################################################################
# File : least_square.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2018-10-02 21:14
# Description:
#################################################... |
# -*- coding: ISO-8859-1 -*-
#import MidiOutStream
#import MidiInStream
#import MidiInFile
#import MidiToText |
import numpy as np
import pytest
import torch
from tests.base import (
images_list, flows_list, NUM_IMAGES, IMAGE_HEIGHT, IMAGE_WIDTH)
from flow_transforms import ToTensor, RandomAdditiveColor
@pytest.fixture
def get_tensor_data(images_list, flows_list):
tt = ToTensor()
images, flows = tt(images_list, fl... |
from django.contrib.messages import get_messages
from django.forms.models import model_to_dict
from django.test import TestCase
from django.urls import resolve, reverse
from products.factories import ProductFactory
from sellers.factories import SellerFactory, UserFactory
from sellers.models import Seller
from sellers.... |
#! python
import arcrest.admin
arcrest.admin.cmdline.createservice()
|
import appdaemon.plugins.hass.hassapi as hass
import datetime
#
# App which reminds you daily to water your plants if it won't rain
#
#
# Args:
#
# app_switch: on/off switch for this app. example: input_boolean.turn_fan_on_when_hot
# rain_precip_sensor: sensor which shows rain probability. example: sensor.dark_sky_pre... |
# PEP-8
# snake case
my_var = 5 # instance class int
print(my_var, type(my_var), dir(my_var))
my_var = '5' # instance class str
print(my_var, type(my_var), dir(my_var))
my_var = 5.0 # instance class float
print(my_var, type(my_var), dir(my_var))
|
from kapteyn import maputils
from matplotlib import pyplot as plt
f = maputils.FITSimage("m101.fits")
f.set_limits(pxlim=(50,440), pylim=(50,450))
fig = plt.figure(figsize=(8,5.5))
frame = fig.add_axes((0.05, 0.1, 0.8, 0.7))
fig.text(0.5, 0.96, "Combination of plot objects",
horizontalalignment='center',
... |
# This file simply indicates that GeneralClasssesFunctions is a package and enables compatibility with Python versions
# prior to 3.3
|
import pytest
import copy
from contextlib import contextmanager
from tracking_plan.errors import ValidationError
@contextmanager
def assert_raises_validation_error(expected_msg=None):
with pytest.raises(ValidationError) as err_info:
yield
if expected_msg:
assert expected_msg in str(err_info.... |
from pathlib import Path
from pyfixtures import fixture
from virtool_workflow.analysis.utils import make_read_paths
from virtool_workflow.data_model.samples import Sample
from virtool_workflow.api.samples import SampleProvider
@fixture
async def sample(sample_provider: SampleProvider, work_path: Path) -> Sample:
... |
# Copyright 2009 The Closure Library 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 requi... |
from typing import List
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if not matrix:
return 0
M, N = len(matrix), len(matrix[0])
dp = [[0] * (N+1) for _ in range(M+1)]
res = 0
for i in range(1, M+1):
for j in range(1, N+1):
... |
#!/usr/bin/env python
import os
import sys
# For coverage.
if __package__ is None:
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/..")
from unittest import main, TestCase
import requests
import requests_mock
from iris_sdk.client import Client
from iris_sdk.models.account import Account
XML_RES... |
import asyncio
import aiohttp
import pytest
import uvicorn
from asgiproxy.context import ProxyContext
from asgiproxy.simple_proxy import make_simple_proxy_app
from tests.configs import ExampleComProxyConfig
@pytest.mark.asyncio
async def test_asgiproxy_e2e(unused_tcp_port):
"""
End-to-end test the library's... |
# Licensed under a 3-clause BSD style license - see LICENSE
from __future__ import print_function, division
import sys
import os
try:
from scipy import weave
except:
try:
import weave
except:
print('weave cannot be import from scipy nor on its own.')
try:
from numba import autojit
ex... |
import numpy as np
from park import core, spaces, logger
from park.param import config
from park.utils import seeding
class ReplicaplacementEnv(core.Env):
def __init__(self):
self.setup_space()
self.seed(config.seed)
self.num_stream_jobs = config.num_stream_jobs
# self.cur_server... |
# You would like to count the number of fruits in your basket.
# In order to do this, you have the following dictionary and list of
# fruits. Use the dictionary and list to count the total number
# of fruits, but you do not want to count the other items in your basket.
result = 0 # initializes the result
basket_item... |
from samp import (
GetPlayerName,
SendClientMessage,
)
def OnPlayerConnect(playerid):
player_name = GetPlayerName(playerid)
SendClientMessage(
playerid,
0xFF0000FF,
f'Hello from Python, {player_name}!',
)
|
"""
Project Euler - Problem Solution 038
Problem Title - Pandigital multiples
Copyright (c) Justin McGettigan. All rights reserved.
https://github.com/jwmcgettigan/project-euler-solutions
"""
def is_pandigital(identity):
''' Checks if a number contains all digits 1-9 exactly once. '''
return len(identity) == 9 and... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
#!/usr/bin/env python
# encoding: utf-8
import RPi.GPIO as gpio
import time
# 指定GPIO口的选定模式为GPIO引脚编号模式(而非主板编号模式)
gpio.setmode(gpio.BCM)
# 指定GPIO14(就是LED长针连接的GPIO针脚)的模式为输出模式
# 如果上面GPIO口的选定模式指定为主板模式的话,这里就应该指定8号而不是14号。
gpio.setup(14, gpio.OUT)
# 循环10次
for i in range(0, 10):
# 让GPIO14输出高电平(LED灯亮)
gpio.output(14, True... |
import os
import numpy as np
from skimage.transform import resize
import streamlit as st
from streamlit_drawable_canvas import st_canvas
from PIL import Image
from matplotlib import pyplot as plt
import torch
from torchvision import datasets, transforms
from mnist import Net
model_path = "mnist_cnn.pt"
def load_m... |
# -*- coding: utf-8 -*-
"""VendorPart views."""
from flask import Blueprint, render_template, request, jsonify, make_response
from flask_login import login_required, current_user
from .forms import CreateVendorPartForm
from .models import VendorPart
from pid.common.models import Project, Material, MaterialSpecification... |
"""LTI Consumer plugin URLs configuration."""
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from . import models
from .api import LTIConsumerViewsSet
router = DefaultRouter()
router.register(
models.LTIConsumer.RESOURCE_NAME,
LTIConsumerViewsSet,
basename="lti-co... |
# Copyright 2021 The FastEstimator 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 appl... |
# coding=utf-8
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QLineEdit, \
QPushButton, QGridLayout, QTableWidget, QTableWidgetItem, QHeaderView
from PyQt5.QtCore import Qt
from zhixuewang import Zhixuewang
from zhixuewang.exceptions import UserOrPassError
import sys
class MainGUI(QWidget):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.