content stringlengths 5 1.05M |
|---|
# coding: utf-8
"""
Jamf Pro API
## Overview This is a sample Jamf Pro server which allows for usage without any authentication. The Jamf Pro environment which supports the Try it Out functionality does not run the current beta version of Jamf Pro, thus any newly added endpoints will result in an error and sh... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# sort_quick_singly_linked_list_implement.py
# python
#
# 🎂"Here's to the crazy ones. The misfits. The rebels.
# The troublemakers. The round pegs in the square holes.
# The ones who see things differently. They're not found
# of rules. And they have no respect for the... |
from Harbir_101917050 import main
# main('file','file2') |
# Copyright (c) 2014 Red Hat 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 writi... |
#!/usr/bin/env python
"""This module defines the entry of console commend.
"""
import sys
from cogdata.arguments import get_args
def main():
args = get_args()
if args is not None:
args.func(args)
if __name__ == '__main__':
main()
|
# Contains the code for managing psychiatrist post comments.
# Imports --------------------------------------------------------------------------------
from datetime import datetime
from flask_login import current_user
from flaskr.mood_tracker.forms import MoodReview
from flaskr import db
from flaskr.mood_tracker.... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class Elastigroup(pulumi.CustomResour... |
import torch
import torch.nn as nn
from torchvision import models
from torch.autograd import Variable
from utils.utils import weights_init_kaiming, weights_init_classifier
class ClassBlock(nn.Module):
def __init__(self, input_dim, class_num, droprate, relu=False, bnorm=True, num_bottleneck=512, linear=True, retu... |
#!/usr/bin/env python
'''
Copyright (c) 2020 RIKEN
All Rights Reserved
See file LICENSE for details.
'''
import log,traceback
class load:
def __init__(self, args):
log.logger.debug('started')
try:
# default
self.genome_cov_thresholds=0.05 # Defining high coverage viruse... |
import math
import networkx
import numpy
from matplotlib import pyplot as plt
from networkx import DiGraph
from networkx import nx_agraph
def route_len(g: DiGraph):
edge_costs = [e[2]['cost'] for e in g.edges(data = True)]
return numpy.sum(edge_costs)
def closest_neighbor(g: DiGraph, v, forbidden: set):
min_di... |
import re
from unicodedata import category
def letter_only(text):
return re.sub("[^\w' ]", "",
re.sub("[^\w']", " ", text))
def normalize(text):
lower = text.lower()
return letter_only(lower)
def split(text):
return text.split()
def count(text):
words = {}
for word in text:
... |
import argparse
from argparse import RawTextHelpFormatter
from dataclasses import dataclass
import sys
queue = []
def rr(n, timeslice):
total_wait = total_turn = complete = time = 0
while complete != n:
for i in range(n):
if not queue[i].isCompleted:
... |
# %% Importing libraries
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
import time
import os
import random
import copy
import loss_landscapes
import loss_landscapes.metrics
from mpl_toolkits.mplot3d import ... |
from bestiary.models import Monster, GameItem
from data_log import models
from .test_log_views import BaseLogTest
class SummonLogTests(BaseLogTest):
fixtures = ['test_summon_monsters', 'test_game_items']
def test_summon_1_with_unknown_scroll(self):
self._do_log('SummonUnit/scroll_unknown_qty1.json')
... |
from os import path
import lmdb
import lz4framed
import numpy as np
import pyarrow as pa
import six
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from utils.image_utils import blur_image
class LMDB(Dataset):
def __init__(self, db_path, transform=None, t... |
import functools
import re
from typing import Optional
from sqlalchemy.orm import Session
from itunesdb.web import models
from itunesdb.web import schemas
_genre_name_splitter = re.compile("(.+): ([^:]+)$")
##########
# Genres #
##########
@functools.singledispatch
def get_genre(genre_id: int, db: Session) -> mo... |
def controllo_input(n):
if len(n) < 4:
raise TypeError("Errore: il numero deve avere minimo 4 cifre")
def ordina_crescente(n):
return "".join(sorted(n))
def ordina_decrescente(n):
return "".join(reversed(sorted(n)))
def costante_kaprekar(n):
iterazioni_max_kaprekar = 7
for i in range(i... |
#!/usr/bin/env python3
""" VGG Obstructed face mask plugin
Architecture and Pre-Trained Model based on...
On Face Segmentation, Face Swapping, and Face Perception
https://arxiv.org/abs/1704.06729
Source Implementation...
https://github.com/YuvalNirkin/face_segmentation
Model file sourced from...
https://github.com/Y... |
from investing_algorithm_framework.core.mixins import BinanceDataProviderMixin
from investing_algorithm_framework.core.data_providers.data_provider import \
DataProvider
class BinanceDataProvider(BinanceDataProviderMixin, DataProvider):
pass
|
import re
import typing
from pathlib import Path
initialNumberRe = re.compile("^(\\d+)-(.+)$")
def parsePatchName(s: str) -> typing.Tuple[int, str]:
res = initialNumberRe.match(s)
if res:
return int(res.group(1)), res.group(2)
def getPatchFilesInADir(dirP: Path):
for el in dirP.glob("*.patch"):
if el.is_fil... |
"""Xiaomi mija weather sensor device."""
import logging
from zigpy import quirks
from zigpy.profiles import zha
from zigpy.quirks.xiaomi import TemperatureHumiditySensor
from zigpy.zcl.clusters.general import (
AnalogInput, Groups, Identify, MultistateInput, Ota, Scenes)
from zigpy.zcl.clusters.measurement import ... |
from abc import ABCMeta, abstractmethod
import six
from .iter_dispatch import iter_
from .base import BaseItertool
@six.add_metaclass(ABCMeta)
class BaseFilter(BaseItertool):
def __init__(self, pred, seq):
self._predicate = pred
self._iter = iter_(seq)
@abstractmethod
def __next__(self):
... |
from pseas.instance_selection.instance_selection import InstanceSelection
from typing import Tuple, List, Optional
import numpy as np
class DiscriminationBased(InstanceSelection):
"""
Discrimination based method based on dominance of algorithms.
Parameter:
----------
- rho: the domination ratio ... |
# Generated by Django 3.1.5 on 2021-01-12 11:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('WebApp', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='UniversityDetail',
fields=[
... |
# For convenience, import collection and numpy
# into the "pyradiomics" namespace
import collections # noqa: F401
import inspect
import logging
import os
import pkgutil
import sys
import tempfile
import numpy # noqa: F401
from six.moves import urllib
from . import imageoperations
def deprecated(func):
"""
De... |
"""
Arquivos com funções utilizadas na Criptogafia de César
Autor: Thiago Souza
"""
# Função para Criptografar a mensagem
def criptografar(mensagem, chave):
# Constrói alfabeto extraído da tabela ASCII (Somente letras minúsculas)
alfabeto = []
for i in range(97, 123): # Intervalo de letras minúsculas na t... |
import torch
import torch.nn as nn
from torch.autograd import Variable
from dpp_nets.my_torch.linalg import custom_decomp, custom_inverse
from dpp_nets.my_torch.DPP import DPP, AllInOne
from dpp_nets.my_torch.utilities import compute_baseline
from itertools import accumulate
class NetBaseline(nn.Module):
def __... |
import json
import os
import copy
from models import DownloadSpec
DEFAULT_SOURCES_FILE_PATH = os.path.join(os.path.dirname(__file__), 'sources.json')
DEFAULT_ROUTING_FILE_PATH = os.path.join(os.path.dirname(__file__), 'agents_routing.json')
class SourcesManager:
def __init__(self, sources_file_path=DEFAULT_SOU... |
#!/usr/bin/python
"""
Main Workspace Run Script
"""
import os
import sys
import logging
import coloredlogs
import json
import math
import glob
import yaml
import yamale
import scripts.functions as func
from copy import copy
from subprocess import run, call
### Enable logging
logging.basicConfig(
format="%(asct... |
"""A function for extracting batch data into a tabular format."""
import csv
import html
import json
import logging
import os
from xml.dom import minidom
import click
from amti import settings
from amti import utils
logger = logging.getLogger(__name__)
TABULAR_SUPPORTED_FILE_FORMATS = [
'csv',
'json',
... |
#!/usr/bin/env python3
"""
===========
dswx_pge.py
===========
Module defining the implementation for the Dynamic Surface Water Extent (DSWx) PGE.
"""
import glob
import os.path
from collections import OrderedDict
from os.path import abspath, basename, exists, isdir, join, splitext
from opera.util.error_codes impo... |
import sys
import os
import datetime
import logging
from tqdm import tqdm
import copy
import numpy as np
import re
from concurrent import futures
logger = logging.getLogger("sacluster").getChild(os.path.basename(__file__))
path = "../../.."
os.chdir(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(path + ... |
from domains.interval import Interval, IntervalAbstractState
import random
def test_single_interval_comparisons():
random_intervals = []
for _ in range(100):
# These bounds are chosen arbitrarily.
lower = random.randint(-100000, +100000)
upper = random.randint(lower, +100000)
ra... |
#!/usr/bin/env python3
# Copyright (c) 2010 Anil Kumar
# All rights reserved.
#
# License: BSD
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from . import filecontext
class FileContextView(QTabWidget):
sig_goto_line = pyqtSignal(int)
sig_ed_cursor_changed = pyqtSignal(int, in... |
# Python3 Program to
# Write a program to accept minutes and convert it into hours and minute
#storing the number of minutes in the variable 'minutes'
minutes = int(input("Enter the total number of minutes: "))
#converting it to hours and minute
minute_left = minutes % 60
hours = minutes // 60
#final output
print(f"ti... |
import pandas as pd
from neurotin.evamed.parsers import parse_thi
from neurotin.io import read_csv_evamed
from neurotin.psd import (
blocks_count_success,
blocks_difference_between_consecutive_phases,
ratio,
)
from neurotin.psd.viz import plot_joint_clinical_nfb_performance
#%% CLI commands
"""
# Compute ... |
"""
Author : Sitanshu15
Bot : Nora
"""
import asyncio
import datetime
import difflib
import functools
import io
import math
import os
import json
import random
import re
import textwrap
import time
import typing as t
import unicodedata
from difflib import get_close_matches
from io import BytesIO
import aiohttp
import... |
from flask_wtf.form import FlaskForm
from flask_wtf.file import FileAllowed, FileRequired, FileField
from wtforms import PasswordField, SubmitField, TextAreaField, StringField, BooleanField
from wtforms.validators import DataRequired, Email, EqualTo, Length, Regexp, ValidationError
from models import Article, User
impo... |
# contains implementations for DFU methods. This allows for unit testing.
# hmm, class or functions, class or functions... let's go with functions for now.
# If we wind up having to pass in a ton of crap every time try an OO approach.
# TODO move more method implementations here - or in other files - as needed.
# TOD... |
#! /usr/bin/env python
# coding: utf-8
import os
import uuid
import hashlib
from werkzeug.utils import secure_filename
from flask import Flask, Blueprint, send_from_directory, request, jsonify, url_for, make_response
from flask_helper.utils.folder import create_folder2
__author__ = '鹛桑够'
def support_upload(app_or... |
import os
import argparse
import pandas as pd
import numpy as np
import re
from os import walk
from collections import Counter
import random
import shutil
def sort_moas(cpds_moa):
"""
Sort MOAs based on the number of compounds that are attributed to them in ASCENDING order.
This is HIGHLY Required before p... |
random_numbers = [1, 22, 333, 4444, 55555]
print("\n".join([str(n) for n in random_numbers]))
|
import os
from sklearn.ensemble import RandomForestClassifier
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import multiprocessing
if __name__ == '__main__':
multiprocessing.set_start_method('spawn')
from params import global_param
from TsmlExtractorWrapper import get_dataset_fold
import tensorflow as tf
from logi... |
from __future__ import print_function, absolute_import, division # makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# Importing the Kratos Library
import KratosMultiphysics
# other imports
from KratosMultiphysics.time_based_ascii_file_writer_utility import TimeBasedAsciiFileWriterUtility
def Fac... |
from google.cloud.aiplatform.helpers import value_converter
__all__ = (value_converter,)
|
# -*- coding: utf-8 -*-
"""NOTICE: This file was generated automatically by the command: xpoetry setup-py."""
from distutils.core import setup
packages = ["flake8_nitpick", "flake8_nitpick.files"]
package_data = {"": ["*"]}
install_requires = ["attrs", "dictdiffer", "flake8>=3.0.0", "jmespath", "python-slugify", "py... |
from typing import List, MutableMapping, NamedTuple, Tuple, Union
from enum import Enum, auto
from itertools import product
class Operator(Enum):
addition = auto()
subtraction = auto()
division = auto()
multiplication = auto()
pop = auto()
insert = auto()
convert = auto()
exponential =... |
# job_runner.py: gis cloud test case,
# Get list of folders, and process each using another python script.
# Author: JMassey
import sys
import argparse
import boto3
import sys
import os
from timeit import default_timer as timer
batch = boto3.client('batch')
def main():
# 1 - Define Variables passed from CLI, a... |
from datetime import datetime
from lib.resources import Resources
import logging
from PIL import Image, ImageDraw
import requests
class Weather:
def __init__(self, config, resources: Resources):
self.config = config
self.resources = resources
def render(self, image: Image):
response =... |
import staticfiles_tests.signals # noqa
|
# coding: utf-8
"""
Borrowed from https://github.com/1996scarlet/Dense-Head-Pose-Estimation/blob/main/service/CtypesMeshRender.py
To use this render, you should build the clib first:
```
cd utils/asset
gcc -shared -Wall -O3 render.c -o render.so -fPIC
cd ../..
```
"""
import sys
sys.path.append('../../3DDFA')
impo... |
"""Aimsun dummy server.
This script creates a dummy server mimicking the functionality in the Aimsun
runner script. Used for testing purposes.
"""
from thread import start_new_thread
import socket
import struct
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import... |
__version__ = '0.14.0'
|
from __future__ import division
import matplotlib as mpl
# Set correct backend
mpl.use('tkagg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import random
import itertools
import threading
import time
import mplcursors
import sys
from hrm import *
from matplotlib.widgets i... |
from django.shortcuts import render
from rest_framework import status
# Create your views here.
from rest_framework.response import Response
from django.contrib.auth.models import User
from rest_framework import viewsets
from rest_framework import serializers
from accounts.models import Customer, Vendor
from accounts.... |
#!/usr/bin/env python3
#coding: utf-8
### 1st line allows to execute this script by typing only its name in terminal, with no need to precede it with the python command
### 2nd line declaring source code charset should be not necessary but for exemple pydoc request it
__doc__ = "this module provide support for tempo... |
from .space import *
from .task import *
from .decorator import *
|
# -*- coding: utf-8 -*-
# @Time : 2020/6/11
# @Author : Fred liuchuanhao
# @File : .py
# @Role :
import fire
from libs.aws.com_ebs import ComplianceEbsApi
from models.ebs import DB
from libs.web_logs import ins_log
from libs.db_context import DBContext
from libs.aws.session import get_aws_session
from setti... |
# coding: utf-8
from pprint import pformat
from ..utils import to_dict
class PublicProfile(object):
def __init__(self, id=None, first_name=None, last_name=None, profile_image=None):
self._id = id
self._first_name = first_name
self._last_name = last_name
self._profile_image = pr... |
import random
import numpy as np
"""
Problem Generation:
This file includes all methods used for generating problems
"""
class Problem:
def __init__(self, param_fragment_size, param_queries, param_query_frequency,
param_query_cost, param_query_ids, total_nr_queries):
self.param_f... |
"""A classification example where we we only have asymptotically 1/4th of parameterized gates."""
import numpy as np
from qiskit import QuantumCircuit
from qiskit.circuit.library import ZFeatureMap, RealAmplitudes
from qiskit.circuit.parametertable import ParameterTable
from qiskit.opflow import H
from .benchmark imp... |
import sys
sys.path.append("xicd")
import tkinter as tk
import time
from xicdcfg import Config
class App(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self._canvas = None
self._config = Config("config.json")
self._config.setup()
self._running =... |
from backbone import *
def cnn(backbone, nb_classes=20, patch_size=224, activation='softmax', pretrain='imagenet', trainable=False, isbackbone=False):
if backbone=='resnet50':
base_model = resnet50(nb_classes, patch_size, activation, pretrain, isbackbone)
feat_channel = 2048
if backbone=='nasn... |
def char_mask(pat, alphabet):
ret = {}
for c in alphabet:
ret[c] = bitarray(m*'1')
for i in range(m):
ret[pat[i]][m-i-1] = 0
return ret
def scan(txt, pat, err, alphabet):
n = len(txt)
m = len(pat)
occ = []
chmasks = char_mask(pat, alphabet)
print chmasks
S = [bitarray((m-q) * '1' + q*'0')... |
from app.main.model.review_dao import ReviewDAO as model_review
from app.main.model.congestion_dao import CongestionDAO as model_congestion
from app.main.model.place_dao import PlaceDAO as model_place
from app.main.model import *
from ..service.search import get_score, get_top_tag, get_matching_rate
from ..service.user... |
from api.schemas import AllowedBlurType, AllowedFilter, CompressMethod
from api.schemas.schemas import PlacePosition, Position
from api.utils.convert import sizeof_fmt, to_dict
from api.utils.executor import executor
from api.utils.image import *
from fastapi import APIRouter, File, Form, UploadFile, params
from fastap... |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from __future__ import unicode_literals
from indico.core.settings import AttributeProxyProperty
from indi... |
from main import config
def md5_with_salt(text: str, salt: str) -> str:
import hashlib
md5 = hashlib.md5()
md5.update((text+salt).encode())
return md5.hexdigest()
def encode_json(obj):
import json
encoder = json.JSONEncoder(default=lambda x: str(x))
return encoder.encode(obj)
def decod... |
#coding=utf-8
'''
Created on 2016-12-5
@author: Administrator
'''
from doraemon.project import models
from url_filter.filtersets.django import ModelFilterSet
class IssueDailyStatisticsFilterSet(ModelFilterSet):
class Meta(object):
model = models.ProjectIssue
fields = ['Project','Version','Status... |
import colorsys
import re
from app.nanoleaf.model import AuroraObject
from app.nanoleaf.exceptions import BadRequestException
class State(AuroraObject):
def __init__(self, requester):
super().__init__(requester)
@property
def color_mode(self):
"""Returns the current color mode."""
... |
#!/usr/bin/python
#
# Copyright 2019 Google LLC
#
# 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 ag... |
#!/usr/bin/env python3
from argparse import ArgumentParser
from urllib.parse import urlparse
from base64 import b64decode
from itertools import count
import os
import sys
import json
import shutil
try:
import ijson.backends.yajl2_cffi as ijson
except ImportError:
try:
import ijson.backends.yajl2 as i... |
# Copyright (C) 2012 Yaco Sistemas (http://www.yaco.es)
#
# 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 applic... |
import keras
import numpy as np
import sys
import time
PUNISHMENT_FOR_VISIT = 0.2
MAX_COUNTER = 1000
def test_with_data(model):
print("TEST")
counter = 0
total = 0
for i in range(21):
path = "../moves/bin-moves/sol_ida_problem_"+str(i)+"_.txt"
file = open(path, 'r')
for line in... |
#! /usr/bin/python
#
'''
Version : 0.1
Author : Arian Pasquali
Summary : This class defines generic datasource interface
'''
class DataSource: # define parent class
def open_connection(self,options):
print 'Openning connection'
def index(self,object):
print 'Indexing'
def close_c... |
import sys
from abc import ABC
from typing import final
from extutils import exec_timing_result
from mongodb.factory import SINGLE_DB_NAME, MONGO_CLIENT
from tests.base import TestCase
if not SINGLE_DB_NAME:
print("Utilize single DB by setting `MONGO_DB` in environment variables "
"to prevent the possib... |
# -*- coding: utf-8 -*-
from django.template import Library
from django.utils.translation import ugettext as _
register = Library()
@register.filter
def get_range(value):
"""
Filter - returns a list containing range made from given value
Usage (in template):
<ul>{% for i in 3|get_range %}
<l... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_pagedown import PageDown
from config import config
db = SQLAlchemy()
boots... |
Desc = cellDescClass("TBUFX20")
Desc.properties["cell_leakage_power"] = "6496.329600"
Desc.properties["cell_footprint"] = "tbuf"
Desc.properties["area"] = "76.507200"
Desc.pinOrder = ['A', 'OE', 'Y']
Desc.add_arc("A","Y","combi")
Desc.add_arc("OE","Y","three_state_disable")
Desc.add_arc("OE","Y","three_state_enable")
D... |
# TODO: Implement genetic algorithms
|
from filesystem import InjectText, CopyFile, CreateLink, CreateDirectory
|
class DbDig:
def __init__(self, conn, dbtype="Postgres"):
self.Imp = None
self.Type = dbtype
if dbtype == "Oracle":
self.Impl = DbDigOracle(conn)
else: # assume Postgres
self.Impl = DbDigPostgres(conn)
def __getattr__(self, name):
return ge... |
"""
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-search-ii
"""
import collections
from typing import List
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
END_OF_WORD = "#"
class Solution(object):
def __init__(self):
self.n = None
self.m = None
self.result = None
def find_words(s... |
import os
import re
import boto3
import requests
def download_from_s3():
s3_bucket_name = 'heartrate-power-streams'
s3_base_url = 'https://s3-eu-west-1.amazonaws.com/heartrate-power-streams/{key}'
s3 = boto3.resource('s3')
s3_bucket = s3.Bucket(s3_bucket_name)
athletes = set()
for obj in s... |
from django.urls import path
from . import views
from .views import buchung, bausparvertrag, sparbeitrag, sparbeitrag_job
from .views.index import IndexView
urlpatterns = [
path('', IndexView.as_view(), name='index'),
path('bausparvertrag/', bausparvertrag.ListView.as_view(), name='bausparvertrag_list'),
... |
import collections
class Solution:
# 和554很相近
def orangesRotting(self, grid) -> int:
if not grid:
return -1
n, m = len(grid), len(grid[0])
zero_list = [(i, j) for i in range(len(grid)) for j in range(len(grid[0])) if grid[i][j] == 2]
q = collections.deque(zero_list)
... |
with open("./twelve_step/version.txt", "r+") as version_file:
version = version_file.readline().replace("\n", "")
with open("./twelve_step/version.txt", "w+") as version_file:
version_parts = version.split(".")
patch = version_parts[-2]
version_parts[-2] = str(int(patch) + 1)
version_file.write(".".... |
import time
import srt
import re
import datetime
from mqtthandler import MQTTHandler
INIT_STATUS={
"video": {
"title": None,
"series_title": None,
"season": None,
"episode": None
},
"time": None,
"events": None
}
class SubtitleHandler:
subtitles = []
phrases = ... |
import pytest
from _midynet.prior import sbm
from midynet.config import Wrapper
@pytest.fixture
def wrapper():
size = 100
max_block_count = 10
block_count = sbm.BlockCountUniformPrior(max_block_count)
blocks = sbm.BlockUniformPrior(size, block_count)
return Wrapper(
blocks,
block_... |
# -*- coding: utf-8 -*-
class Solution(object):
def numSquares(self, n):
dp = [float("inf") for x in xrange(n + 1)]
dp[0] = 0
i = 0
while i <= n:
j = 1
while j * j <= i:
# dp[i]: integer i can be consist of least number of square
... |
# -*- encoding:utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
"""Common functions used for odps input."""
from easy_rec.python.protos.dataset_pb2 import DatasetConfig
def is_type_compatiable(odps_type, input_type):
"""Check that odps_type are compatiable with input_type."""
type_map = {
'bigint... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above... |
from django.db import transaction
from django.template.response import TemplateResponse
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from bambu_webhooks.forms i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Content',
fields=[
('id', models.AutoField(prim... |
from scipy.special import j1,jn_zeros
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
plt.style.use('mint')
x = np.linspace(0, 4 * np.pi, 10000)
y = (2 * j1(x) / x)**2
golden_mean = (np.sqrt(5) - 1) / 2 # Aesthetic ratio
fig_width_pt = 400 # column width
inche... |
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
CallbackContext,
)
import os
import telegram
import logging
import logging.config
import redis_client as rds
DEFAULT_SEARCH_RADIUS = 100
logging.config.fileConfig("logging.conf")
log = logging.getLogger("grassroot")
def... |
from django.contrib import admin
# Register your models here.
from .models import Item, User, Group, Receipt, ItemOnReceipt
admin.site.register(Item)
admin.site.register(User)
admin.site.register(Group)
admin.site.register(Receipt)
admin.site.register(ItemOnReceipt)
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
class QNetwork(nn.Module):
def __init__(self, my_pretrained_model, seed):
super(QNetwork, self).__init__()
self.seed = torch.manual_seed(seed)
self.pretrained = my_pretrained_model
self.fc = nn.Se... |
#!/usr/bin/env python
#
# Copyright 2018 GoPro Inc.
#
# 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... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from pyspark.sql import SparkSession
from pyschema2 import JSONConverter, py_type_from_json_schema, array_of, nullable, \
STRING_TYPE, LONG_TYPE, BOOLEAN_TYPE, TIMESTAMP_TYPE, print_pyschema
def get_spark():
# spark = SparkSession.builder.\
# config("spa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.