text stringlengths 1 927k |
|---|
from django.db import DatabaseError
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from proffy_api.core.models import ClassSchedule, Connection, ProffyUser
from proffy_api.core.serializers import (
... |
import numpy as np
import pytest
from pandas import DataFrame, Float64Index, Index, Int64Index, RangeIndex, Series
import pandas._testing as tm
class TestFloatIndexers:
def check(self, result, original, indexer, getitem):
"""
comparator for results
we need to take care if we are indexing ... |
from typing import Optional, Union
from typing import Literal
from pydantic import BaseModel
class Dessert(BaseModel):
kind: str
class Pie(Dessert):
kind: Literal['pie']
flavor: Optional[str]
class ApplePie(Pie):
flavor: Literal['apple']
class PumpkinPie(Pie):
flavor: Literal['pumpkin']
... |
"""
FString unparsing
This whole module feels like a hack.
Mostly because FStrings feel like a hack.
"""
import ast
import copy
from python_minifier import UnstableMinification
from python_minifier.ast_compare import CompareError
from python_minifier.ast_compare import compare_ast
from python_minifier.expression_pr... |
import os
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.colorchooser import askcolor
from PIL import Image, ImageTk
from tkmacosx.widget import *
from tkmacosx.variables import *
from tkmacosx.colorscale import Colorscale
from tkmacosx.colors import Hex as C_dict
def grid(root,row,column):
"Defines r... |
import pytest
from mimesis_stats.providers.distribution import Distribution
@pytest.mark.parametrize(
"population, weights, return_value",
[
(["A", "B"], [0, 1], "B"),
([1, 2, 3], [1, 0, 0], 1),
],
)
def test_discrete_distribution_fixed(population, weights, return_value):
"""Test does... |
'''
Import module:
Terdapat library yang khusus digunakan pada sensor M5Stack.
Dalam pengembangan mungkin akan muncul notifikasi error 'Unable to Import' karena
modul yang digunakan tidak tersedia pada library python umum.
'''
from numbers import Number
from m5stack import *
from m5ui import *
from uiflow import *
fro... |
import logging
import theano
logger = logging.getLogger(__name__)
import numpy
from theano.gof import Op, Apply
from theano.tensor import as_tensor_variable, dot, DimShuffle, Dot
from theano.tensor.blas import Dot22
from theano.tensor.opt import (register_stabilize,
register_specialize, register_canonicalize... |
# Copyright (c) ACSONE SA/NV 2018
# Distributed under the MIT License (http://opensource.org/licenses/MIT).
import ast
import os
import re
import subprocess
MANIFEST_NAMES = ("__manifest__.py", "__openerp__.py", "__terp__.py")
VERSION_RE = re.compile(
r"^(?P<series>\d+\.\d+)\.(?P<major>\d+)\.(?P<minor>\d+)\.(?P<p... |
import importlib
def load_config(args):
config_module = importlib.import_module("configs.{}_configs".format(args.dataset))
config = getattr(config_module, "{}_config".format(args.model))
config_obj = config()
config_dict = {}
obj_attributes = [attribute for attribute in dir(config_obj) if not att... |
"""Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where
horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly,
verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertica... |
#!/usr/bin/env python
from __future__ import print_function
from collections import OrderedDict
from shutil import copyfile
import argparse
import json
import os
import pprint
import re
import subprocess
import sys
import tempfile
def normalize(dict_var):
for k, v in dict_var.items():
if isinstance(v, Or... |
class Solution:
"""
@param A : a list of integers
@param target : an integer to be inserted
@return : an integer
"""
def searchInsert(self, A, target):
# write your code here
l, r = 0, len(A) - 1
while l <= r:
m = (l + r) / 2
if A[m] == target:
... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# 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 modif... |
import typing as tp
import jax
import jax.numpy as jnp
import numpy as np
import treeo as to
from treex import types, utils
from treex.metrics.metric import Metric
class Metrics(Metric):
metrics: tp.Dict[str, Metric]
def __init__(
self,
metrics: tp.Any,
on: tp.Optional[types.IndexLi... |
####################################
# File name: batch_project_elevation.py
# About: Process for batch converting elevation raster tiles.
# Author: Geoff Taylor | Imagery & Remote Sensing Team | Esri
# Date created: 01/25/2021
# Date last modified: 01/25/2021
# Python Version: 3.7
#########################... |
import os
from io import open
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname), encoding='utf-8').read()
setup(
name="c7n",
version='0.8.27.2',
description="Cloud Custodian - Policy Rules Engine",
long_description=read('READM... |
from ledfx.effects.audio import AudioReactiveEffect, FREQUENCY_RANGES
from ledfx.effects.colorrainbow import ColorRainbowEffect
import voluptuous as vol
import numpy as np
import time
import statistics
import requests
import threading
class DranoBeatAudioEffect(AudioReactiveEffect, ColorRainbowEffect):
NAME = "D... |
# -*- coding: utf-8 -*-
"""
flask_security.recoverable
~~~~~~~~~~~~~~~~~~~~~~~~~~
Flask-Security recoverable module
:copyright: (c) 2012 by Matt Wright.
:license: MIT, see LICENSE for more details.
"""
from flask import current_app as app
from werkzeug.local import LocalProxy
from .signals impor... |
from unittest import mock
import graphene
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.utils import calculate_checkout_quantity
from .....plugins.manager import get_plugins_manager
from ....tests.utils import get_g... |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
def test_bool_sort():
array = ak.layout.NumpyArray(np.array([True, False, True, False, False]))
assert ak.to_list(ak.sort(ar... |
"""
Copyright(c) 2016-2019 Keith Sterling http://www.keithsterling.com
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, mod... |
#!/usr/bin/env python
import zmq
socket = zmq.Context().socket(zmq.SUB)
socket.connect("tcp://localhost:50000")
socket.setsockopt(zmq.SUBSCRIBE, b"")
poller = zmq.Poller()
poller.register(socket, zmq.POLLIN)
while True:
socks = dict(poller.poll(timeout=None))
if socket in socks and socks[socket] == zmq.POLLI... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
import RTxxx_uidef
import uidef
import uivar
import uilang
sys.path.append(os.path.abspath(".."))
from _main import RTyyyy_main
class secBootRTxxxUi(RTyyyy_main.secBootRTyyyyMain):
def __init_... |
# coding: utf-8
"""
Browse API
OpenAPI spec version: v1.7.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class TimeDuration(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do no... |
from uuid import uuid1
import click
from sceptre.context import SceptreContext
from sceptre.cli.helpers import catch_exceptions, confirmation
from sceptre.cli.helpers import write, stack_status_exit_code
from sceptre.cli.helpers import simplify_change_set_description
from sceptre.stack_status import StackChangeSetSta... |
import math
class Scheduler:
def __init__(self, n_epoch):
self.n_epoch = n_epoch
class ExponentialScheduler(Scheduler):
def __init__(self, x_init: float, x_final: float, n_epoch: int):
Scheduler.__init__(self, n_epoch)
self.step_factor = math.exp(math.log(x_final / x_init) / n_epoch)... |
#!/usr/bin/env python
"""The setup script."""
# Copyright (c) 2018-2020 Beijing Ekitech Co., Ltd.
# All rights reserved.
from setuptools import setup, find_packages
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
... |
# Generated by Django 3.2.2 on 2021-07-11 13:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recipes', '0021_tag_slug'),
]
operations = [
migrations.AlterField(
model_name='tag',
name='title',
fiel... |
"""P6E4 VICTORIA PEÑAS
Escribe un programa que te pida dos números, de manera que el segundo
sea mayor que el primero. El programa termina escribiendo los dos
números tal y como se pide:"""
num1=int(input("Escribe un número: "))
num2=int(input(f"Escribe un número mayor que {num1}: "))
while num1>=num2:
num2=int(inp... |
# Copyright (c) 2014 Rackspace US, Inc
# 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 req... |
# core
from django.db import models
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.urls import reverse
# django-taggit
from taggit.managers import TaggableManager
# django-markdownx setting
from markdownx.models import MarkdownxField
from markdownx.utils import markdownif... |
from tkinter import *
from tkinter import messagebox
import re
from tkinter import ttk
import sqlite3
from sqlite3 import Error
import os,sys
py=sys.executable
#creating window
class reg(Tk):
def __init__(self):
super().__init__()
self.title("SLIMS")
self.maxsize(1366, 768)
self.min... |
from rest_framework import serializers
from testapp.models import details
class detailserialize(serializers.ModelSerializer):
class Meta:
model=details
fields="__all__" |
from PyQt5.QtWidgets import QMenu
from qtpy.QtWidgets import (
QHBoxLayout,
QWidget,
QPushButton,
QToolButton,
QStyle,
QGroupBox,
QLabel,
)
from qtpy.QtCore import Qt
from aydin.io.datasets import examples_single
class QProgramFlowDiagramWidget(QWidget):
def __init__(self, parent):
... |
"""
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
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, merg... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayMarketingCrowdDataSyncModel(object):
def __init__(self):
self._biz_from = None
self._create_id = None
self._crowd_id = None
self._crowd_name = None
s... |
# coding=utf-8
from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField
from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde
# Generated with OTLEnumerationCreator. To modify: extend, do not edit
class KlAlgProvincie(KeuzelijstField):
"""Lijst van provincies in Vlaanderen."""
n... |
from __future__ import division
import os
from collections import OrderedDict
from future.utils import iteritems
import numpy as np
import scipy.stats
from scipy.integrate import cumtrapz
from scipy.interpolate import interp1d
from scipy.special import erf, erfinv
# Keep import bilby statement, it is necessary for s... |
resp = 'S'
soma = quant = media = maior = menor = 0
while resp in 'Ss':
n = int(input('Digite um número'))
soma += n
quant += 1
if quant == 1:
maior = menor = n
else:
if n > maior:
maior = n
if n < menor:
menor = n
resp = str(input('Quer continuar?... |
# -*- coding: utf-8 -*-
#
# CodeIgniter documentation build configuration file, created by
# sphinx-quickstart on Sun Aug 28 07:24:38 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
#... |
from django.test import TestCase, Client
from django.urls import reverse
from posts.models import Post, Group, User
class ViewsTests(TestCase):
@classmethod
def setUpClass(cls):
"""
Making unauthorised client
Creating 'First Group' and 'FirstUser'
"""
super().setUpClas... |
"""
Base class and utilities for defining neural networks to be used on ComptoxAI
data.
We stick to PyTorch for implementing all neural networks, due to its speed,
expressiveness, and readability. For more documentation on PyTorch, check out
`PyTorch Documentation<https://pytorch.org/docs/stable/index.html>`_. Severa... |
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from datetime import date
from ..core import ChineseNewYearCalendar, WesternCalendar
from ..core import IslamicMixin
from ..registry_tools import iso_register
@iso_register('MY')
class... |
# Copyright 2012 New Dream Network, LLC (DreamHost)
#
# 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 a... |
import carla
import matplotlib.pyplot as plt
import numpy as np
import math
import sys
from srunner.tools.route_manipulation import interpolate_trajectory
#Returns only the waypoints in one lane
def single_lane(waypoint_list, lane):
waypoints = []
for i in range(len(waypoint_list) - 1):
if waypoint_lis... |
from __future__ import absolute_import
from django.template import Library
from django.core.urlresolvers import reverse
from i18ntools.utils import url_for_language, language_context
register = Library()
@register.simple_tag
def i18nurl(language_code, view, *args, **kwargs):
with language_context(language_cod... |
# -*- coding: UTF-8 -*-
#NVDAObjects/window/_msOfficeChartConstants.py
#A part of NonVisual Desktop Access (NVDA)
#Copyright (C) 2014-2017 NV Access Limited, NVDA India
#This file is covered by the GNU General Public License.
#See the file COPYING for more details.
import eventHandler
import time
import ui
from . impo... |
# Copyright 2016 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 writin... |
# -*- encoding: utf-8 -*-
"""
Module for running stat command. Same can be used in both Audit/FDG
Note: Now each module just returns its output (As Data gathering)
For Audit checks, comparison logic is now moved to comparators.
See below sections for more understanding
Usable in Modules
-----------------... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyNeo(PythonPackage):
"""Neo is a package for representing electrophysiology data in Pytho... |
# -*- coding: utf-8 -*-
__author__ = """Yngve Mardal Moe"""
__email__ = 'yngve.m.moe@gmail.com'
__version__ = '0.0.1'
from . import color, files |
import logging
import os
from galaxy.util import galaxy_root_path, parse_xml
log = logging.getLogger(__name__)
# Set a 10 minute timeout for repository installation.
repository_installation_timeout = 600
def get_installed_repository_info(elem, last_galaxy_test_file_dir, last_tested_repository_name, last_tested_cha... |
from django.http import HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import numpy as np
from PIL import Image
import io
# Create your views here.
def index(request):
return HttpResponse(request, "hi there")
class SendImage(A... |
# coding: utf-8
"""
Gate API v4
Welcome to Gate.io API APIv4 provides spot, margin and futures trading operations. There are public APIs to retrieve the real-time market statistics, and private APIs which needs authentication to trade on user's behalf. # noqa: E501
Contact: support@mail.gate.io
Gen... |
"""
The Plugin Extension handles application plugin support, and is the default
plugin handler used by Cement.
Requirements
------------
* No external dependencies
Configuration
-------------
This extension does not directly honor any configuration settings.
Usage
-----
For usage information see :ref:`applicat... |
"""定义任务"""
from .hywx.sms2 import send_sms
from celery_tasks.main import celery_app
# 使用装饰器装饰异步任务,保证celery识别任务
@celery_app.task(name='send_sms_code')
def send_sms_code(mobile, sms_code):
"""
发送短信验证码
:param mobile:手机号码
:param sms_code:短信验证码
:return: 成功:0 或者 失败:-1
"""
send_ret = send_sms(mob... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed ... |
import re
import typing
EXPANSION_PATTERN = re.compile(r"(\d*)\(([^()]*)\)")
def solve(st: str) -> str:
def expand(match: typing.Match) -> str:
if match.group(1):
return match.group(2)*int(match.group(1))
else:
return match.group(2)
old = None
while old != st:
... |
import sys
import nltk
import sklearn
import pandas as pd
import numpy as np
df= pd.read_table('SMSSpamCollection',header= None, encoding='utf-8')
classes = df[0]
print(classes.value_counts())
#Preprocess the data
"""
0= ham
1=spam
for this we use label encoder
"""
from sklearn.preprocessing import LabelEncoder
... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.11.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
i... |
# this is an attempt at dividing a surface in bite-size possibility
import Rhino.Geometry as rg
# grasshopper parameters
surface
min_length
max_length
div_aim
# resetting the domain of the surface
domain_goal = rg.Interval(0.0, 1.0)
surface.SetDomain(0, domain_goal)
surface.SetDomain(1, domain_goal) |
import argparse # pragma: no cover
from . import BaseClass, base_function # pragma: no cover
def main() -> None: # pragma: no cover
"""
The main function executes on commands:
`python -m test_template` and `$ test_template `.
This is your program's entry point.
You can change this function t... |
#
# Copyright SAS Institute
#
# 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... |
#define BPM 140.0
const float PI = acos(-1.0);
const float TAU = PI * 2.0;
/* sound common */
float timeToBeat(float t) {return t / 60.0 * BPM;}
float beatToTime(float b) {return b / BPM * 60.0;}
float sine(float phase) {
return sin(TAU * phase);
}
float fm(float t, float f, float i, float r){
return sin(TAU *... |
import openeo
import logging
logging.basicConfig(level=logging.INFO)
GEE_DRIVER_URL = "https://earthengine.openeo.org/v1.0"
# Connect to backend via basic authentication
con = openeo.connect(GEE_DRIVER_URL)
con.authenticate_basic()
datacube = con.load_collection("COPERNICUS/S1_GRD",
s... |
import KratosMultiphysics
import KratosMultiphysics.KratosUnittest as KratosUnittest
import KratosMultiphysics.HDF5Application.single_mesh_temporal_output_process as single_mesh_temporal_output_process
import KratosMultiphysics.HDF5Application.multiple_mesh_temporal_output_process as multiple_mesh_temporal_output_proce... |
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
# Copyright 2020 CSIRO
# 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, software
... |
# 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... |
import io
import csv
import logging
from StringIO import StringIO
from datetime import datetime
from gzip import GzipFile
import boto3
from celery import shared_task
from flask import current_app
from flask_mail import Attachment
from invenio_mail.api import TemplatedMessage
logger = logging.getLogger(__name__)
def... |
#!/usr/bin/env python
""" light django app to return the client ip address """
import os
import sys
from django.conf import settings
DEBUG = os.environ.get('DEBUG', 'on') == 'on'
SECRET_KEY = os.environ.get('SECRET_KEY', 'you need a secret key here, dude')
ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').... |
# -*- coding: utf-8 -*-
from h.util import db
from h.util import user
from h.util import view
__all__ = ("db", "user", "view") |
"""
Tests for the query API
"""
import sys
try:
from unittest.mock import Mock, patch
except ImportError:
from mock import Mock, patch
from nose.tools import assert_is_not_none, assert_is_none, assert_equals, assert_true, assert_raises
import pandas as pd
import requests
from apptuit import Apptuit, ApptuitE... |
"""Tests for the RGCN message passing layer."""
import tensorflow as tf
import pytest
from tf2_gnn.layers.message_passing import MessagePassingInput, RGCN
shape_test_data = [
(tf.TensorShape(dims=(None, 3)), tuple(tf.TensorShape(dims=(None, 2)) for _ in range(3)), 5),
(tf.TensorShape(dims=(None, 1)), tuple(t... |
#!/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.
# --------------------------------------------------------------... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
from ray.tune.error import TuneError
from ray.tune.suggest import BasicVariantGenerator
from ray.tune.trial import Trial, DEBUG_PRINT_INTERVAL
from ray.tune.log_sync import wait_for_log_sync
from r... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# flake8: noqa
from __future__ import print_function
import io
from os import path
from setuptools import setup
here = path.abspath(path.dirname(__file__))
def read(*names, **kwargs):
return io.open(
path.join(here, *names),
encoding=kwargs.get('... |
import warnings
import unittest
import sys
import os
import atexit
import numpy as np
from scipy import sparse
import pytest
from sklearn.utils.deprecation import deprecated
from sklearn.utils.metaestimators import if_delegate_has_method
from sklearn.utils._testing import (
assert_raises,
assert_warns,
... |
'tldextract helpers for testing and fetching remote resources.'
import re
import socket
import sys
from urllib.parse import scheme_chars
IP_RE = re.compile(
r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$') # pylint: disable=line-too-long
SCHEME_RE =... |
import json
from daemon import _get_app
from daemon.parser import get_main_parser
from jina.logging.logger import JinaLogger
from jina.parsers import set_gateway_parser
from jina.peapods.runtimes.asyncio.http.app import get_fastapi_app
JINA_LOGO_URL = 'https://api.jina.ai/logo/logo-product/jina-core/horizontal-layou... |
# coding=utf8
# Copyright 2018 JDCLOUD.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 required by applicable law or agreed ... |
class Solution:
"""
@param A: A list of integers
@return: A boolean
"""
def canJump(self, A):
# write your code here
dp = [False] * (len(A))
dp[0] = True
for i in range(1, len(A)):
dp[i] = False
for j in range(i):
if (dp[j] ==... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from enum import Enum
from typing import List, Optional
from .pytext_config import ConfigBase
class ModuleConfig(ConfigBase):
# Checkpoint load path
load_path: Optional[str] = None
# Checkpoint save path, relati... |
#!/usr/bin/env python3
# Copyright (c) 2015-2018 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 multiple RPC users."""
from test_framework.test_framework import BitcoinTestFramework
from test_f... |
"""
Version number normalization library.
"""
import re
from typing import List, Optional, Tuple, Any
from pineboolib.core.utils import logging
SubVersionNumber = int
SubVersionAppendedText = str
SubVersionTuple = Tuple[SubVersionNumber, SubVersionAppendedText]
logger = logging.getLogger(__name__)
class VersionNu... |
#
# 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... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Author : windz
Date : 2020-04-15 15:26:26
LastEditTime : 2021-10-09 16:43:49
Description : get full length transcripts from bam
'''
import pysam
import pandas as pd
import click
@click.command()
@click.option('-i', '--infile', required=True)
@click.o... |
from model.contact import Contact
import random
import allure
def test_update_contact(app, db):
with allure.step("Сheck for not empty list of contacts"):
if len(db.get_contact_list()) == 0:
app.contact.contact(Contact(firstname="Nikita", middlename="qqqqq", lastname="Skvortsov"))
with allu... |
#KeyboardInterrupt
try:
print 'Press Return or Ctrl-C:',
ignored = raw_input()
except Exception, err:
print 'Caught exception:', err
except KeyboardInterrupt, err:
print 'Caught KeyboardInterrupt'
else:
print 'No exception'
#MacBook-Pro-de-jose:exceptions joseuranga$ python exceptions_KeyboardInte... |
# -*- coding: utf-8 -*-
# Copyright 2020 Green Valley Belgium NV
#
# 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... |
from pkg_import import pkg_func # noqa |
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
ME_URL = reverse('user:me')
def create_user(**params... |
"""
Select the correct ordering of steps for a preorder depth-first traversal
A - 1. Visit node
2. Go to the right subtree
3. got to the left subtree
B - 1. Go to the right subtree
2. Go to the left subtree
3. Visit node
C - 1. Go to the left subtree
2. Go to the right subtree
3. Visit node... |
"""caps URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/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-based views
1. A... |
__author__ = 'myang'
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class StartFailoverProtectionGroupRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_ma... |
import FWCore.ParameterSet.Config as cms
from Validation.CTPPS.simu_config.base_cff import *
import CalibPPS.ESProducers.ppsAssociationCuts_non_DB_cff as ac
ac.use_single_infinite_iov_entry(ac.ppsAssociationCutsESSource, ac.p2016)
ppsAssociationCutsESSource = ac.ppsAssociationCutsESSource
# base profile settings for... |
#!/usr/bin/python
import os
import urllib2
import urllib
import websocket
import sys
if sys.version_info[0] < 3:
import thread
else:
import _thread
import time
import json
class Network ():
def __init__(self, uri, wsuri):
self.Name = "Communication to Node.JS"
self.ServerUri = uri
self.WSServerUri ... |
from invoke import task
from tasks.common import COMMON_TARGETS_AS_STR, VENV_PREFIX
@task
def flake8(ctx):
"""Check style through flake8"""
ctx.run(f"{VENV_PREFIX} flake8 --config=setup.cfg")
@task
def mypy(ctx):
"""Check style through mypy"""
ctx.run(f"{VENV_PREFIX} mypy")
@task
def black_check(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.