content stringlengths 5 1.05M |
|---|
"""Component for the Portuguese weather service - IPMA."""
from .config_flow import IpmaFlowHandler # noqa: F401
from .const import DOMAIN # noqa: F401
DEFAULT_NAME = "ipma"
PLATFORMS = ["weather"]
async def async_setup_entry(hass, entry):
"""Set up IPMA station as config entry."""
hass.config_entries.asy... |
import time
import gs_rest_api_workspaces
from gs_rest_api_workspaces.rest import ApiException
from gs_rest_api_workspaces.model import Workspace
import logging
class WorkspaceAddTask(object):
def __init__(self, configuration, workspace_name):
self.configuration = configuration
self.workspace_nam... |
from phyton.constants import *
from phyton.vectors import *
class Location:
def __init__(self, M=ME, h=RE, μ=0):
self.M = Mass(M.value)
self.h = Displacement(0, h.value)
print(self.M, self.h)
self.μ = 0
@property
def g(self):
return Acceleration(0, -(G*f... |
from src.new_class import NewClass
def test_new_class():
instance = NewClass()
assert instance.a == 1
|
from NewDeclarationInQueue.processfiles.customprocess.search_text_line_parameter import SearchTextLineParameter
class TableConfigDetail:
upper: SearchTextLineParameter
lower: SearchTextLineParameter
header: SearchTextLineParameter
first_level: list
second_level: list
def __init__(sel... |
import pygame
from pygame.locals import *
from math import *
import random
import sys
import threading
class PlayerPaddle:
def __init__(self, image, left, top, alignment):
self.__image = pygame.image.load(image)
self.__rect = pygame.Rect(left, top, self.__image.get_size()[0], self.__image.get_size... |
# 0 -10000
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import tqdm
#生成文字检测数据集
# seed=42时,生成了 train 7156 | val 776
np.random.seed(42)
train_cnt = 0
val_cnt = 0
for i in tqdm.tqdm(range(1,10000+1)):
root = '/workspace/str/icdar/train/'
num = str(i)
while len(num) < 5:
... |
import torch
from torch import nn
from torch.nn import functional as F
from Utils.flags import FLAGS
import numpy as np
from torch.autograd import Variable
crossentropy = nn.CrossEntropyLoss()
softmax = nn.Softmax(1)
logsoftmax = nn.LogSoftmax(1)
# some utils TODO
def update_average(model_tgt, model_src, beta=0.999)... |
from splinter import Browser
from bs4 import BeautifulSoup as bs
import time
import requests
import pandas as pd
def init_browser():
# @NOTE: Replace the path with your actual path to the chromedriver
executable_path = {"executable_path": "/usr/local/bin/chromedriver"}
return Browser("chrome", **executable... |
import setuptools
with open('README.md', 'r') as fh:
long_description = fh.read()
setuptools.setup(
name='cleanse',
version='0.1',
license='MIT',
description='Replace sensitive xml data while maintaining its structure',
long_description=long_description,
author='Dalton Dirkson',
author... |
# %% Imports
import os
import glob
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
import seaborn as sns
from sklearn.linear_model import LinearRegression
from scipy.optimize import least_squares
from ruamel_yaml import Y... |
from lxml import etree as et
from utils import is_empty_string
# ############ RELATED #########################
def get_ns(tag):
'''Prefix tag with TEI namespace.'''
return r'{http://www.tei-c.org/ns/1.0}' + tag
# ################# MAIN #######################
def create_entry_parent_node(lemma):
'''Creat... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-09 19:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('writecode', '0002_descriptor_vowel'),
]
operations = [
migrations.CreateMod... |
import torch
from lib.config.paths import PATHS
# from .datasets.df import OpenWorldNoDef
from .datasets.coco import COCO
from .datasets.hpatches import Hpatches, HpatchesViewpoint, HpatchesIllum
from .evaluators.pck import DescPckEvaluator
class DatasetFactory:
def __init__(self, cfg):
self.cfg = c... |
import tensorflow as tf
import _pickle as pickle, sys
import sys
sys.path.insert(0,'./../')
from Housekeeping import *
class Load_BBB():
def __init__(self, controller_identity):
self.sess = tf.Session()
meta_information_directory_copycat = controller_identity + 'training/' + SAVED_FINAL_MODEL_DIRECTORY
best_m... |
import os
import pytest
from unittest import mock
import tempfile
import subprocess
from shutil import copytree, copyfile
from molotov import __version__
from molotov.slave import main
from molotov.tests.support import TestLoop, dedicatedloop, set_args
_REPO = "https://github.com/loads/molotov"
NO_INTERNET = os.envi... |
#!/usr/bin/python3.7
# UTF8
# Author: Nicolas Flandrois
# Description: Ici je cherche à grouper par valeur, selon une clé,
# des données venant d'une liste de disctionaires, afin d'en effectuer un compte.
import itertools
heroes = [
{
'name':'Batman',
'city':'Gotham',
'univers':'DC'
},... |
import argparse
import logging
import sys
from stackstrap.commands import CommandLoader, CommandError
from stackstrap.commands.create import Create
from stackstrap.commands.template import Template
from stackstrap import __version__
class StackStrapCLI(CommandLoader):
"""
The main CLI interface for StackStra... |
# Copyright 2020 Google LLC. 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 applicable law or a... |
from gd.typing import TYPE_CHECKING, Any, Optional, TypeVar
__all__ = (
"GDException",
"HTTPException",
"HTTPError",
"HTTPStatusError",
"ClientException",
"MissingAccess",
"SongRestricted",
"CommentBanned",
"LoginFailure",
"LoginRequired",
"NothingFound",
"... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="ipython-ngql",
version="0.4",
author="Wey Gu",
author_email="weyl.gu@gmail.com",
description="iPython and Jupyter Plugin for Nebula Graph",
long_description=long_desc... |
from pymongo import MongoClient
from gridfs import GridFS
from bson.objectid import ObjectId
from datetime import datetime
from os import environ
from const import RequestType
def GetAdminUsers(db=None):
if not db:
client = MongoClient('data', 27017)
db = client.aaf_db
admins = []
for admin... |
#!/usr/bin/env python3
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import torch
import pytest
import poptorch
# Random Number Generation Harness
# Checks that the IPU generated data with roughly the same summary statistics as the CPU version
def rng_harness(rng_op, stat_funs):
class Model(torch.nn.Mo... |
import sys
import config
import threading
import multiprocessing
import abc
import requests
import mysql.connector
import re
from html.parser import HTMLParser
if config.enable_images_optimisations:
import pyimglib
ENABLE_REWRITING = False
TRANSCODE_FILES = {'png', 'jpg', 'jpeg', 'gif', 'webm', 'svg'}
downlo... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-05-27 06:24
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('project_awards_app', '0004_auto_20190526_1857'),
]
o... |
# -*- coding: utf-8 -*-
import time
import datetime
class TimeUtil:
@staticmethod
def stamp_to_date(timestamp):
sdf = "%Y-%m-%d %H:%M:%S"
# 转换成localtime
time_local = time.localtime(timestamp)
# 转换成新的时间格式(2016-05-05 20:28:54)
return time.strftime(sdf, time_local)
@st... |
# -*- coding: utf-8 -*-
"""
Created on Oct 03 2015
Modified on Jan 2017 by Saúl Blanco
Modified on Jan 13, 2017, by Jerónimo Arenas
Modified on May 2018, by Jerónimo Arenas and Ángel Navia for MINECO project
@author: jarenas
"""
import os
import re
import sys
import nltk
from nltk import sent_tokenize
import langid
... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Compone... |
import math
import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import geometry as gm
import rtx
def load_texture_image(filename):
image = Image.open(filename)
image = image.convert("RGB")
texture = np.array(image, dtype=np.float32) / 255
return texture
... |
# Available indicators here: https://python-tradingview-ta.readthedocs.io/en/latest/usage.html#retrieving-the-analysis
from datetime import datetime
from tradingview_ta import TA_Handler, Interval, Exchange
# use for environment variables
import os
# use if needed to pass args to external modules
import sys
... |
class Environment:
def __init__():
pass
def reset():
pass
def step(action):
#should return
#returns observation, reward, done, _
pass
def close():
pass
|
# Copyright 2013-2021 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)
import os
from spack import *
class KokkosNvccWrapper(Package):
"""The NVCC wrapper provides a wrapper around NVCC t... |
from azureml.pipeline.steps import PythonScriptStep
class EvaluateStep:
def __init__(self, workspace, env, compute, config, pipeline_parameters):
self.workspace = workspace
self.env = env
self.compute = compute
self.config = config
self.pipeline_parameters = pipeline_parame... |
# -*- coding: utf-8 -*-
"""Rmarkdown readers and writers.
"""
# ------------------------------------------------------------------------------
# Imports
# ------------------------------------------------------------------------------
import re
import os.path
import json
import pypandoc
try:
import nbformat a... |
import nltk
from nltk.corpus import mac_morpho
from nltk.tag import UnigramTagger
from nltk.tag import DefaultTagger
from nltk.chunk import RegexpParser
from nltk.tree import *
from nltk.tokenize import RegexpTokenizer
from decimal import Decimal
from .models import Adverblist, Caractlist, Comments, Dictwords, Sentil... |
import time
now = time.strftime("%Y-%m-%d_%H-%M")
login = ''
password = r''
sender = login
received = ''
smtp_server = ''
port = 587
temat = f"Raport z backupu - {now}"
body = f''' To jest raport z backupu \n
Kopia z dnia - {now} \n
\n
Contact : \n
mail: biuro@tmask.pl \n
'''
|
#!/usr/bin/env python
"""Module to create concatemer per genome of orthologs, create a phylogenetic tree and deduce taxa from that tree."""
from Bio import AlignIO, Phylo, SeqIO
from shared import create_directory, parse_options, extract_archive_of_files, create_archive_of_files
from select_taxa import select_genomes_... |
#Write a Python program to split a variable length string into variables.
x = (30, 50, 60)
a, b, c = x
print(a, b, c) |
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import numpy as np
import os
import pickle
from mxnet.gluon.data import dataset
class Ngram_dataset(dataset.ArrayDataset):
'''
The ngram_dataset takes a noisy_forms_dataset object and converts it in... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.WGL import _types as _cs
# End users want this...
from OpenGL.raw.WGL._types import *
from OpenGL.raw.WGL import _errors
from OpenGL.constant import Constant as _C
import ctype... |
"""
Created on Sat May 23 18:17:31 2020
celebx = 'CC1=CC=C(C=C1)C2=CC(=NN2C3=CC=C(C=C3)S(=O)(=O)N)C(F)(F)F'
tiotixene = 'CN1CCN(CC1)CCC=C2C3=CC=CC=C3SC4=C2C=C(C=C4)S(=O)(=O)N(C)C'
Troglitazone = 'CC1=C(C2=C(CCC(O2)(C)COC3=CC=C(C=C3)CC4C(=O)NC(=O)S4)C(=C1O)C)C'
@author: akshat
"""
import selfies
... |
from rest_framework import serializers
from .models import App, User
class AppSerializer(serializers.ModelSerializer):
app_name = serializers.CharField(max_length=1000, required=True)
app_id = serializers.CharField(max_length=200, required=True)
category = serializers.CharField(max_length=1000, required=... |
import tensorflow as tf
import numpy as np
import ee
def feature_process(features):
"""Function that adds indexes to the features.
Args :
features : tensor
labels : tensor
Returns :
A tuple of (inputs, outputs).
"""
Blue = features[...,1]
Green = features[...,2]
... |
#!/usr/bin/python2
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import socket
import fcntl
import struct
import os
def window():
app = QApplication(sys.argv)
win = QDialog()
b1 = QPushButton(win)
b1.setText("Make Datanode")
b1.move(50,20)
b1.clicked.connect(b1_clicked)
win.setGe... |
from .comics import Comics
def setup(bot):
bot.add_cog(Comics(bot))
|
"""Class that handle client connections"""
import socket
import json
import select
from random import randint
from threading import Thread
UDP_PORT = 13702
TCP_PORT = 13703
class Client:
"""Class that handle client connections"""
def __init__(self):
self.udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
... |
from django.conf import settings
''' app and models in Wagtail instance '''
BLOG_APP = getattr(
settings, 'BLOG_APP', 'blog')
BLOG_PAGE_MODEL = getattr(
settings, 'BLOG_PAGE_MODEL', 'BlogPage')
BLOG_INDEX_PAGE_MODEL = getattr(
settings, 'BLOG_INDEX_PAGE_MODEL', 'BlogIndexPage')
|
"""
WSGI config for catch project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
from dotenv import load_dotenv
import os
from django.core.wsgi import get_wsgi_application
# if ... |
# coding: utf-8
# Aluno: Misael Augusto
# Matrícula: 117110525
# Problema: Inserção ordenada do último elemento de uma lista
def insere_ordenado_ultimo(lista):
for i in range(len(lista) - 1, 0, -1):
if lista[i] < lista[i - 1]:
lista[i], lista[i - 1] = lista[i - 1], lista[i]
else:
break
return lista
l1 =... |
#! /usr/bin/env python3
# -*-coding:utf-8 -*-
# @Time : 2019/06/18 21:13:49
# @Author : che
# @Email : ch1huizong@gmail.com
import subprocess
import datetime
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
def disk_report():
p = subprocess.Popen("df -h", shell=True, stdout=subproc... |
from sklearn.preprocessing import OneHotEncoder
import os
import numpy as np
from Neuron import Neuron
import provider
from keras import backend as K
from sklearn.preprocessing import MinMaxScaler as min_max_scaler
class neuron_dataset():
"""
-----2019/5/14-------heping----
read data from files,and proce... |
# @Author: Pieter Blok
# @Date: 2021-03-25 18:48:22
# @Last Modified by: Pieter Blok
# @Last Modified time: 2021-06-04 13:49:37
## t-SNE visualization of the box-features of Mask R-CNN
## t-SNE is a technique for dimensionality reduction for the visualization of high-dimensional datasets
## https://lvdmaaten.githu... |
import random
import re
import math
import discord
import yrumee.modules.gacha_params as params
from yrumee.modules import Module
from yrumee.modules import gacha_db
class GachaCard:
def __init__(self, number, season, rare, name, desc, imgurl):
self.number = number
self.season = season
... |
from dataset.data import *
from optim.regression import *
from utils.draw_tools import *
from utils.toolbox import LOGGER
from config.config import *
def reg_single(m, is_high, is_bad):
if is_bad:
LOGGER.info('Regression Model(Contain Bad Point, High Temp)')
save_path = SAVE_ROOT + 'reg_bad_m_' ... |
CHART_WIDTH = 600
CHART_HEIGHT = 400
TITLE_HEIGHT = 50
X_AXIS_HEIGHT = 50
Y_AXIS_WIDTH = 50
MARGIN = 20
TICKMARK_HEIGHT = 8
|
"""
This app module dispatches pre-configure or on-the-fly studies to user from a link request
that is redirected to the front-end which customizes its view
"""
# TODO: move here all studies_access.py
from .module_setup import setup_studies_dispatcher
|
from application import db
from application.models import Base
class Row(Base):
id = db.Column(db.Integer, primary_key=True)
product_num = db.Column(db.Integer, db.ForeignKey(
'product.number'), nullable=False, index=True)
product = db.relationship("Product")
qty = db.Column(db.Integer, nullab... |
from api.api import run
|
#!/usr/bin/env python3
import datetime
import os
import time
from typing import Optional
import cv2
import numpy as np
cap = cv2.VideoCapture(1)
# cap.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1)
xvid = cv2.VideoWriter_fourcc(*'XVID')
def main():
# Setup controls window
cv2.namedWindow('controls')
cv2.imshow('c... |
from typing import List, Tuple, Optional, Union
from .base import ConfigBase
class VectorizerConfig(ConfigBase):
# Convert all characters to lowercase or not
lowercase: bool = True
# If ‘english’, a built-in stop word list for English is used.
# If a list, that list is assumed to contain stop words, ... |
from utils.functions import old_to_new_points
from scipy.spatial import ConvexHull
from os import system
system('mkdir computed_results')
old_points = [(0,), (2,)]
for dimension in range(2, 7):
points = old_to_new_points(dimension, old_points)
hull = ConvexHull(points)
volume = hull.volume
# The c... |
def check_fermat(a, b, c, n):
if a**n + b**n == c**n:
print('Holy smokes, Fermat was wrong!')
else:
print("No, that doesn't work")
def get_input():
a = int(input('Please enter a value for a:'))
b = int(input('Please enter a value for b:'))
c = int(input('Please enter a value for c:'... |
#!/usr/bin/python
from beem import Hive
from beem.comment import Comment
from beem.account import Account
from beem.amount import Amount
from beem.blockchain import Blockchain
from beem.nodelist import NodeList
from beem.exceptions import ContentDoesNotExistsException
from beem.utils import addTzInfo, resolve_authorper... |
from django.contrib.auth.admin import UserAdmin
from .models import User
from django.contrib import admin
admin.site.register(User, UserAdmin)
|
"""Project domain module that defines different project domains."""
from enum import Enum
class ProjectDomains(Enum):
"""Defines a set of project domains."""
value: str
CHAT_CLIENT = "Chat client"
CODEC = "Codec"
COMPRESSION = "Compression"
C_LIBRARY = "C Library"
DATABASE = "Database"
... |
#WAPP sum of digits of given number
num = input("enter a number ")
n = int(num)
sum = 0
while n>0:
digit = n % 10
sum = sum + digit
n = n // 10
else:
print("Sum =",sum)
|
#
# Autogenerated by Thrift Compiler (0.15.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
from thrift.TRecursive impo... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
@author: ogouvert
"""
import numpy as np
def divide_train_test(Y,prop_test=0.2,seed=None):
np.random.seed(seed)
U,I = Y.shape
nnz = Y.nnz
mask = np.random.choice(nnz, size=int(nnz*prop_test), replace=False)
no_mask = np.asarray(list(set(... |
#!/usr/bin/env python3
from concurrent import futures
import grpc
from grpc_reflection.v1alpha import reflection
from wemmick import wemmick_pb2, wemmick_pb2_grpc
import wemmick.api
class Wemmick(wemmick_pb2_grpc.WemmickServicer):
def HealthCheck(self, request, context):
return wemmick_pb2.Response(messag... |
from setuptools import setup, find_packages
setup(
name='yanky',
version='0.9.0',
packages=['yanky'],
package_data={'': ['LICENSE']},
package_dir={'yanky': 'yanky'},
author='Josue Ortega',
author_email='josueortega@protonmail.ch',
description='Easy and Simple copy and paste module for GN... |
import os
import yaml
from github import Github
def load_github() -> Github:
with open(f'{os.path.expanduser("~")}/.config/hub') as hub_file:
hub_config = yaml.safe_load(hub_file)
return Github(login_or_token=hub_config['github.com'][0]['oauth_token'])
def print_current_rate_limit():
rate_l... |
import numpy as np
import simple_learning.grad.functional as F
from .module import Module
from .parameter import Parameter
__all__ = ['Linear']
class Linear(Module):
"""Apply an affine transformation (bias=True) or linear transformation (bias=False)
to a some input, where the weight matrix has its values ... |
import dis
import io
def compare_lines(t1, t2):
for l1, l2 in zip(t1.split('\n'), t2.split('\n')):
if 'LOAD_CONST' in l1:
# some small variation is OK
assert 'LOAD_CONST' in l2
else:
assert l1.strip() == l2.strip()
def test_asyncFor():
co = compile('''
async... |
import numpy as np
from numba import jit
@jit
def SOR1(md, p, ap, ae, aw, bb, m, p_exact, relax_factor):
eps = 1e-15 # convergence criterion
error1, error2, error3 = 0, 0, 0 # initialize parameters
p_old = np.zeros(md + 1)
''' SOR algorithm '''
iter_n = 1
while True:
error1 = 0 # ... |
r"""
Tables of elliptic curves of given rank
The default database of curves contains the following data:
+------+------------------+--------------------+
| Rank | Number of curves | Maximal conductor |
+======+==================+====================+
| 0 | 30427 | 9999 |
+------+---------... |
"""This module contains the general information for BiosVfBootOptionRetry ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class BiosVfBootOptionRetryConsts():
SUPPORTED_BY_DEFAULT_NO ... |
import sys
sys.path.append("../")
from DAL.CONN import labConn,bancoSQL
from LOG.logs_APP import logDatabase
import pandas as pd
'''
App conecta no banco de dados e printa os valores das colunas em uma tabela, e se ocorreu algum erro ele escreve este erro em um arquivo de LOG
'''
#configurando o los dos erros de ba... |
from lxml import etree
import numpy
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
import operator
import pandas as pd
import requests
import json
from collections import defaultdict, Counter
import re
###GET FF-ICF PER EVENT TYPE###
def frames_naf_predicate(path_to_doc, frame_to_info, ... |
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A test to confirm and set SKU information.
Description
-----------
A test to confirm SKU information, then apply SKU or model specific settings.
And t... |
from contextlib import closing
import pytest
from helpers import *
def test_404_if_stream_does_not_exists():
with pytest.raises(websocket.WebSocketBadStatusException) as err:
client_ws("/streams/" + random_stream())
assert err.value.status_code == 404
def test_401_if_stream_exists_and_invalid_tok... |
"""This module provides an interface to the program NACCESS."""
import subprocess
import tempfile
import os
def naccess_available():
"""True if naccess is available on the path."""
available = False
try:
subprocess.check_output(['naccess'], stderr=subprocess.DEVNULL)
except subprocess.CalledP... |
from notify.models import Notification
from rest_framework import serializers
from core.serializers import DynamicModelSerializer
from users.models.custom_user import CustomUser
from users.serializers.user_serializers import AuthorStampSerializer
class NotificationSerializer(DynamicModelSerializer):
class Meta:... |
# Generated by Django 3.1.3 on 2020-11-30 11:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0006_auto_20201130_1318'),
]
operations = [
migrations.RemoveField(
model_name='review',
name='rating',
... |
"""
MQTT client creation
~~~~~~~~~~~~~~~~~~~~
"""
import paho.mqtt.client as mqtt
from delight.config import MQTTConfig
mqttc = mqtt.Client()
mqttc.connect(MQTTConfig.HOST, MQTTConfig.PORT, 60)
mqttc.loop_start()
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
class ClipSymmetricalLoss(nn.Module):
def __init__(self, enable_tem=False, tem: float = None, device=torch.device("cuda")):
super().__init__()
self.device = device
self.enable_tem = enable_tem
... |
#!/usr/bin/env python3
import numpy as np
import cereal.messaging as messaging
from PIL import ImageFont, ImageDraw, Image
# font = ImageFont.truetype("arial", size=72)
def get_frame(idx):
img = np.zeros((874, 1164, 3), np.uint8)
img[100:400, 100:100+(idx % 10) * 100] = 255
# big number
im2 = Image.new("RGB",... |
import sys
input = sys.stdin.readline
a, b = map(int, input().split())
cnt = 0
for i in range(a, b+1):
i = str(i)
if i == i[::-1]:
cnt += 1
print(cnt)
|
import tkinter as tk
win = tk.Tk()
win.title("Python GUI")
win.mainloop() |
from math import *
array = [0]*101;
vals = [];
for i in xrange(101):
vals.append([0]*200)
def solve(num):
presLeft=0;
presNum =num;
for i in xrange(100):
j=-1
presSum=0
for k in xrange(1,11):
j=k
if(presNum < (presLeft*10+j)*j): break
presSum+=(j-1)
presNum = (presNum - (j-1)*(presLeft*10+(... |
# Stdlib
from io import BytesIO
import os
import sys
import textwrap
# External Libraries
from PIL import Image, ImageDraw, ImageFont
def handle(req):
"""GET"""
path = os.path.dirname(os.path.realpath(sys.argv[0]))
font = ImageFont.truetype(f'{path}/public/fonts/comicsans.ttf', 40)
txt = req.query['... |
from bs4 import BeautifulSoup
from exceptions import base_exception
@base_exception
def parse_champion_name(data: BeautifulSoup) -> str:
"""
Parse champion's name.
"""
champion_info = data.find('div',
class_='champ__header__left__main')
champion_name = champion_info.find('h2').get_text()
... |
from utils import mainNetwork, timeNetwork, weight_variable, bias_variable
from utils import state_environment_3D, last_price, price_format_conversion, Window_time_update
from utils import genetic_modification, final_metric
from sklearn.metrics import mean_squared_error as mse
import matplotlib.pyplot as plt
impo... |
class Solution(object):
def magicalString(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
elif n <= 3:
return 1
q = [1, 2, 2]
cur = 1
skip = 2
cnt_1 = 1
total_cnt = 3
for v in q:
... |
import numpy as np
import pandas as pd
import torch
import clip
from PIL import Image
import requests
from utils import mutual_information_2d
device = "cuda"
model, transform = clip.load("ViT-B/32", device=device)
df = pd.read_csv('data/selected_images.csv')
occupations = df.search_term.unique()
for occupation in oc... |
import unittest
from streamlink.plugins.skai import Skai
class TestPluginSkai(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
'http://www.skai.gr/player/tvlive/',
'http://www.skaitv.gr/live',
]
for url in should_match:
self.assertTru... |
# coding=utf-8
from flask import Flask
app = Flask(__name__)
from api.user import api_of_user
app.register_blueprint(api_of_user,url_prefix='/api/user')
from api.book import api_of_book
app.register_blueprint(api_of_book,url_prefix='/api/book')
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8081, debug... |
class Solution:
s=[]
def getList(self, root: TreeNode):
if root:
self.getList(root.left)
self.s.append(root.val)
self.getList(root.right)
def XXX(self, root: TreeNode) -> bool:
self.getList(root)
s=self.s
for i in range((l... |
'''
Exercise 5:
Write a program to read through the mail box data and when you find line\
that starts with “From”, you will split the line into words using the
split function. We are interested in who sent the message, which is
the second word on the From line.
From stephen.marq... |
#!/usr/bin/env python
import boto
OrdinaryCallingFormat = boto.config.get('s3', 'calling_format', 'boto.s3.connection.OrdinaryCallingFormat')
s3 = boto.connect_s3(host='localhost', port=10001, calling_format=OrdinaryCallingFormat, is_secure=False)
b = s3.get_bucket('mocking')
b.delete_keys(['hello.txt', 'goodbye.txt... |
#! python
# --------- Modify the Following Based on Your Data Size ------------
#DATA_1 configuration
P_Nt = 4
P_tiling_factor = 8
P_Vsnk = 128
B2Nrows = 4
Nsrc = 44
s = 3 # Fixed
Nperms = 36
Nw2 = 288
# ----------- Do Not Modify The Rest --------------------------------
# Automatic Replacement
Lt = P_Nt
t = Lt
t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.