content stringlengths 5 1.05M |
|---|
from __future__ import absolute_import
from django.core import mail
from sentry.utils.compat.mock import patch
from social_auth.models import UserSocialAuth
from sentry.exceptions import InvalidIdentity, PluginError
from sentry.models import (
Commit,
Deploy,
Integration,
LatestRepoReleaseEnvironment,... |
from src.models import Movie
from src.api import Api
from flask import request
from os import remove , listdir
from os.path import exists
class Movies(Api):
def __init__(self):
super().__init__()
def create_model(self):
self.model = Movie()
def sanitize_data(self):
data = [
... |
import unittest
from python_tuya_oittm.api_client import ApiClient
TEST_DEVICE_ID = '<enter a device id>'
TEST_ENCRYPTION_KEY = '<enter an encryption key>'
class TestTuyaApiClientIntegratedMethods(unittest.TestCase):
def test_get_metadata(self):
api_client = ApiClient()
data = api_client.get_met... |
# -*- coding: utf-8 -*-
"""Sentinel Tools API Class
Sentinel Tools - API Class
============================
Simple wrapper class for the Sentinel API that takes a Config object.
This file is a part of Sentinel Tools
Copyright 2020 - MET Norway (Machine Ocean Project)
Licensed under the Apache License, Version ... |
"""
plenum package metadata
"""
import os
import json
from typing import Tuple, List, Union
import collections.abc
from common.version import PlenumVersion, InvalidVersionError
VERSION_FILENAME = '__version__.json'
VERSION_FILE = os.path.join(
os.path.abspath(os.path.dirname(__file__)), VERSION_FILENAME)
def lo... |
from utils.orm.db import BaseModel
import httpx
import json
from sanic.log import logger as _logger
class DemoModel(BaseModel):
__tablename__ = 'demo_model'
async def demo_method(self):
print('demo method')
|
import json
from operator import itemgetter
from orchard_watch import query_db
from orchard_watch import respond
annoucement_schema = [
['annoucementid', 'longValue'],
['title', 'stringValue'],
['description', 'stringValue'],
['dateTime', 'stringValue'],
['email', 'stringValue']
]
def annoucement... |
# Copyright 2021 Adam Byerly. 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 agre... |
import copy
import logging
from random import uniform
import matplotlib.pyplot as plt
import numpy as np
from morpho import BrillouinZonePath as BZPath
from morpho import SymmetryPoint as SPoint
from scipy.signal import find_peaks
from fdtd import EFieldDetector, Grid, HFieldDetector, Material
from fdtd.boundaries im... |
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T
#
# Copyright (c) 2016+ Buro Petr van Blokland + Claudia Mens
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyx... |
import sys
sys.path.append('objection_engine/')
import objection_engine
# You can also import the components like this
from objection_engine.renderer import render_comment_list
from objection_engine.beans.comment import Comment
foo = [objection_engine.comment.Comment(), objection_engine.comment.Comment(text_content='Se... |
from bs4 import BeautifulSoup
from bs4 import NavigableString
import requests
import logging
import pandas as pd
import json
def get_cleaned_movie(movie_bs4):
"""Get a dictionary of a movie from its bs4 object"""
# parse directors and stars arrays
movie_directors_array = []
movie_stars_array = []
... |
from ...kernel import core
from ...kernel.core import VSkillModifier as V
from ...kernel.core import CharacterModifier as MDF
from ...character import characterKernel as ck
from functools import partial
class AuraWeaponBuilder():
def __init__(self, enhancer, skill_importance, enhance_importance):
self.Aura... |
import datetime
import decimal
import functools
from sqlalchemy.ext.associationproxy import _AssociationList
from geojson import dumps as _dumps
from geojson.codec import PyGFPEncoder
class GeoJSONEncoder(PyGFPEncoder):
# SQLAlchemy's Reflecting Tables mechanism uses decimal.Decimal
# for numeric columns an... |
# Generated by Django 3.1.7 on 2021-03-25 19:48
from django.db import migrations, models
import django.utils.timezone
import phonenumber_field.modelfields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
... |
import logging
import allure
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from models.auth import AuthData
from pages.app import Application
logger = logging.getLogger("moodle")
@pytest.fixture(scope="s... |
class RouteException(Exception):
"""Raise when there is a general problem in a route"""
def __init__(self, message, status_code=500, data=None, *args):
self.message = message
self.status_code = status_code
self.data = data
super().__init__(message, status_code, data, *args)
cl... |
"""
class to extract domain-specific terms
for examples, 'JavaScript' in CS and 'limit' in math
"""
import logging
logger = logging.getLogger(__name__)
from DST.utils.TermUtil import filterTerm
class DomainTerm(object):
"""
class to extract domain-specific terms
"""
def __init__(self, maxTermsCount=3... |
"""Bare wrapper around IPOPT using numpy arrays and exception handling.
This module has an intermediate level of abstraction in the wrapping. Exception
handling is done in the callbacks and the error is signalled back to IPOPT. The
parameters in the callbacks are converted to ndarrays and the function inputs
are valid... |
import omemo
from omemo_backend_signal import BACKEND as SignalBackend
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tests")))
from deletingotpkpolicy import DeletingOTPKPolicy
from dr_chat import mainLoop
import example_data
try:
input = raw_input
except Na... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... |
import os
import numpy as np
from tqdm import tqdm
from stable_baselines import PPO2
from navrep.envs.navreptrainencodedenv import NavRepTrainEncodedEnv
from crowd_sim.envs.utils.info import Timeout, ReachGoal, Danger, Collision, CollisionOtherAgent
from navrep.tools.commonargs import parse_common_args
class NavRepCP... |
# Copyright 2013-2020 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 DbusGlib(AutotoolsPackage):
"""dbus-glib package provides GLib interface for D-Bus API.""... |
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
class Meeting(models.Model):
title = models.CharField(
max_length=256,
verbose_name=_('Title'),
help_text=_('Title of the meeting')
)
... |
"""Test the sum_odd_numbers function."""
import pytest
def test_nth_even():
"""test the nth_even function."""
from get_nth_number import nth_even
test_value = nth_even(100)
assert test_value == 198 |
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2008, Yung-Yu Chen <yyc@solvcon.net>
#
# 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 copyrigh... |
'''
HecTime and writing Irregular time-series safely
'''
import sys
from pydsstools.heclib.dss.HecDss import Open
from pydsstools.core import TimeSeriesContainer
from pydsstools.heclib.utils import HecTime, DssLastError
dss_file = "example.dss"
fid = Open(dss_file)
def decor(func):
def f(*arg,**kwargs):
... |
# -*- coding: utf-8 -*-
# @File : baseview.py
# @Date : 2021/2/25
# @Desc :
from rest_framework.generics import UpdateAPIView, DestroyAPIView
from rest_framework.serializers import Serializer
from rest_framework.viewsets import ModelViewSet
class FakeSerializer(Serializer):
pass
class BaseView(ModelViewSet, ... |
import math
import time
import pytest
from . import assert_javascript_entry
@pytest.mark.asyncio
async def test_types_and_values(bidi_session, current_session, inline, wait_for_event):
await bidi_session.session.subscribe(events=["log.entryAdded"])
on_entry_added = wait_for_event("log.entryAdded")
exp... |
"""
LibriParty Dataset creation by using official metadata.
Author
------
Samuele Cornell, 2020
Mirco Ravanelli, 2020
"""
import os
import sys
import speechbrain as sb
from hyperpyyaml import load_hyperpyyaml
from speechbrain.utils.data_utils import download_file
from local.create_mixtures_from_metadata import create... |
import simplejson as json
class PConf():
def __init__(self, filename="", schema={}):
"""initialize with a schema dictionary"""
if not filename or not isinstance(schema, dict):
return None
with open(filename, "r") as f:
self.conf = json.loads(f.read())
self.schema = schema
self.validate(self.conf, ... |
from flask import request
def get_locale():
rv = request.accept_languages.best_match(['zh', 'en'])
return rv or 'en'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2022 askusay
#
# 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 b... |
from pyit.cop import ITokenCop, Cop
from pyit.offence import Offence
from token import *
class SpaceIndentationCop(Cop):
COP_CONFIG = {}
OPEN_BRACKETS = {
'(': LPAR,
'[': LSQB,
'{': LBRACE,
}
CLOSE_BRACKETS = {
'}': RBRACE,
']': RSQB,
')': RPAR,
}
... |
import sys
import pandas as pd
import matplotlib.pyplot as plt
sys.path.append('../minvime')
import estimator_classification as esti # The file ../minvime/estimator_classification.py
fprates = [0.0, 0.00001, 0.0001, 0.001, 0.002, 0.003, 0.004, 0.005, 0.01, 0.015,
0.02,0.025, 0.03, 0.035, 0.04, 0.045, 0... |
# -*- coding: utf-8 -*- #
# Copyright 2021 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 requir... |
from flask import Flask, jsonify, request
from pymongo import MongoClient
from flask_script import Manager, Command, Shell
from flask_mail import Mail, Message
import nltk
from nltk.corpus import state_union
from nltk.tokenize import PunktSentenceTokenizer
from nltk import word_tokenize, pos_tag
from tenseflow ... |
from mayan.apps.appearance.classes import Icon
icon_statistics = Icon(driver_name='fontawesome', symbol='chart-line')
icon_execute = Icon(driver_name='fontawesome', symbol='cog')
icon_namespace_details = Icon(driver_name='fontawesome', symbol='chart-line')
icon_namespace_list = Icon(driver_name='fontawesome', symbol='... |
from distutils.core import setup
# py2exe stuff
import py2exe, os
# find pythoncard resources to add as 'data_files'
pycard_resources=[]
for filename in os.listdir('.'):
if filename.find('.rsrc.')>-1:
pycard_resources+=[filename]
# includes for py2exe
includes=[]
for comp in ['button','multicolumnlist','s... |
# Copyright Contributors to the Packit project.
# SPDX-License-Identifier: MIT
import shutil
from pathlib import Path
from typing import Tuple
import subprocess
import tempfile
import pytest
from flexmock import flexmock
from packit.utils.commands import cwd
from packit.utils.repo import create_new_repo
from tests.s... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
# -*- coding: utf-8 -*-
import unittest
import numpy as np
import six
import tensorflow as tf
from tfsnippet.bayes import Bernoulli
from tests.helper import TestCase
from tests.bayes.distributions._helper import (DistributionTestMixin,
BigNumberVerifyTestMixin,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
" The code for the sc2 environment, maybe add some functions for the original pysc2 version "
# modified from AlphaStar pseudo-code
import numpy as np
from s2clientprotocol import sc2api_pb2 as sc_pb
from pysc2 import run_configs
from pysc2.lib import features
from pys... |
"""definition of problem instance
Author: Keisuke Okumura
Affiliation: TokyoTech & OSX
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Optional, Union
import numpy as np
from .obstacle import Obstacle, ObstacleSphere
from .static_objects import StaticObjects
@dat... |
# ptif_uploader script / webhook
# The developement has been resumed from uploader_jyhton
# Designed to use models from slide-atlas
__author__ = 'dhan'
#TODO: Extend the uploader for
# - Wrapping c++ image_uploader for ndpi and jp2 images
#noqua E501
import os
import sys
import argparse
# from celery import Celery... |
import warnings
import math
from typing import Optional, TypeVar
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
from torch.nn import Module
from torch.nn import init
from torch.nn.parameter import Parameter
import torchshard as ts
class ParallelLoss(Module):
"""
... |
# Generated by nuclio.export.NuclioExporter
import os
import pandas as pd
import numpy as np
import scipy as sp
import pickle
import datetime
import v3io_frames as v3f
import matplotlib.pyplot as plt
from sklearn.preprocessing import KBinsDiscretizer
def to_observations(context, t, u, key):
t = (
t.app... |
from django.db import models
class Author(models.Model):
"""
An `Article` author
Attributes:
name (CharField):
Author name.
email (EmailField):
Author email.
"""
name = models.CharField(max_length=255)
email = models.EmailField()
class Article(models... |
allData = {'AK': {'Aleutians East': {'pop': 3141, 'tracts': 1},
'Aleutians West': {'pop': 5561, 'tracts': 2},
'Anchorage': {'pop': 291826, 'tracts': 55},
'Bethel': {'pop': 17013, 'tracts': 3},
'Bristol Bay': {'pop': 997, 'tracts': 1},
'Denali': {'pop': 1826, 'tracts': 1},
... |
import torch
import getopt
import math
import numpy
import os
import PIL
import PIL.Image
import sys
import torch.nn.functional as F
import torchvision.transforms as transforms
import skimage.io as io
import numpy as np
from skimage import morphology
from scipy import ndimage
import math
transform = transforms.Compos... |
import ssl
import sys
import json
import os
import requests
import toml
import atexit
import re
import traceback
from pyVim import connect
from pyVmomi import vim
from pyVmomi import vmodl
# GLOBAL_VARS
DEBUG = False
# CONFIG
VC_CONFIG = '/var/openfaas/secrets/vcconfig'
service_instance = None
class bgc:
HEADER... |
from datetime import datetime
from product import Product
class Slides(Product):
def __init__(self, raw_product):
Product.__init__(self, raw_product)
bib_info = raw_product.get('slides', {})
self._parse_bib_info(bib_info)
def _parse_bib_info(self, bib_info):
self._repository =... |
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from data_crystal.settings import URL_PREFIX
from data_manager.models import Data
###############################################################################
def app_home(request):
template = loader.get_temp... |
import argparse
import torch
import torch.nn.functional as F
from gat_conv import GATConv
from torch.nn import Linear
from datasets import get_planetoid_dataset
from snap_dataset import SNAPDataset
from suite_sparse import SuiteSparseMatrixCollection
from train_eval_cs import run
import pdb
from torch_geometric.nn impo... |
import os
from config.defaults import *
if os.environ.get("ENV") == 'dev':
print("==== Loading DEV environment ====")
from config.local import *
elif os.environ.get("ENV") == 'docker':
print("==== Loading Docker environment ====")
from config.docker import *
else:
print("==== Loading HERKOU enviro... |
from typing import Any, Dict, List, Optional, Tuple, Type, Union
import gym
import numpy as np
from stable_baselines3.common.distributions import SquashedDiagGaussianDistribution
import torch as th
from torch.distributions.multivariate_normal import MultivariateNormal
import torch.nn as nn
from torch.nn.utils ... |
import os
import urllib2
import uuid
import falcon
import mimetypes
import requests
import logging
from datetime import datetime
__author__ = 'Maged'
logging.basicConfig(filename='dropbox_upload_manager.log', level=logging.DEBUG)
WGET_CMD = '/usr/bin/wget'
ALLOWED_TYPES = (
'text/plain',
'image/gif',
'i... |
from unittest import TestCase, main
from os import remove
from os.path import exists, join
from datetime import datetime
from shutil import move
from biom import load_table
import pandas as pd
from qiita_core.util import qiita_test_checker
from qiita_db.analysis import Analysis, Collection
from qiita_db.job import Jo... |
# Auto generated by generator.py. Delete this line if you make modification.
from scrapy.spiders import Rule
from scrapy.linkextractors import LinkExtractor
XPATH = {
'name' : "//div[@class='pdt-r']/div[@class='t']/div[@class='l']/h1",
'price' : "//div[@class='l']/div/p/span",
'category' : "//body/form[@id... |
"""pydantic models for GeoJSON Feature objects."""
from typing import Dict, Generic, List, Optional, TypeVar
from pydantic import Field, validator
from pydantic.generics import GenericModel
from geojson_pydantic.geometries import Geometry
from geojson_pydantic.types import BBox
Props = TypeVar("Props", bound=Dict)
... |
"""Async version of stream-unzip (https://github.com/uktrade/stream-unzip). MIT License."""
import zlib
from struct import Struct
async def stream_unzip(zipfile_chunks, chunk_size=65536):
local_file_header_signature = b'\x50\x4b\x03\x04'
local_file_header_struct = Struct('<H2sHHHIIIHH')
zip64_compressed_... |
"""
Given two sequences ‘s1’ and ‘s2’, write a method to find the length
of the shortest sequence which has ‘s1’ and ‘s2’ as subsequences.
Example 2:
Input: s1: "abcf" s2:"bdcf"
Output: 5
Explanation: The shortest common super-sequence (SCS) is "abdcf".
Example 2:
Input: s1: "dynamic" s2:"programming"
Output: 1... |
"""The yale_smart_alarm component."""
|
import numpy as np #import numpy library
#intergers
i=10
print(type(i)) #print out the data type 1
a_i = np.zeros(i,dtype=int) #declare an array of ints
print(type(a_i)) #will return ndarray
print(type(a_i[0])) #will return int64
#floats
x = 119.0 #floating point number
print(type(x)) #print out the... |
"""Utilties for distributed processing"""
import horovod.tensorflow.keras as hvd
def rank():
try:
return hvd.rank()
except ValueError:
return 0
def barrier():
try:
hvd.allreduce([], name='Barrier')
except ValueError:
pass
|
import os
import time
import pytest
from rhcephcompose.compose import Compose
from kobo.conf import PyConfigParser
import py.path
@pytest.fixture
def conf(fixtures_dir):
conf_file = os.path.join(fixtures_dir, 'basic.conf')
conf = PyConfigParser()
conf.load_from_file(conf_file)
return conf
class Test... |
# Copyright 2020 The TensorFlow Probability 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 o... |
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... |
'''
Created on Jul 13, 2018
@author: friedl
'''
import subprocess
import sys
def run_bwa_aln(genome_index, fastq_in_file, sai_out_file, bwa_path='bwa', threads=1, R_param=None):
''' calls bwa aln '''
# build bwa command
command = [bwa_path, 'aln', '-t', str(threads), '-f', sai_out_file]
if(R_par... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Given the taxonomy output from AlchemyAPI, for each level of taxonomies, extract the graph
so that the taxons in this level are connected based on
***Jaccardi score*** for the users sharing these taxons in their tweets
"""
import codecs
from collections import defau... |
# Copyright 2017 Neosapience, 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 wri... |
# problems init file
from tigerforecast.problems.core import Problem
from tigerforecast.problems.sp500 import SP500
from tigerforecast.problems.uci_indoor import UCI_Indoor
from tigerforecast.problems.enso import ENSO
from tigerforecast.problems.crypto import Crypto
from tigerforecast.problems.random import Random
fro... |
import sys
sys.path.append('..')
import torch.nn as nn
import torch
class ConvBlock(nn.Module):
"""Layer to perform a convolution followed by LeakyReLU
"""
def __init__(self, in_channels, out_channels):
super(ConvBlock, self).__init__()
self.conv = Conv3x3(in_channels, out_channels)
... |
import os
import pickle
import socket
import threading
import time
from cryptography.fernet import Fernet
from scripts import encryption
from scripts.consts import MessageTypes
# IP = socket.gethostbyname(socket.gethostname())
IP = 'localhost'
PORT = 8004
class Server:
def __init__(self):
self.active_co... |
#!/usr/bin/env python
import pytest
import os
import sys
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
from pathlib import Path
from dselib.thread import initTLS
initTLS()
from dselib.context import DSEContext
from dselib.defaults import Defaults
from dselib... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 20:06:01 2015
@author: Thomas
"""
# Python standard library imports
import csv
import os
def main():
costs = []
for file in os.listdir("reformatted/"):
print 'getting data from.. ' + file
cost_total = []
cost_2000 = []
... |
class SveaException(Exception):
pass
class MissingFiles(SveaException):
pass
class DtypeError(SveaException):
pass
class PathError(SveaException):
pass
class PermissionError(SveaException):
pass
class MissingSharkModules(SveaException):
pass
|
from __future__ import print_function
import yaml
from cloudmesh.common.util import path_expand
from cloudmesh.shell.command import PluginCommand
from cloudmesh.shell.command import command, map_parameters
from cloudmesh.openapi3.function.server import Server
from cloudmesh.common.console import Console
from cloudmes... |
#! /usr/bin/env python
"""
Author: Scott H. Hawley
Based on paper,
A SOFTWARE FRAMEWORK FOR MUSICAL DATA AUGMENTATION
Brian McFee, Eric J. Humphrey, and Juan P. Bello
https://bmcfee.github.io/papers/ismir2015_augmentation.pdf
"""
from __future__ import print_function
import numpy as np
import librosa
from random impo... |
text = input()
for index, letter in enumerate(text):
if letter == ":":
print(letter + text[index + 1])
|
class Node:
def __init__(self, val):
self.val = val
self.left = left
self.right = right
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
|
import argparse
import datetime
import fnmatch
import os
import pickle
import re
from time import time
from typing import List
import tensorflow.keras
import numpy
import numpy as np
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, TensorBoard
from tensorflow.keras.preprocessin... |
lst = ["A","guru","sabarish","kumar"]
last=lst[-1]
length=0
for i in lst:
length=length+1
if i == last:
break
print("The length of list :",length)
|
def dp(n, k):
if |
# Copyright (c) nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/vulnerablecode/
# The VulnerableCode software is licensed under the Apache License version 2.0.
# Data generated with VulnerableCode require an acknowledgment.
#
# You may not use this software except in compliance ... |
#!/usr/bin/env python3
# encoding: utf-8
import re
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from collections import OrderedDict
import torch
import torch.nn as nn
import math
import numpy as np
import time
import os
import sys
import torchvision
#__all__ = ['DenseNet121','DenseNet169... |
from django.apps import AppConfig
class BizcontactsConfig(AppConfig):
name = 'bizcontacts'
|
'''
--- Day 9: Encoding Error ---
With your neighbor happily enjoying their video game, you turn your attention to an open data port on the little screen in the seat in front of you.
Though the port is non-standard, you manage to connect it to your computer through the clever use of several paperclips. Upon conn... |
import os
import subprocess
import unittest
from fs import open_fs
from celery import Celery, group
import magic
from fs.copy import copy_file
from parameterized import parameterized
app = Celery('test_generators')
app.config_from_object('unoconv.celeryconfig')
app.conf.update({'broker_url': 'amqp://guest:guest@local... |
from .base import BaseDocument
import markdown
import html_parser
class MarkdownDocument(BaseDocument):
def __init__(self, path):
self.path = path
def read(self):
self.document = open(self.path, "r")
text = self.document.read()
html = markdown.markdown(text)
return html_parser.html_to_text(html)
def c... |
while True:
try:
string = input()
print(string)
except EOFError:
break |
# Eerst met PCA. Deze resulteert nu in 3 coponenten, waarvoor je dus twee plot nodig hebt
pca = PCA()
pcas = pca.fit_transform(X)
fig = plt.figure(figsize=(15, 8))
ax = fig.add_subplot(121)
plt.scatter(pcas[:, 0], pcas[:, 1], c=color, cmap=plt.cm.Spectral)
ax = fig.add_subplot(122)
plt.scatter(pcas[:, 2], pcas[:, 1], c... |
# Copyright (c) 2019 Dan Ryan
# MIT License <https://opensource.org/licenses/mit>
from __future__ import absolute_import, unicode_literals
import collections
import csv
import io
import pathlib
import sqlite3
import tempfile
import uuid
from typing import Any, Dict, Generator, List, Optional, Set, Tuple, Union
impor... |
import abc
import flask
from flask import jsonify, make_response
from ..app.swagger_schema import Resource, Schema
from ..extensions.audit import AuditLog
from ..logger.app_loggers import logger
from ..swagger import AfterResponseEventType, BeforeRequestEventType, BeforeResponseEventType
class ResourceResponse:
... |
# -*- coding: utf-8 -*-
"""
Module for common converters settings and functions
"""
import os
from config import log, root_directory, DEFAULT_LANGUAGE
def db_get_statistic(models_list):
"""
:return:
"""
log.info("Start to get statistic of imported items:")
[log.info("%s: %s", model.__name__, mode... |
from django.conf.urls import url
from django.contrib.auth.views import logout
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^change_city/$', views.change_city, name='change_city'),
url(r'^parse/$', views.parse, name='parse'),
url(r'^logout/$', logout, {'next_page': ... |
max_n1 = int(input())
max_n2 = int(input())
max_n3 = int(input())
for num1 in range(2, max_n1 + 1, 2):
for num2 in range(2, max_n2 + 1):
for num3 in range(2, max_n3 + 1, 2):
if num2 == 2 or num2 == 3 or num2 == 5 or num2 == 7:
print(f"{num1} {num2} {num3}") |
from typing import Callable, Dict, Tuple, Any
__all__ = ['HandlerResponse', 'Handler']
HandlerResponse = Tuple[int, Dict[str, str], str]
Handler = Callable[[Dict[str, Any], Dict[str, str]], HandlerResponse]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
import sys
# cyheifloader allows specifying the path to heif.dll on Windows
# using the environment variable LIBHEIF_PATH.
from cyheifloader import cyheif
from PIL import Image
from PIL.ExifTags import TAGS
# Print libheif version
print(f'LibHeif Version: {cyheif.get_heif_version()}')
file_name = sys.ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.