content stringlengths 5 1.05M |
|---|
# Copyright 2013-2022 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 RDmrcate(RPackage):
"""Methylation array and sequencing spatial analysis methods.
De ... |
"""
Gate Class (based on Gameobject).
"""
import pygame
from game_object import GameObject
class Gate(GameObject):
def __init__(self, x, y, width, height, color, player):
GameObject.__init__(self, x, y, width, height)
self.color = color
self.player = player
def draw(self, surface):
... |
from .api import APITestCase, StandardAPITestCases
from .base import MockedResponse, TestCase
from .filtersets import BaseFilterSetTests, ChangeLoggedFilterSetTests
from .functions import load_json
from .views import ViewTestCases
__all__ = (
"load_json",
"MockedResponse",
"APITestCase",
"StandardAPITe... |
"""
Using Evaluation Metrics in Model Selection
-------------------------------------------
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import mglearn
from IPython.display import display
from sklearn.svm import SVC
from sklearn.model_selection import (
cross_val_score,
train_test_s... |
# 2.3 Delete Middle Node
# Implement an algorithm to delete a node in the middle of a singly linked list,
# given only access to that node.
# (i.e. any node but the first and last, not necessarily the exact middle)
class Node:
def __init__(self, data):
self.data = data
self.next = None
def ... |
# -*- coding: utf-8 -*-
# @Time : 2021/1/1 15:53
# @Author : 咸鱼型233
# @File : test1.py
# @Software: PyCharm
# @Function:
import socket
def send_msg(udp_socket):
# 获取发送内容
dest_ip = input("请输入对方的ip:")
dest_port = int(input("请输入对方的端口号:"))
send_data = input("请输入发送信息:")
udp_socket.sendto(send_da... |
"""Support for STIB-MIVB (Brussels public transport) information."""
import logging
from pyodstibmivb import ODStibMivb
import voluptuous as vol
import pytz
import datetime
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import ATTR_ATTRIBUTION, DEVICE_CLASS_TIMESTAMP # TIME_MINUTE... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pdb import set_trace
from lxml import etree
import os
import argparse
import sys
import pprint
from teixml2lib.ualog import Log
from teixml2lib.xml_const import *
import re
__date__ = "20-04-2021"
__version__ = "0.2.1"
__author__ = "Marta Materni"
logerr = Log("w"... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout as django_logout
from django.contrib.auth.models import User
from blog.models import Post
# Create your views h... |
#import shutup;shutup.please() # ignora esto por favor. No es necesario en tu código
import nltk # importamos módulos
import sys
tokens = [] # creamos una lista vacia
with open(sys.argv[1], 'r') as f: # le pedimos a python que lea el archivo que especificamos en la terminal
Lines = f.readlines() # lee línea por l... |
import json
import logging
from typing import Dict
import boto3
from botocore.exceptions import ClientError
from flask import Blueprint, current_app, jsonify
blueprint = Blueprint("api", __name__, url_prefix="/api")
_logger = logging.getLogger(__name__)
def get_quicksight_embedded_dashboard_url(
aws_account_id:... |
import pyodbc
import json
def run_script(server, uid, pwd, connect_to_db, sql):
return_code = 0
# connect to datasource
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+connect_to_db+';UID='+uid+';PWD='+ pwd)
# create cursor associated with connection
... |
import bisect
import copy
import json
import os
import re
from pathlib import Path
import xmltodict
from PIL import Image
from toolz.curried import groupby
from torch.utils.data import Dataset
from torchvision.datasets.utils import download_url, check_integrity
from horch.datasets.utils import download_google_drive
... |
# -*- coding: utf-8 -*-
"""
Input plug-in for a KKR calculation.
"""
import os
from numpy import pi, array
from aiida.orm.calculation.job import JobCalculation
from aiida_kkr.calculations.voro import VoronoiCalculation
from aiida.common.utils import classproperty
from aiida.common.exceptions import InputValidationErr... |
test_input = """
forward 5
down 5
forward 8
up 3
down 8
forward 2
"""
puzzle_input = """
forward 7
down 2
forward 7
down 6
forward 1
forward 7
down 3
up 5
forward 7
forward 6
down 8
down 1
up 5
up 1
down 2
forward 8
forward 3
down 8
down 9
down 1
forward 4
down 8
down 7
forward 3
up 5
up 3
forward 9
forward 5
forward ... |
################################################################################
# Modules and functions import statements
################################################################################
import logging
import socket
import jinja2
from datetime import datetime
from os import getenv
from jinja2 import ... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
# Adding elements to the front of the list
def insertFront(self, new_node):
new_node_... |
"""
The implementation of PSPNet based on Tensorflow.
@Author: Yang Lu
@Github: https://github.com/luyanger1799
@Project: https://github.com/luyanger1799/amazing-semantic-segmentation
"""
from amazingutils import layers as custom_layers
from amazingmodels import Network
import tensorflow as tf
layers = tf.keras.laye... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-10-14 09:20
# Manually modified to serve as input for the data migration 0009_migrate_to_datetimes
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wafer.snippets.markdown_field
class... |
from django import forms
from .choices import *
from common.FrontendTexts import FrontendTexts
view_texts = FrontendTexts('providers')
class ProviderForm(forms.Form):
labels = view_texts.getComponent()['creator']['labels']
name = forms.CharField(max_length=255, label=labels['name'])
category = forms.Choi... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
from typing import Any, Dict, Optional, Tuple
import torch
import torch.distributed as dist
from torch.distributed import ProcessGroup
if to... |
#! /usr/bin/python
"""Xmlgame: does xmlstuff
jsgame: does js stuff
App: gets clipboard and runs UI
Right now everythign depends on the UI being up and running. This won't always be the case, and isn't necessary.
"""
import Tkinter
import os
import re
from Tkconstants import *
import sys
import json
from xml.dom imp... |
import re
from .. import logger as log
from .base import BaseFilter
class RegexParser(BaseFilter):
def __call__(self, event):
key = self.options["key"]
if key in event:
content = event[key]
pattern = re.compile(self.options["pattern"])
if pattern.search(conten... |
#!/usr/bin/env python
## category Conversion
## desc Converts to BAM format (unmapped)
'''
Convert FASTQ to BAM. This doesn't perform any mapping, it simply stores the
read sequences in BAM format as unmapped reads. If given two files, the reads
will be correctly flagged as pairs.
'''
import os
import sys
import itert... |
# -*- coding: utf-8 -*-
"""
The ``sensortoolkit.evaluation_objs`` subpackage contains modules defining
the ``sensortoolkit.SensorEvaluation`` and ``sensortoolkit.PerformanceReport``
evaluation objects.
================================================================================
@Author:
| Samuel Frederick, NS... |
from pybind11 import get_cmake_dir
from pybind11.setup_helpers import Pybind11Extension, build_ext
from setuptools import Extension
from .utils import get_incs, get_srcs
# libi2c_module = Extension('pylibi2c', include_dirs=[
# 'ext_modules/libi2c/src'], sources=get_srcs('ext_modules/libi2... |
from .rest_api_base import *
# First Alert Methods appear in API 3.2
class AlertMethods32():
def __init__(self, rest_api_base: TableauRestApiBase32):
self.rest_api_base = rest_api_base
def __getattr__(self, attr):
return getattr(self.rest_api_base, attr)
def query_data_driven_alerts(self)... |
'''
Decentralized Parallel ICA (“dpICA”) : COINSTAC simulator
This script computes pICA using the INFOMAX criteria in decentralized environment.
Creator : Chan Panichvatana (cpanichvatana1@student.gsu.edu)
Reference: Parallel Independent Component Analysis (pICA): (Liu et al. 2009)
'''
from coinstac_computation impo... |
# Copyright 1999-2021 Alibaba Group Holding 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 a... |
#!/usr/bin/python
"""
(C) Copyright 2020 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... |
import sys
import subprocess
import numpy as np
from tqdm import tqdm
argline = sys.argv[1:]
if not argline:
print('Usage:')
print(' $ python 6_random_check.py <command_to_run_your_solution>')
print('Example:')
print(' $ python 6_random_check.py python 6_my_solution.py')
exit()
... |
#
# Generated with StressJointSegmentBlueprint
from dmt.blueprint import Blueprint
from dmt.dimension import Dimension
from dmt.attribute import Attribute
from dmt.enum_attribute import EnumAttribute
from dmt.blueprint_attribute import BlueprintAttribute
from sima.sima.blueprints.moao import MOAOBlueprint
class Stres... |
# Standard libraries
import logging
import os
import json
import datetime
import math
import copy
# External libraries
import pandas as pd
import numpy as np
import statsmodels.api as sm
import statsmodels.formula.api as smf
from statsmodels.stats.diagnostic import het_breuschpagan
from statsmodels.stats.diagnostic i... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) ARIADNEXT.
# Distributed under the terms of the Modified BSD License.
"""Annotator widget and associated models."""
from __future__ import annotations
import asyncio
from typing import Callable, Dict as TpDict, NoReturn, Union
from uuid import uuid4
from ipywid... |
# -*- encoding: utf-8 -*-
"""
Created by Ênio Viana at 22/09/2021 at 23:03:27
Project: py_dss_tools [set, 2021]
"""
from .PCElement import PCElement
class IndMach012(PCElement):
name = "IndMach012"
name_plural = "IndMach012s"
columns = ['basefreq', 'bus1', 'conn', 'd', 'daily', 'debugtrace', 'duty', 'en... |
from typing import Optional
from returns.maybe import Maybe, Nothing, Some
def test_bind_some():
"""Ensures that bind works correctly."""
def factory(inner_value: int) -> Maybe[int]:
return Some(inner_value * 2)
input_value = 5
bound = Some(input_value).bind(factory)
assert bound == fac... |
import csv
import folium
from folium.plugins import MarkerCluster
from bike_service_proxy import BikeServiceProxy
PATH_TO_LOCATIONS = 'locations.csv'
GDANSK_CENTER_POSITION = [54.346320, 18.649246]
BATTERY_LOW_PERCENT = 20
BATTERY_MEDIUM_PERCENT = 50
def get_available_bikes_number(station_row):
return int(stat... |
# Copyright 2021 The Flax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
import requests
import urllib.parse
from bs4 import BeautifulSoup
from geopy.geocoders import Nominatim
def parseCoord (coord):
start = 0
for i in range(0, len(coord)):
if coord[i].isnumeric () or coord[i] == '-' :
start = i
break
coordAsStr = coord[start: - 1].split (", ")... |
#!/usr/bin/env python
# Copyright (c) 2017 Facebook, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
import ctypes as ct
import unittest
from bcc import BPF
from netaddr import IPAddress
class KeyV4(ct.Structure):
_fields_ = [("prefixlen", ct.c_uint),
("data", ct.c_ubyte * 4)... |
class ActivityBase:
def __init__(self, activityId, x, y, h):
self.activityId = activityId
self.x = x
self.y = y
self.h = h
def __str__(self):
string = '<ActivityBase activityId=%d, ' % self.activityId
string += 'x=%d, y=%d, h=%d>' % (self.x, self.y, self.h)
... |
#!/usr/bin/env python3
## Simple talker demo that published std_msgs/Strings messages
## to the 'chatter' topic
import rospy
from std_msgs.msg import String
def talker():
rospy.init_node('talker', anonymous=True)
pub = rospy.Publisher('chatter', String, queue_size=10)
r = rospy.Rate(10) # 10hz
while ... |
# -*- coding: utf-8 -*-
"""
Paraxial optical calculations
"""
|
from typing import List, Optional, Union
import pandas as pd
from sklearn.utils.validation import check_is_fitted
from feature_engine.creation.base_creation import BaseCreation
from feature_engine.docstrings import (
Substitution,
_drop_original_docstring,
_feature_names_in_docstring,
_fit_not_learn_d... |
from wurst.geo import geomatcher
from . import DATA_DIR
REGION_MAPPING_FILEPATH = DATA_DIR / "regionmappingH12.csv"
def get_IAM_geomatcher():
"""
Geographical boundaries for IMAGE regions are initally included in geomatcher.
However, they are not properly labelled.
"""
d_image_regions = {
... |
"""API response model for PyTautulli Api.."""
from __future__ import annotations
from enum import Enum
from typing import Any
from .activity import PyTautulliApiActivity
from .base import APIResponseType, PyTautulliApiBaseModel
from .session import PyTautulliApiSession
from .user import PyTautulliApiUser
class APIR... |
#!/usr/bin/env python
"""Download files from Cohesity backups using Python"""
# usage: ./downloadFile.py -v mycluster -u myusername -d mydomain.net -o myserver -f 'mypath/myfile' -p /Users/myusername/Downloads
from pyhesity import *
from urllib import quote_plus
import sys
import os
# command line arguments
import a... |
# 现在单位成本价,现在数量
current_unit_cost = 78.1
current_amount = 1300
# 计算补仓后成本价
def calc_stock_new_cost(add_buy_amount,add_buy_unit_cost):
# 补仓买入成本
buy_stock_cost = add_buy_amount*add_buy_unit_cost
# 补仓后总投入股票成本 = 现数量 * 现成本单价 + 新数量 * 新成本单价
new_stock_cost = current_amount * current_unit_cost + buy_stock_cost
... |
# coding=utf-8
# Copyright 2017 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 os
from pant... |
#! /usr/bin/python
# usage: python topics.py [beta-file] [vocab-file] [num words] [result-file]
#
# [beta-file] is output from the dln-c code
# [vocab-file] is a list of words, one per line
# [num words] is the number of words to print from each topic
# [result-file] is file to write top [num words] words
import sys... |
# Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
import matplotlib.pyplot as plt
import pandas as pd
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--log-file', '-l', default='reward.log', type=str,
help='reward log file name')
args = parser.parse_args()
df = pd.read_csv(args.log_file)
x = df.columns[0]
y = df.columns[1]... |
###
# Copyright 2015-2019, Institute for Systems Biology
#
# 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 la... |
from enum import IntEnum;
from struct import unpack_from;
try:
from OgreHardwareBuffer import OgreFakeHardwareBuffer
except ImportError as e:
directory = os.path.dirname(os.path.realpath(__file__));
print("Import error: " + str(e) + " manual compilation" );
srcfile="OgreHardwareBuffer.py"; exec(compile... |
import signal
import logging
import email
import os
import time
from datetime import datetime
from email.policy import default
from paho.mqtt import publish
from emqtt.plugins import EmailProcessor
from emqtt.plugins import PluginManager
from emqtt.mqtt import mqtt_packet
log = logging.getLogger('emqtt')
class EMQT... |
"""A standard Weasel menu providing functions to download and upload DICOM data from/to XNAT."""
def main(weasel):
menu = weasel.menu("XNAT")
menu.item(
label = 'Download DICOM from XNAT',
tooltip = 'Prompts the user to choose the images to download from XNAT',
icon = 'Docum... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import sys
from datetime import datetime
from awsglue.transforms import ApplyMapping, SelectFields, ResolveChoice
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue... |
# THIS FUNCTION ALLOWS TO PARSE A CIGAR SEGMENT CONTAINING ONLY DELETED BASES AND INCREMENT
# A SPECIFIC PILEUP DICTIONNARY ACCORDINGLY
#
# INPUT : -PILEUP : (DICT) THE DICTIONNARY CONTAINING COUNTERS THAT ARE CHROMOSOME-POSITION-BASE-STRAND SPECIFIC
# -UMI : (STR) UMI SEQUENCE OF THE REA... |
import jwt
from . import GopublishTestCase
class TestApiToken(GopublishTestCase):
def test_get_token_no_body(self, client):
"""
Get token without a body
"""
url = "/api/token/create"
response = client.post(url)
assert response.status_code == 400
assert r... |
"""Support for WiLight Fan."""
from __future__ import annotations
from pywilight.const import (
FAN_V1,
ITEM_FAN,
WL_DIRECTION_FORWARD,
WL_DIRECTION_OFF,
WL_DIRECTION_REVERSE,
WL_SPEED_HIGH,
WL_SPEED_LOW,
WL_SPEED_MEDIUM,
)
from homeassistant.components.fan import DIRECTION_FORWARD, Fa... |
def _fix_fracs(string):
substrs = string.split("\\frac")
new_str = substrs[0]
if len(substrs) > 1:
substrs = substrs[1:]
for substr in substrs:
new_str += "\\frac"
if substr[0] == "{":
new_str += substr
else:
try:
... |
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
FILES = ['send_log.txt', 'recv_log.txt']
if __name__ == '__main__':
send_list = []
recv_list = []
file_handles = {filename: open(filename, 'r') for filename in FILES}
while 1:
for filename, fi in file_h... |
#!/usr/bin/env python
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
app = Flask(__name__)
api = Api(app, prefix="/api/v1")
# subscriber key value store
subscribers = {}
class Subscriber(Resource):
parser = reqparse.RequestParser()
parser.add_argument("email", type=str, r... |
class EventWaitHandleAuditRule(AuditRule):
"""
Represents a set of access rights to be audited for a user or group. This class cannot be inherited.
EventWaitHandleAuditRule(identity: IdentityReference,eventRights: EventWaitHandleRights,flags: AuditFlags)
"""
@staticmethod
def __new__(self,identity,even... |
__author__ = "jalfaizy"
# code for https://www.hackerrank.com/challenges/handshake
#!/bin/python
import sys
T = int(raw_input().strip())
for a0 in xrange(T):
N = int(raw_input().strip())
ans = (N*(N - 1))/2
print ans
|
#!/bin/env python
#
# -*- coding: utf-8 -*-
#
# Copyright (C) University of Manchester 2012
# Julian Selley <j.selley@manchester.ac.uk>
################################################################################
"""
Test Enzyme Module
******************
This is a test suite for the enzyme module. I... |
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from rest_framework.mixins import ListModelMixin... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2014 Mag. Christian Tanzer All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# ****************************************************************************
# This module is part of the package MOM.DBW.
#
# This module is licensed under the ter... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import matplotlib as mpl
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
from ..cache import get_memory
from ..cache.cloudpickle_backend import register... |
# @lint-ignore-every PYTHON3COMPATIMPORTS
from .linear_relu import LinearReLU
from .conv_relu import ConvReLU2d, ConvReLU3d
__all__ = [
'LinearReLU',
'ConvReLU2d',
'ConvReLU3d',
]
|
from time import sleep
import dbus
class Spotify:
def __init__(self):
try:
self.spotify_bus = dbus.SessionBus().get_object("org.mpris.MediaPlayer2.spotify",
"/org/mpris/MediaPlayer2")
except:
self.isSpotifyPlaying = False
else:
self.isSpot... |
# encoding=utf-8
from nltk.corpus import stopwords
from sklearn.preprocessing import LabelEncoder
from sklearn.pipeline import FeatureUnion
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.cross_validation import KFold
from sk... |
# -*- coding: utf-8 -*-
import logging
import smtplib
from contextlib import contextmanager
from functools import wraps
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
from etutorservice.utils.config_helper import c... |
class Solution:
def canReach(self, arr: List[int], start: int) -> bool:
result:bool = False
def DFS(arr: [], index: int):
nonlocal result
if arr[index] == -1:
return
elif arr[index]... |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 7 14:50:11 2018
@author: mahsayedsalem
"""
from imblearn.under_sampling import RandomUnderSampler
import numpy as np
import os
from random import shuffle
import cv2
from keras.utils.np_utils import to_categorical
import gc
from tqdm import tqdm
import warnings
warnings... |
from random import choice
from typing import Dict, List, Tuple
import numpy as np
import pandas
from hts._t import MethodT, NAryTreeT
from hts.hierarchy import make_iterable
def to_sum_mat(ntree: NAryTreeT) -> Tuple[np.ndarray, List[str]]:
"""
This function creates a summing matrix for the bottom up and opt... |
# Get input
import glob
import CSGM.dcgan.dcgan_utils as dcgan_utils
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
def mnist_data(hparams, num_batches):
# mnist = input_data.read_data_sets('./data/mnist', one_hot=True)
"""Create input tensors"""
image_paths = glob.glob(hparams... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
# coding=utf-8
import sys
import os
import glob
import re
import numpy as np
import tensorflow as tf
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
# Keras
from tensorflow.keras.applications impo... |
# coding: utf-8
import gym
import numpy as np
import xtools as xt
import xtools.simulation as xs
from .base import BaseEnv
from ..models.lvaircraft import LVAircraftEx
class LVAircraftAltitudeV0(BaseEnv):
def __init__(
self,
dt,
range_target=[-2000, 2000],
samplin... |
import pandas as pd
from sklearn.model_selection import train_test_split
import joblib
import lightgbm as lgb
import numpy as np
import os
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV
from sklearn.ensemble import BaggingClassifier
from sklearn.neighbors impo... |
# -*- coding: utf-8 -*-
import logging
from django.test.client import Client
from mock import patch
from networkapi.api_vip_request.models import VipRequest
from networkapi.api_vip_request.serializers.v3 import VipRequestV3Serializer
from networkapi.api_vip_request.tasks.deploy import deploy
from networkapi.test.test... |
print()
print("Which Ted Lasso character are you?")
teastr = input("Do you like tea? (y/n) ")
optimiststr = input("Are you an optimist? (y/n) ")
print()
if (teastr == "y") & (optimiststr == "y"):
print("You are Becks!")
elif (teastr == "y") & (optimiststr == "n"):
print("You are Roy!")
elif (teastr == "n") &... |
from rest_framework.test import APITestCase
from rest_framework.test import APIRequestFactory
from polls import apiviews
class TestPoll(APITestCase):
def setUp(self):
self.factory = APIRequestFactory()
self.view = apiviews.PollViewSet.as_view({'get': 'list'})
self.uri = '/polls/'
def... |
import argparse
import dill as pickle
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.ticker import FormatStrFormatter
from nes.ensemble_selection.config import BUDGET, PLOT_EVERY
matplotlib.use("Agg")
import os
from pathlib import Path
import numpy as np
import pandas as pd
plt.rcParams['axes.grid... |
from flask import Blueprint, render_template
errors= Blueprint('errors', __name__)
#There's also a method called errorhandler() but we aren't using it as it would only be applicable for this blueprint.
#Our main goal is to enable the error handlers throughout the application.
@errors.app_errorhandler(404)
def erro... |
"""Sanity check image sizes and svg viewboxes."""
from PIL import Image
from pathlib import Path
from lxml import etree
def _check_image(base_dir, image_dir):
assert image_dir.is_dir()
expected_size = (int(image_dir.name), int(image_dir.name))
num_bad = 0
num_good = 0
for image_file in image_dir.iterdir():
wi... |
"""View of QuotaWindowView."""
from gi.repository import Gtk
from lib.mvc.bases import WindowViewBase
from lib.exception_feedback import add_default_exception_handling
class QuotaWindowView(Gtk.Window, WindowViewBase):
"""View of QuotaWindowView."""
def __init__(self, app, model):
"""Ctor of QuotaWi... |
from hippy.builtin_klass import wrap_method
from hippy.builtin import ThisUnwrapper, Optional
from hippy.klass import def_class
from hippy.objects.base import W_Root
from hippy.objects.instanceobject import W_InstanceObject
from hippy import consts
class W_ApplevelArrayIterator(W_InstanceObject):
pass
@wrap_met... |
"""Module for Genomic DelIns Translation."""
from variation.translators.translator import Translator
from variation.schemas.classification_response_schema import ClassificationType
from variation.schemas.token_response_schema import GenomicDelInsToken
class GenomicDelIns(Translator):
"""The Genomic DelIns Transla... |
# -*- coding: utf-8 -*-
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
from sklearn_porter import Porter
iris_data = load_iris()
X = iris_data.data
y = iris_data.target
clf = KNeighborsClassifier(algorithm='brute',
n_neighbors=3,
... |
"""Add indexes to models
Revision ID: 440a8a3c0d96
Revises: 4d1e2e13e514
Create Date: 2020-02-04 17:15:37.150756
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "440a8a3c0d96"
down_revision = "4d1e2e13e514"
def upgrade():
op.create_index(
"idx_component_builds_build_id_n... |
from .bars import *
from .feature_mat import *
from .frac_diff import *
from .filters import * |
import unittest
import ray
from ray.rllib.agents.dqn import DQNTrainer, DEFAULT_CONFIG
from ray.rllib.utils.test_utils import check, framework_iterator
class TestPolicy(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
... |
from check.serializers import PingSerializer, PongSerializer
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
class PongViewSet(ListAPIView):
serializer_class = PongSerializer
message = "PING: The API is running!"
def get(self, format=None):
return Resp... |
import unittest
import xmlrunner
def runner(output='python_test_xml'):
return xmlrunner.XMLTestRunner(
output=output
)
def find_test():
return unittest.TestLoader().discover('pystache')
if __name__=='__main__':
runner().run(find_tests()) |
D = float(input('Qual é a distância da sua viagem?'))
print(f'Você está prestes a começar uma viagem de {D:.1f}Km')
if D > 200:
print(f'E o preço da sua passagem será de R${D*0.45:.2f}')
else:
print(f'E o preço da sua passagem será de R${D*0.50:.2f}')
|
from typing import Dict, Any
import copy
class Label(object):
def __init__(self, raw_label: Dict[str, Any]):
self._raw = copy.deepcopy(raw_label)
def name(self) -> str:
return self._raw["name"]
def to_raw(self) -> Dict[str, Any]:
return copy.deepcopy(self._raw)
|
lst = ["Москва", "Санкт-Петербург", "Тверь", "Казань"]
print(lst)
print(lst[1:3])
lst2 = lst[2:4]
print(lst2)
lst3 = lst[-2:-1] # правая граница не входит
print(lst3)
# создается ли копия списка
c = lst[:]
print(c, id(c))
print(lst, id(lst))
print("Создание списка через функцию-конструктор list(lst): ")
c = list(lst... |
import numpy as np
import pytest
from psydac.core.bsplines import make_knots
from psydac.fem.basic import FemField
from psydac.fem.splines import SplineSpace
from psydac.fem.tensor import TensorFemSpace
from psydac.fem.vector import ProductFemSpace
from psydac.feec.derivatives import Direct... |
# DROP TABLES
songplay_table_drop = "DROP TABLE IF EXISTS songplays"
user_table_drop = "DROP TABLE IF EXISTS users"
song_table_drop = "DROP TABLE IF EXISTS songs"
artist_table_drop = "DROP TABLE IF EXISTS artists"
time_table_drop = "DROP TABLE IF EXISTS time"
# CREATE TABLES
songplay_table_create = ("""
CREATE TABLE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.