content stringlengths 5 1.05M |
|---|
from typing import Dict, List, Tuple
import torch
import torch.nn as nn
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from ..base import Individual
import numpy as np
from sklearn.metrics import mean_squared_error
@torch.no_grad()
def evaluation_func(individuals:List[Individual], model:nn.Module, la... |
from typing import List
from structures import TreeNode
def sortedArrayToBST(nums: List[int]) -> TreeNode:
if len(nums) == 0:
return None
l, r = 0, len(nums) - 1
mid = l + (r-l) // 2
root = TreeNode(nums[mid])
root.left = sortedArrayToBST(nums[:mid])
root.right = sortedArrayT... |
import boto3
from auditMeth import printColor
from auditMeth import setAnsible
class ProviderContext(object):
_provider_name = ''
def __init__(self, session, account_id,mthread, ansible):
"""
:type session: boto3.Session
"""
self._report_items = []
self._session ... |
#!/usr/bin/env python3
import socket
import time
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
# Enable port reusage so we will be able to run multiple clients and servers on single (host, port).
# Do not use socket.SO_REUSEADDR except you using linux(kernel<3.9): goto https://stackov... |
import asyncio
import pytest
import weakref
from opentrons.hardware_control.modules import ModuleAtPort
from opentrons.hardware_control.thread_manager import (
ThreadManagerException,
ThreadManager,
)
from opentrons.hardware_control.api import API
def test_build_fail_raises_exception():
"""
Test that... |
import time
import numpy as np
from sklearn.metrics import roc_auc_score, average_precision_score, ndcg_score
import networkx as nx
import csv
from rw2 import ParallelRW2 as RW2
import pickle
import itertools
def load_graph(path):
H = nx.read_edgelist(path)
temp = sorted(H.nodes())
mapping = {k: i for i, ... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""
This script is a tutorial sample script to explain how all the benchmark
scripts are structured and standardized using the `RunnableScript` helper class.
We've numbered the steps you need to modify and adapt this sample script
to your own ne... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
##
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache Licen... |
from .bfp import BFP
from .fpn import FPN
from .fpn_carafe import FPN_CARAFE
from .hrfpn import HRFPN
from .nas_fpn import NASFPN
from .nasfcos_fpn import NASFCOS_FPN
from .pafpn import PAFPN
from .attff import ATTFF
from .attff2 import ATTFF2
from .fpn_bu import FPNBU
from .fpn_denoise import FPNDENOISE
from .fpn_deno... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
###
# File: data.py
# Created Date: Friday, April 17th 2020, 11:11:26 am
# Author: Amelia Villegas-Morcillo
#
# Copyright (c) 2020 Amelia Villegas-Morcillo
###
import copy
import torch
class Data(object):
"""A plain old python object modeling the attributes.
Arg... |
from config import constants
from utils import logutils
from news.searchnews import NewsDataIngestion
logger = logutils.get_logger("News Fetch")
def news_fetch_and_persist():
news_search_agent = NewsDataIngestion()
for product, search_query_list in constants.PRODUCT_SEARCH_QUERY_DICT.items():
for sea... |
import sys
import os
import random
import pygame as pg
from sounds import set_sound
# Variables
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720
BALL_SIZE = 30
PADDLE_WIDTH = 10
PADDLE_HEIGHT = 140
BALL_SPEED_X = 0.1
BALL_SPEED_Y = 0.1
OPPONENT_SPEED = 10
RGB_GRAY = (200, 200, 200)
RGB_BLACK = (0, 0, 0)
FPS = 60
MS_PER_... |
import json
from overrides import overrides
from typing import List
from repro.data.dataset_readers import DatasetReader
from repro.data.types import InstanceDict
@DatasetReader.register("sacrerouge")
class SacreROUGEDatasetReader(DatasetReader):
@overrides
def _read(self, *input_files: str) -> List[Instance... |
# Copyright (c) 2020 SMHI, Swedish Meteorological and Hydrological Institute.
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
"""
Created on 2020-04-07 10:54
@author: a002028
"""
import yaml
from sirena import utils
class YAMLreader(dict):
"""Read yaml files."""
def load_yaml... |
# Generated by Django 2.0.1 on 2018-01-02 22:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Genre',
fields=[
... |
"""Rename table to 'people'
Revision ID: 759aa532ee97
Revises: 08fe671e3702
Create Date: 2020-09-11 15:00:52.748073
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '759aa532ee97'
down_revision = '08fe671e3702'
branch_la... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Define the smartphone and tablet interface.
These interfaces allows you to get sensor values sent with your phone or tablet, and values returned by the
corresponding (Android / IPhone) application.
"""
from pyrobolearn.tools.interfaces import InputOutputInterface
__a... |
import csv
import json
from collections import OrderedDict
csvfile = open('./pokedexV2.csv', 'r')
jsonfile = open('./pokedexV2.json', 'w')
jsonNames = ("orderID", "nDex", "name", "types", "abilities", "stats", "note", "tier", "image")
reader = csv.DictReader(csvfile, jsonNames)
jsonordered = [OrderedDict(sorted(item... |
#
# Licensed Materials - Property of IBM
#
# (c) Copyright IBM Corp. 2007-2008
#
import unittest, sys
import ibm_db
import config
from testfunctions import IbmDbTestFunctions
class IbmDbTestCase(unittest.TestCase):
def test_042_FetchTupleMany_02(self):
obj = IbmDbTestFunctions()
obj.assert_expect(self.r... |
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
from chainalytic.common import config, rpc_client
from chainalytic.common.util import get_child_logger
class BaseKernel(object):
"""
Base class for different Kernel implementations
Properties:
working_dir (str):
zone_id (... |
#!/usr/bin/env python
r"""
Run an experiment consisting of multiple model runs based on the passed
- `config_builder`, which describes DAG and configs
- `experiment_builder`, which describes the model driver
# Run an RH1E pipeline using 2 threads:
> run_experiment.py \
--experiment_builder "core.dataflow_model.mas... |
# Generated by Django 3.0.4 on 2020-03-23 17:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('bookings', '0004_book_a_table'),
]
operations = [
migrations.AddField(
model_name='book_a_room',
name='room',
... |
from django.contrib.auth.base_user import BaseUserManager, AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.db import models
class UserManager(BaseUserManager):
def create_superuser(self, email, password, **kwargs):
kwargs.setdefault('is_staff', True)
kwargs.s... |
# You need to find the largest value in each row of a binary tree.
#
# Example:
#
# Input:
#
# 1
# / \
# 3 2
# / \ \
# 5 3 9
#
# Output: [1, 3, 9]
#
#
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val =... |
# -*- coding: utf-8 -*-
'''
File name: code\uphill_paths\sol_411.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #411 :: Uphill paths
#
# For more information see:
# https://projecteuler.net/problem=411
# Problem Statement
'''
Let n be ... |
# -*- coding: utf-8 -*-
#
# Tencent is pleased to support the open source community by making QTA available.
# Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the BSD 3-Clause License (the "License"); you may not use this
# file except in compliance with the License. You may ... |
# Generated by Django 3.1.5 on 2021-05-31 14:58
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('operations', '0001_initial'),
migr... |
def leiaint(msg):
while True:
try:
n=int(input(msg))
except (ValueError, TypeError):
print("\033[31mERRO: Por Favor,Digite um Numero Inteiro Valido.\033[m ")
continue
except (KeyboardInterrupt):
print("\033[31m Usuario Preferiu não Digitar\033[... |
from django.db import IntegrityError
from django.test import TestCase
from .models import (Kingdom,
Node,
Property,
PropertyStation,
Resource,
Territory)
from crafting.models import Material, Station
class Kingdo... |
import shutil
import os
import re
import fileinput
def deleteFromTo(dir, path):
for j in range(1, len(dir)+1):
selectedDir = dir[j-1]
entirePath = "{}{}".format(path, selectedDir)
print(selectedDir)
for i in range(len([name for name in os.listdir(entirePath)])): #loop for number of ... |
import logging
import symbol
from collections import OrderedDict
from typing import List, Tuple
import torch
from lark import Lark
from lark.grammar import Terminal, Rule
logger = logging.getLogger(__name__)
RULES = List[Tuple[int, List[int]]]
class Grammar:
def __init__(self, lark_file_path: str, *, lark_sta... |
from setuptools import setup, find_packages
setup(
name='download_spotify_playlist',
version='1.0',
description='Script to download your spotify playlists',
author="Ashish Madeti",
author_email="ashishmadeti@gmail.com",
install_requires=[
'youtube_dl',
'eyed3',
'requests... |
import sqlite3
class DatabaseManager:
def __init__(self, database_file):
self.conn = sqlite3.connect(database_file, check_same_thread=False)
def __del__(self):
self.conn.commit()
self.conn.close()
def get_cursor(self):
return self.conn.cursor()
def commit(self):
... |
from beluga.problem2 import *
def test_problem():
p = Problem('test_problem')
assert p.name == 'test_problem'
p.add_dynamic_element('x','v*cos(theta)','s',element_kind='states',
element_props=['name','eom','unit'])
assert p._systems['default'] == {'states':
... |
from distutils.core import Extension, setup
setup(
name="ctypes_example",
version="1.0",
description="ctypes example",
author="Mateen Ulhaq",
author_email="mulhaq2005@gmail.com",
maintainer="mulhaq2005@gmail.com",
url="https://github.com/YodaEmbedding/experiments",
ext_modules=[
... |
import cv2 as cv
import numpy as np
first_frame = None
video = cv.VideoCapture(0)
while True:
check,frame = video.read()
gray = cv.cvtColor(frame,cv.COLOR_BGR2GRAY)
gray = cv.GaussianBlur(gray,(21,21),0)
if first_frame is None:
first_frame = gray
continue
delta_frame = c... |
import pytest
from scrapping_asyncio.entities.task import Status
@pytest.fixture
async def task_in_repo(task, tasks_repo):
tasks_repo.tasks[task.id] = task
return task
@pytest.mark.asyncio
async def test_get_tasks(scrapping_service, task_in_repo):
tasks = await scrapping_service.get_tasks
assert ta... |
"""
Non-overriding descriptor (a.k.a. shadowable descriptor):
>>> o = Model()
>>> o.nonover # doctest: +ELLIPSIS
--> NonOverriding.__get__ invoked
'value of an attribute in instance <descriptorkinds.Model object at 0x...>'
>>> Model.nonover # doctest: +ELLIPSIS
--> NonOverriding.__get__ inv... |
#standard
import argparse
import os
#local
from GTFileReader import Trajectories
from readlinks import read_intersection_file, read_intersection_cycle_file, read_signal_controllers_file, read_greentimes_file
from TCACore import Timer
QUEUE_START_SPEED = 0.0
QUEUE_FOLLOWING_SPEED = 10.0 #ft/s
QUEUE_HEADWAY_DISTANC... |
# Copyright (c) 2018 Chenrui Lei
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
"""A bunch of stuff useful for glyph name comparisons and such.
1. A group of sorted glyph name lists that can be called directly:
2. Some tools to work with glyph names to do things like build control strings."""
import string
######################################################
# THE LISTS
######################... |
import re
from utils.input import load_lines
def in_memory_size(line: str) -> int:
char_pattern = re.compile(r"\\\\|\\\"|\\x[0-9a-f]{2}")
line = line[1:-1]
line = char_pattern.sub("a", line)
return len(line)
if __name__ == "__main__":
total_diff = 0
for l in load_lines():
total_diff... |
# -*- coding: utf-8 -*-
# Copyright 2021 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
The utils file for all netaddr tests
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.errors import AnsibleError
f... |
n = int(input('Digite o número da tabuada que você deseja:'))
print('_______TABUADA DO {} ________'.format(n))
print(n, 'x 1', n)
x = n * 2
print('| {} x 2 = {} |'.format(n, x))
print('-----------------------')
x = n * 3
print('| {} x 3 = {} |'.format(n, x))
print('-----------------------')
x = n * 4
... |
API_KEY = "your key here"
SECRET_KEY = "your key here" |
from abc import ABCMeta, abstractmethod
from typing import List, Optional, Set, Union
from . import EnumValidator, JsonObject, JsonValidator, extract_json
from .objects import DynamicSelectElementTypes, Option, OptionGroup
TextElementSubtypes = {"email", "number", "tel", "url"}
class DialogTextComponent(JsonObject,... |
DEBUG = False
CSV_DELIMITER = ','
CSV_QUOTECHAR = '"'
DATA_ROOT = '/srv/data'
HEDGE_DETECTION_THRESHOLD = 0.8
STORAGE_PATH = '/mnt/tension_analysis_results'
USER_IDENTIFICATION_COOKIE_NAME = 'uid'
import logging # noqa
logger = logging.getLogger('tension_analysis')
logger.setLevel(logging.INFO)
|
__author__ = 'Edward J. C. Ashenbert'
import math
class PVector:
def __init__(self, *args, **kwargs):
if len(args) == 2:
self.x = args[0]
self.y = args[1]
else:
self.x = 0
self.y = 0
self.isVector = True
def add(self, a):
try:
... |
from datetime import datetime
description = "This is a dummy job used by the Urd examples."
options = dict(timestamp=datetime)
jobs = ('previous',)
def synthesis():
pass
|
def process_input(file_contents):
temp = dict()
for i, line in enumerate(file_contents):
for j, seat in enumerate(line):
if seat != '\n':
temp.update({(0,0,i,j) : seat})
return temp, len(file_contents)
# Helper function to visualize room in the command line
def visuali... |
#! /usr/bin/env python
# pylint: disable=unused-wildcard-import
from util import *
def parse(inp):
lines = inp.splitlines()
return lines[0], [(rule[0], rule[0][0] + rule[1] + rule[0][1]) for rule in structured(lines[2:], (str, None, str))]
def step2(rules, counts):
counts_pairs = counts[0]
ncounts_pai... |
'''
Copyright 2020 Xilinx Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softw... |
from clutch.method.typing.session.shared import SessionArguments
SessionAccessorArguments = SessionArguments
SessionAccessorResponse = SessionArguments
|
import tangelo
tangelo.paths(".")
import compute
@tangelo.types(dataSet=compute.dataSet, column=int, row=int, plate=int, exemplars=compute.exemplarDict, probes=compute.objectDict)
def run(dataSet, column, row, plate, exemplars, probes):
return compute.objectFeatureValues(dataSet, column, row, plate, exemplars, pro... |
import os
from pandaharvester.harvestercore import core_utils
from pandaharvester.harvestersweeper.base_sweeper import BaseSweeper
from pandaharvester.harvestermisc.k8s_utils import k8s_Client
# logger
baseLogger = core_utils.setup_logger('k8s_sweeper')
# sweeper for K8S
class K8sSweeper(BaseSweeper):
# constr... |
from math import pi
shape = str(input("Which shape are you interested in? \nPossibilities: sphere, triangle, rectangle, circle: "))
shape = str.lower(shape) #Makes sure that the input is in lowercase so that it can be compared later
# This program could have used a switch statement, but for assignment 1 if statements... |
import logging
from typing import List, Tuple
import backoff
import sqlalchemy.exc
from climsoft_api.api.instrumentinspection import (
schema as instrumentinspection_schema
)
from climsoft_api.utils.query import get_count
from fastapi.exceptions import HTTPException
from opencdms.models.climsoft import v4_1_1_core ... |
from typing import Union
from yarl import URL
import libkol
from ..Error import (
AlreadyCompletedError,
InvalidUserError,
ItemNotFoundError,
UnknownError,
UserInHardcoreRoninError,
UserNotFoundError,
WrongKindOfItemError,
)
from .request import Request
class curse(Request[bool]):
d... |
"""
Copyright [2009-2019] EMBL-European Bioinformatics 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 a... |
from django.shortcuts import render
from django.views import generic
from .forms import SignUpForm, EditProfileForm, PasswordChangingForm
from django.urls import reverse_lazy
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.views import PasswordChangeView
# Create your views here.
cla... |
# -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this sof... |
from django import forms
from .models import Team, Tournament, Match, Score
from player.models import Player
from performance.models import BattingInnings, BowlingInnings
class TeamCreationForm(forms.ModelForm):
logo = forms.ImageField(required=False)
class Meta:
model = Team
fields = [
... |
"""
Copyright (C) <2010> Autin L. TSRI
This file git_upy/autodesk3dsmax/v2015/maxHelper.py is part of upy.
upy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the Li... |
#!/usr/bin/env python3
# ---------------------------------------------------------------------------- #
# DegNorm CLI entrypoint for distributed pipeline run.
# ---------------------------------------------------------------------------- #
try:
from mpi4py import MPI
except ImportError as e:
raise e
from deg... |
'''
Extract headers from a corpus,
Filter header before generating feature vectors
Format of _header_valid.csv:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Columns: Descriptions
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Locator ... |
"""
Rendering-agnostic tools for animations.
Conceptually, an animation on type A consists of two parts:
- a duration (float)
- a projector (float -> A)
A projector is a function from [0; 1] to an element of type A. It transforms
the "progress" (a number from 0 to 1 inclusively) of the animation to a still
frame of t... |
from benchmark_django_rest_framework.benchmark_api_view import BenchmarkAPIView
from django.http import HttpResponse
from apps.common.jigsaw_trouserdrop.id_code import ValidationCode
import os
class IdCodeView(BenchmarkAPIView):
'''
获取验证码图片
'''
access = {'get': 'all', 'post': None, 'put': None, 'dele... |
from ..utils import TranspileTestCase
from unittest import expectedFailure
class WithLoopTests(TranspileTestCase):
def test_with(self):
self.assertCodeExecution("""
class CtxMgr:
def __enter__(self):
print('entering CtxMgr')
return 42
... |
from .base import Base
import os
class Dbpw(Base):
"""Generates Database PW from AWS"""
def run(self):
os.system("aws ssm get-parameter --name \"/local/CFG_MYSQL_MASTER_PASS\" --with-decryption --query 'Parameter.Value' --output text")
|
from occupant import EmergencyOccupant
from fire import FireControl
import random
import datetime as dt
from soba.models.continuousModel import ContinuousModel
from time import time
import time as sp
from ast import literal_eval as make_tuple
import listener as lstn
from avatar import EmergencyAvatar
from sob... |
import collections
class Solution:
# @param {int} n a positive integer
# @return {int[][]} n x 3 matrix
def consistentHashing(self, n):
# Write your code here
res = [0,359,1]
q = collections.deque()
q.append(res)
k = 1
while n > 1:
k += 1
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
QSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems
This module is developed by:
Yalin Li <zoe.yalin.li@gmail.com>
This module is under the University of Illinois/NCSA Open Source License.
Please refer to https://github.com/QSD-G... |
# Copyright 1996-2021 Cyberbotics Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
# -*- coding: utf-8 -*-
from .AbstractVariantOperations import AbstractVariantOperations
from .Variant import Variant
from .VariantType import VariantType
class TypeSafeVariantOperations(AbstractVariantOperations):
"""
Implements a strongly typed (type safe) variant operations manager object.
"""
de... |
"""ESXi Stats Integration."""
import asyncio
import logging
import os
from datetime import datetime, timedelta
from .esxi import (
esx_connect,
esx_disconnect,
check_license,
get_host_info,
get_datastore_info,
get_license_info,
get_vm_info,
vm_pwr,
vm_snap_take,
vm_snap_remove,
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sonarqube.config import (
API_METRICS_SEARCH_ENDPOINT,
API_METRICS_TYPES_ENDPOINT
)
class SonarQubeMetrics:
def __init__(self, sonarqube):
self.sonarqube = sonarqube
def get_metrics(self):
"""
Search for metrics
:return... |
from pathlib import Path
class MainPanel(object):
def __init__(inputmethod, dosomething):
a = input('$ { ')
if a == inputmethod:
print(dosomething)
def __attributes__(attr, removeCache: bool):
if removeCache == True:
a = Path("__pycache__")
if a.exists... |
import os
from typing import *
import torch
from mltk import StatefulObject, BaseCheckpoint
__all__ = ['Checkpoint']
class _TorchCheckpointableObject(StatefulObject):
"""Wraps a PyTorch checkpointable object into :class:`StatefulObject`."""
def __init__(self, torch_object):
self.torch_object = torc... |
import functools
import os.path
import typing
import cmd2
import fiepipelib.legalentity.authority.data.entity_authority
import fiepipelib.encryption.public.privatekey
import fiepipedesktoplib.shells.AbstractShell
import fiepipelib.storage.localvolume
from fiepipelib.storage.routines.localstorage import LocalStorageIn... |
# Copyright © VASP Software GmbH,
# Licensed under the Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import py4vasp.data._base as _base
from py4vasp.data import Structure
class BornEffectiveCharge(_base.DataBase):
"""The Born effective charge tensors coupling electric field and atomic displaceme... |
import sys
from pathlib import Path
import subprocess
print("Checking if VSIX exists at ", sys.argv[1])
my_file = Path(sys.argv[1])
if my_file.is_file():
print("VSIX correctly generated.")
else:
print("VSIX was not correctly generated.")
sys.exit(1) |
from PyQt5.QtWidgets import QLabel, QTextEdit
class UIB_Text_type:
def __init__(self, parent: object, key: str, value: dict):
self._p = parent
self._id = key
self._json = value
if self._json.get("title", ""):
title = QLabel(self._json.get("title", ""))
self... |
# coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from unittest import TestCase
import filters as f
from filters.test import BaseFilterTestCase
from cornode import cornode
from cornode.adapter import MockAdapter
from cornode.commands.core.add_neighbors import AddNei... |
"""Utilities for calculating / manipulating price data."""
from ..tools import stamps
from ..tools.nits import Q_
from typing import Tuple, Union
import pandas as pd
def is_peak_hour(
ts_left: Union[pd.Timestamp, pd.DatetimeIndex]
) -> Union[bool, pd.Series]:
"""
Boolean value indicating if a timestamp i... |
from rest_framework import generics
from rest_framework.response import Response
from products.models import Product
from products.serializers import ProductSerializer
from . import client
class SearchListView(generics.GenericAPIView):
def get(self, request, *args, **kwargs):
user = None
if reque... |
""" Copyright (c) Microsoft Corporation. All Rights Reserved. """
""" Licensed under the MIT license. See LICENSE file on the project webpage for details. """
import textwrap
import logging
LOG = logging.getLogger(__name__)
from const import OEMBED_SERVICES
import re
import urllib2
import json
import pyembed
EMBED_CO... |
class Solution:
def encode(self, longUrl):
# Encodes a URL to a shortened URL.
return longUrl
def decode(self, shortUrl):
# Decodes a shortened URL to its original URL.
return shortUrl
|
# AUTOGENERATED! DO NOT EDIT! File to edit: 02_figures.ipynb (unless otherwise specified).
__all__ = ['new_x_y', 'add_trace', 'get_figure']
# Cell
import plotly.graph_objects as go
import numpy as np
from scipy.interpolate import interp1d
import pandas as pd
from pathlib2 import Path
import datetime
# Cell
def new_x... |
from easysparql import easysparql
DBPEDIA_ENDPOINT = "https://dbpedia.org/sparql"
albert_uri = "http://dbpedia.org/resource/Albert_Einstein"
albert_name = "Albert Einstein"
scientist = "http://dbpedia.org/ontology/Scientist"
foaf_name = "http://xmlns.com/foaf/0.1/name"
classes = easysparql.get_classes(albert_uri, DB... |
#! /usr/bin/python
# -*-coding:utf-8-*-
import MySQLdb
import json
update_sql = ""
select_sql = "SELECT * FROM t_task t WHERE t.`workflow_id` IN (925, 955, 967, 968)"
def getConnection(hostIp, username, password, dbName):
dbConnection = MySQLdb.connect(host=hostIp, user=username, passwd=password, db=dbName)
... |
import sys
from functools import singledispatch
import click
from kaos_cli.exceptions.exceptions import CommandError, SimpleApplicationError, WorkspaceExistsError, \
InvalidWorkspaceError, NoTrainingJobsError, NoNotebookError, NoServingJobsError
from kaos_cli.utils.environment import format_missing_command_error
... |
import torch.nn as nn
from .helper import init, make_standard_block
import torch
from .MobileNetV2 import InvertedResidual
class PAFModel(nn.Module):
def __init__(self, backend, backend_outp_feats, n_joints, n_paf, n_stages=6): #backend_outp_feats=128,n_joints=19,n_paf=34
super(PAFModel, self).__init__()... |
import argparse
import datetime
import os
import json
import random
import string
import requests
import io
from flymazerl.agents.neuralnetworks import GQLearner, GRNNLearner
from flymazerl.gym.environment import *
import numpy as np
import pandas as pd
start_text = """
++++++++++++++++++++++++++++++++++++++++++++++... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 The F4PGA Authors.
#
# Use this source code is governed by a ISC-style
# license that can be found in LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
"""
This file defines TimingAnalyzer class.
The TimingAna... |
from typing import Type
from eth_utils import decode_hex
from eth_keys import datatypes, keys
from evm.db.chain import AsyncChainDB, NonJournaledAsyncChainDB
from p2p import kademlia
from p2p.peer import BasePeer, HardCodedNodesPeerPool
class LocalGethPeerPool(HardCodedNodesPeerPool):
def __init__(self,
... |
# Copyright (C) 2021-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import os.path as osp
import tempfile
from os import remove
import mmcv
import numpy as np
import pytest
from ote_sdk.entities.annotation import (
Annotation,
AnnotationSceneEntity,
AnnotationSceneKind,
)
from ote_sdk.enti... |
import pytest
from ..multiply import multiply
@pytest.mark.parametrize("num_1, num_2, expected", [
(10, 2, 20),
(11, 4, 44),
(9, 3, 27)
])
def test_multiply(num_1, num_2, expected):
actual = multiply(num_1, num_2)
assert actual == expected
|
import os
from fhirzeug.fhirspec import (
FHIRSpec,
FHIRVersionInfo,
)
def test_writable_profiles(spec: FHIRSpec):
check = any(
item in spec.generator_config.manual_profiles
for item in spec.writable_profiles()
)
assert check is False
def test_read_version(spec: FHIRSpec):
... |
casa = float(input('Qual é o valor da casa que deseja financiar ? '))
sal = float(input('Qual seu salário ? '))
anos = int(input('Em quantos anos vc quer pagar ? ')) |
from corner_detector import find_corners_in_image
from corner_validator import validate_image_corners, validate_image_corners_using_completely_built_ipm
from warping_unit import warp_document, warp_document_using_ipm
from content_processor import process_document_content
first_frame = True
def scan(img, op... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.